Upgrade to Pro — share decks privately, control downloads, hide ads and more …

What is a PLC? And how do I talk Python to it?

What is a PLC? And how do I talk Python to it?

Presented at Pycon US 2019

Jonas Neubert

May 03, 2019
Tweet

More Decks by Jonas Neubert

Other Decks in Technology

Transcript

  1. Jonas Neubert WHAT IS A PLC? AND HOW DO I

    TALK PYTHON TO IT ? PYCON US 2019
  2. PLC Inside PLC Inside Photo by Tyler Casey on Unsplash

    https://unsplash.com/photos/ficbiwfOPSo PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside
  3. Photo by Sebastian Terfloth at at Wikimedia Commons (CC-BY-SA 3.0

    Unported) https://commons.wikimedia.org/wiki/File:ICE_3_Oberhaider-Wald-Tunnel.jpg PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside
  4. Photo by Daniel Åhs Karlsson at at Wikimedia Commons (CC-BY-SA

    3.0) https://commons.wikimedia.org/wiki/File:OTIS_GEN_2_Comfort_Roof_Taket_(Daniel_Åhs).jpg PLC Inside
  5. Table of Contents What is a PLC? (and how does

    one program a PLC?) How do I talk Python to it? But what about RaspberryPi? https: // jonasneubert.com / pycon2019 @jonemo Q: What was THE acronym “PLC” for again? A: Programmable Logic Controller slides: twitter:
  6. “Compact” Fixed form factor Photo of Siemens Logo by Stehfun

    at Wikimedia Commons (CC-BY-SA 3.0 Unported) https://commons.wikimedia.org/wiki/File:Siemens_Logo.jpg Photo of Beckhoff CX by Beckhoff Automation GmbH at Wikimedia Commons (CC-BY-SA-3.0-DE) https://commons.wikimedia.org/wiki/File:Embedded-PC_Beckhoff_CX1020.jpg This is what a PLC looks like* “Modular” Backplane with fixed number of slots “Expansible” Infinitely* stackable modules * when it’s new
  7. “CPU” DI 4-20mA DI 24V AI 5V DQ 24V Motion

    Control Serial Port Power Supply PLC with 6 modules Quick Intro to “Field Devices” Sensors Actuators
  8. The Input-Process-Output Cycle Step 1: Input Scan Step 2: Program

    Scan Step 3: Output Scan Read process variables from Field Instruments into PLC memory Create “Process Image In” (PII) Execute application program (this is the Programmable Logic!) Creates “Process Image Out (PIQ)” STEP 2 is the one we have control over! Read “Process Image Out” (PIQ) Set output signals
  9. Ladder Logic | | | DI1 Timer2Done DQ1 Red Light

    | |------[ ]------|------[ ]----------------------(OUT)---------| | | | | DI2 | | |------[ ]------| | | | | | Timer1Done | | |------[/]------| | | | | OtherBoolVar Timer1 | |------[ ]--------------------------------------(TMR)---------| | | | Timer1Done Timer2 | |------[/]--------------------------------------(TMR)---------| | | Contacts RUNGs HOT rail Neutral rail COILS
  10. Ladder Logic Photo of elevator logic by Tom Magliery on

    Flickr (CC-BY-NC-SA-2.0) https://www.flickr.com/photos/mag3737/306386128
  11. Ladder Logic Still the most popular language for programming PLCs.

    Common denominator across all PLC brands. Part of curriculum for most Automation Engineering degrees. A language optimized for debugging, not writing.
  12. Alternative Languages - LD: Ladder diagram - FBD: Function block

    diagram, graphical - ST: Structured text, textual - IL (deprecated):Instruction list, textual - SFC: Sequential function chart , has elements to organize programs for sequential and parallel control processing, graphical. - C/C++ - Matlab/Simulink - Custom graphical wiring diagram tools IEC-61131-3
  13. Process Data Process Parameters Sensor Signals Actuator Signals The Two

    Control Loops of “IIoT” Field Devices PLC Logic Python Code “Inner Loop” “Outer Loop” milliseconds per iteration interfaces to the physical world timing critical & safety critical logic release process might be regulated minutes to months per iteration interfaces to databases and APIs optimization & customization regular software release cycle
  14. Vendor/Brand Specific Protocols Protocol Ethernet/IP S7 ADS DirectNet DF1 PCOM

    [unnamed?] Vendor/Brand Allen Bradley Siemens S7 Series Beckhoff Koyo (Autom. Direct) Allen Bradley Unitronics Fatek Python libraries pycomm python-snap7 chwiede.pyads bfabio.pyads, adshli, pyads clickplc df1 pcom fatek-fbs-lib ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ RS-232/485 Ethernet TCP/IP CAN bus see also: my spreadsheet of PLC brands and products and “List of PLC Manufacturers“ on Wikipedia Best Case Scenario: You’re using one of these PLC BrAnds Otherwise: go to next slide
  15. No Python support: CC-Link IE, Ethernet Powerlink, PROFINET, Ethernet/IP SERCOS

    III. Utility libraries like rawsocketpy and dnet are handy for non-TCP/IP level networking. “Open Standard” Protocols Modbus TCP Modbus ASCII/RTU pymodbus, pyModbusTCP, cpppo pymodbus, MinimalModbus ✓ ✓ ✓ RS-232/485 Ethernet TCP/IP CAN bus Protocol Python Packages Ethernet/IP (TCP) Profinet (TCP) OPC-UA pycomm, cpppo GH: devkid/profinet opcua, asyncua, opcua-client (GUI), opcua-webclient ✓ ✓ ✓ ✓ ✓ ✓ EtherCAT pysoem ✓ ✓ Profibus-DP CANopen SAE J1939 OPC Windows OLE ✓ ✓ pyprofibus canopen j1939 OpenOPC Many more with no Python support. Standard library sockets and ctypes are your friends! Modbus is universal 40 years old this year! see also: “List of Automation Protocols“ on Wikipedia Ethernet based “Fieldbus” standards Many more with no Python support. Many require custom hardware or cables. Other TCP/IP based standards “Office-to-Machine networking”
  16. Example: pyads import pyads plc = pyads.Connection('10.23.19.3.1.1', pyads.PORT_SPS1) plc.open() plc.read_by_name('GLOBAL.RED_ON',

    pyads.PLCTYPE_BOOL) # → False plc.write_by_name('GLOBAL.YELLOW_DURATION', 300, pyads.PLCTYPE_INT) @plc.notification(pyads.PLCTYPE_BOOL) def callback(handle, name, timestamp, value): print(f"Notification: {name} has new value {value}") plc.add_device_notification('GLOBAL.PEDESTRIAN_WAITING', callback)
  17. Example: pyads import pyads plc = pyads.Connection('10.23.19.3.1.1', pyads.PORT_SPS1) plc.open() plc.read_by_name('GLOBAL.RED_ON',

    pyads.PLCTYPE_BOOL) # → False plc.write_by_name('GLOBAL.YELLOW_DURATION', 300, pyads.PLCTYPE_INT) @plc.notification(pyads.PLCTYPE_BOOL) def callback(handle, name, timestamp, value): print(f"Notification: {name} has new value {value}") plc.add_device_notification('GLOBAL.PEDESTRIAN_WAITING', callback) Reference Variables by Name
  18. Example: pyads import pyads plc = pyads.Connection('10.23.19.3.1.1', pyads.PORT_SPS1) plc.open() plc.read_by_name('GLOBAL.RED_ON',

    pyads.PLCTYPE_BOOL) # → False plc.write_by_name('GLOBAL.YELLOW_DURATION', 300, pyads.PLCTYPE_INT) @plc.notification(pyads.PLCTYPE_BOOL) def callback(handle, name, timestamp, value): print(f"Notification: {name} has new value {value}") plc.add_device_notification('GLOBAL.PEDESTRIAN_WAITING', callback) Subscription to value changes
  19. Observations from reviewing 40ish Python packages Lots of recent activity:

    - 11 packages first published within the last 12 months - 24 packages with new releases within the past 12 months Many Python 3-only packages, few Python 2-only packages Most activity in Europe* * based on supported brands and package maintainer website information Overlap with the much more active home automation community e.g. homeassistant has support for two PLC brands built-in
  20. Things you get from a PLC that you don’t get

    from a . Hardware Works in crazy environments EM interference protection ESD protected, isolated I/O 24VDC power, DIN rail mount Expected life measured in decades Supply chain guarantees Safety certifications Software (c.f. IEC-61131-3) Realtime guarantees PID control and Motion Control Zero-downtime code changes Industry-standard programming languages Support for common fieldbus protocols
  21. But maybe the RaspberryPi is a PLC? - CODESYS for

    RaspberryPi (codesys.com, €50) Cross-platform IEC 61131-3 editor and runtime. The editor is free, the RaspberryPi runtime is €50. - OpenPLC (openplcproject.com, free) A IEC-61131-3 editor (written in Python) and runtime for various targets, including RaspberryPi - PiLC (bues.ch/cms/automation/pilc.html) Runs the awlsim PLC simulation software (an open source Python package!) on RaspberryPi. awlsim implements a subset of the languages and features of Siemens’ STEP 7.
  22. But maybe the RaspberryPi is a PLC? Several products add

    a protected power supply, realtime clock, isolated I/O pins, fieldbus protocol adapters, enclosures, etc. - PiXtend (www.pixtend.de, €165+) Extension board for RaspberryPi, communicates via SPI Adds one or two Atmel controllers to manage I/O pins Fixed set of digital and analog I/O, relays, CAN bus, RS-485 Programmable with CODESYS - Andino (andino.systems, €135+) - RevolutionPi (revolution.kunbus.com, €212+) Custom PCB with RaspberryPi Compute Module Raspbian OS with realtime patch Expansion modules for I/O, many fieldbus protocols Programmable with logi.CAD3 Revolution Pi product photo © Kunbus GmbH PiXtend product photo © Qube GmbH, source: https://www.pixtend.de
  23. But maybe the Arduino is a PLC too? - Controllino

    (www.controllino.biz, €135+) Arduino-compatible custom board Fixed set of digital and analog I/O, relays, RS-485 Modbus server for communications Programmable with logi.CAD3 or Arduino IDE - SoapBox Snap for Arduino (soapboxautomation.com, free) A free ladder logic editor for Windows, and a corresponding runtime for Arduino. Open source project, but sadly appears to be unmaintained since 2016. Controllino product photo © CONELCOM GmbH
  24. Hey Jonas, time is up and we all want to

    get lunch. What should I do next if I want to learn more about this PLC stuff?
  25. Jonas’ PLC Shopping Guide How much it’s going to cost,

    approximately If you want to do this: Try out ladder logic Try software the pros use Program your like a PLC Buy a cheap “real” PLC Hack some real gear Learn about the market leaders Contribute to a Python project Own a traffic signal Then take a look at that: OpenPLC, plcfiddle.com List of free software in appendix Codesys for , OpenPLC Automation Direct, Siemens Logo! Ebay1, industrial surplus sales Allen Bradley (US), Siemens (Europe) FreeOpcIUa, package list in appendix County/state surplus auctions, Ebay 1 On Ebay, this is where you want to look: Business & Industrial → Automation, Motors & Drives → Control Systems & PLCs → PLC Processors free free $70 $200 $500 — — $250
  26. What’s the URL for these slides again? https://jonasneubert.com/pycon2019 Want to

    work with me? https://www.zymergen.com/careers/ Watching this on Youtube? The best ways to contact me are Twitter (@jonemo) and email ([email protected]) Open Space for questions, errata, and playing with PLCs and traffic signals Friday (today!) 3pm, Room 21 #PyConOpenSpace http://pycon.us/os My last slide
  27. Free PLC programming software Software packages that support multiple brands/platforms

    Codesys — editor is free download, addons and device-specific runtimes are not free Inforteam OpenPCS — same concept and pricing model as Codesys, but smaller market share logi.CAD3 — base edition is free download OpenPLC — open source Vendor/brand specific software platforms Beckhoff Twincat — trial license may be renewed indefinitely for personal use ABB — free basic version Vendors whose programming software is generally free: Automation Direct, Bedrock Automation, Phoenix Contact, Unistream. Generally, smaller brands offer cheap or free software while market leaders use software as a revenue stream. Avoid over-simplified “basic editions” that don’t resemble the full version or don’t use IEC-61131-3 languages, for example Allen Bradley’s “Connected Components Workbench”. Software with free trial versions that have reasonable limitations Siemens TIA Portal — 21 day free trial, requires registration Schneider Electric EcoStruxure Machine Expert — 42 day free trial Panasonic — limits program complexity, no time limit Keyence — only opens 50 times
  28. List of Python packages mentioned in this presentation • pycomm

    • python-snap7 • chwiede.pyads • bfabio.pyads • adshli • pyads • clickplc • df1 • pcom • fatek-fbs-lib • pymodbus • pyModbusTCP • cpppo • pymodbus • MinimalModbus • devkid/profinet (Github link, no PyPI project) • opcua (part of the FreeOpcUa project) • asyncua (part of the FreeOpcUa project) • opcua-client (part of the FreeOpcUa project) • opcua-webclient • pysoem • pyprofibus • canopen • j1939 • OpenOPC • rawsocketpy • Dnet From the standard library: • socket • ctypes
  29. Forums and Online Communities https://reddit.com/r/PLC/ — surprisingly friendly community, by

    Reddit standards https://control.com https://www.mrplc.com Books Sorry, I couldn’t find any books on the topic that seemed worth their price tag.
  30. from pymodbus.datastore import ModbusServerContext, ModbusSlaveContext, ModbusSparseDataBlock from pymodbus.server.asynchronous import StartTcpServer

    from datetime import datetime def boolfmt(label: str, boolvar: bool): return f"[ {label} ]" if boolvar else "[ ]" class MyDataBlock(ModbusSparseDataBlock): """A custom data "storage" class that logs all incoming requests""" def setValues(self, address, values): super().setValues(address, values) now = datetime.now().strftime("%H:%M:%S.%f") g, y, r, h, f, w = [boolfmt(k, v) for k, v in zip("GYRHFW", values)] print(f"{now} {g} {y} {r} {w} {f} {h}") def main(): block = MyDataBlock([0]*100) # storing 100 words store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block) context = ModbusServerContext(slaves=store) StartTcpServer(context, address=('0.0.0.0', 502)) if __name__ == "__main__": main()
  31. import socket HOST = "192.168.1.9" # IP address of the

    PLC PORT = 50505 # Arbitrary port I used in Ladder Logic with socket.socket() as s: s.connect((HOST, PORT)) s.sendall(b'REQ') print(s.recv(1024)) # → ACK s.sendall(b'DISCO') print(s.recv(1024)) # → ACK