Slide 1

Slide 1 text

Jonas Neubert WHAT IS A PLC? AND HOW DO I TALK PYTHON TO IT ? PYCON US 2019

Slide 2

Slide 2 text

PROGRAMMABLE

Slide 3

Slide 3 text

PROGRAMMABLE LOGIC

Slide 4

Slide 4 text

PROGRAMMABLE LOGIC CONTROLLER

Slide 5

Slide 5 text

LC Inside PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside

Slide 6

Slide 6 text

PLC Inside

Slide 7

Slide 7 text

PLC Inside Photo by Annie Spratt on Unsplash https://unsplash.com/photos/Iqwnr00mfQM

Slide 8

Slide 8 text

Photo by Gonz DDL on Unsplash https://unsplash.com/photos/a1Lm99Kkqtg PLC Inside PLC Inside PLC Inside

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

Photo by Zhang JR on Unsplash https://unsplash.com/photos/sCkqeWNGqMw PLC Inside

Slide 11

Slide 11 text

By Dusso Janladde at at Wikimedia Commons (CC-BY-SA 3.0) https://commons.wikimedia.org/wiki/File:Nitro_coaster.jpg PLC Inside

Slide 12

Slide 12 text

PLC Inside

Slide 13

Slide 13 text

Photo by Liesel at Wikimedia Commons (CC-BY-SA 3.0 Unported) https://commons.wikimedia.org/wiki/File:Liesel_28-11-10_642_055-8_im_Bahnhof_Scharfenstein.JPG PLC Inside

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

Official White House Photo by David Lienemann (public domain) https://obamawhitehouse.archives.gov/sites/default/files/image/image_file/V020811DL-0076edit.jpg PLC Inside

Slide 16

Slide 16 text

Official White House Photo by David Lienemann (public domain) https://commons.wikimedia.org/wiki/File:Cities_Sprinter_cab.jpg PLC Inside

Slide 17

Slide 17 text

Photo by Vladimir Kudinov on Unsplash https://unsplash.com/photos/OwWIfjoVkbI PLC Inside PLC Inside PLC Inside PLC Inside PLC Inside

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

PLC Inside

Slide 20

Slide 20 text

Usually not a PLC Inside

Slide 21

Slide 21 text

Photo by Alex D’Alessio on Unsplash https://unsplash.com/photos/sCkqeWNGqMw PLC Inside

Slide 22

Slide 22 text

PLC Inside

Slide 23

Slide 23 text

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:

Slide 24

Slide 24 text

“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

Slide 25

Slide 25 text

This is what a PLC looks like* * once it’s installed

Slide 26

Slide 26 text

“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

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

PLC Programming Demo

Slide 29

Slide 29 text

Ladder Logic | | | DI1 Timer2Done DQ1 Red Light | |------[ ]------|------[ ]----------------------(OUT)---------| | | | | DI2 | | |------[ ]------| | | | | | Timer1Done | | |------[/]------| | | | | OtherBoolVar Timer1 | |------[ ]--------------------------------------(TMR)---------| | | | Timer1Done Timer2 | |------[/]--------------------------------------(TMR)---------| | | Contacts RUNGs HOT rail Neutral rail COILS

Slide 30

Slide 30 text

Ladder Logic Photo of elevator logic by Tom Magliery on Flickr (CC-BY-NC-SA-2.0) https://www.flickr.com/photos/mag3737/306386128

Slide 31

Slide 31 text

Source: https://news.ycombinator.com/item?id=275587 (content edited for length) Ladder Logic — Why?

Slide 32

Slide 32 text

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.

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

Demo 2

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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”

Slide 38

Slide 38 text

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)

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

Example: opcua-client Screenshot from project Readme: https://github.com/FreeOpcUa/opcua-client-gui/blob/c103b3f/README.md the “UA” is important! Previous versions of OPC are Microsoft-only legacy technology

Slide 42

Slide 42 text

Example: opcua-client Screenshot from project Readme: https://github.com/FreeOpcUa/opcua-client-gui/blob/c103b3f/README.md Data and Methods are discoverable in a tree of nested objects

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

? Raspberry Pi is a trademark of the Raspberry Pi Foundation

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

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.

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

? Arduino Community Logo, CC-SA-BY-NC 3.0, available at www.arduino.cc

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

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?

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

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

Slide 53

Slide 53 text

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

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

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.

Slide 56

Slide 56 text

Backup slides for Demo 1

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

No content

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

No content

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

No content

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

No content

Slide 76

Slide 76 text

No content

Slide 77

Slide 77 text

back to slides

Slide 78

Slide 78 text

Backup slides for Demo 2

Slide 79

Slide 79 text

No content

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

No content

Slide 84

Slide 84 text

back to slides

Slide 85

Slide 85 text

Addon slides for (optional) Demo 2c

Slide 86

Slide 86 text

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()

Slide 87

Slide 87 text

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

Slide 88

Slide 88 text

back to slides