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

    View full-size slide

  2. PROGRAMMABLE

    View full-size slide

  3. PROGRAMMABLE
    LOGIC

    View full-size slide

  4. PROGRAMMABLE
    LOGIC
    CONTROLLER

    View full-size slide

  5. LC Inside
    PLC Inside
    PLC Inside
    PLC
    Inside
    PLC Inside
    PLC Inside

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  8. 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

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  11. 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

    View full-size slide

  12. 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

    View full-size slide

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

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  16. 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

    View full-size slide

  17. Usually not a
    PLC Inside

    View full-size slide

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

    View full-size slide

  19. 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:

    View full-size slide

  20. “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

    View full-size slide

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

    View full-size slide

  22. “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

    View full-size slide

  23. 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

    View full-size slide

  24. PLC Programming Demo

    View full-size slide

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

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  28. 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.

    View full-size slide

  29. 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

    View full-size slide

  30. 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

    View full-size slide

  31. 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

    View full-size slide

  32. 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”

    View full-size slide

  33. 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)

    View full-size slide

  34. 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

    View full-size slide

  35. 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

    View full-size slide

  36. 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

    View full-size slide

  37. 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

    View full-size slide

  38. 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

    View full-size slide

  39. ?
    Raspberry Pi is a trademark of the Raspberry Pi Foundation

    View full-size slide

  40. 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

    View full-size slide

  41. 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.

    View full-size slide

  42. 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

    View full-size slide

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

    View full-size slide

  44. 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

    View full-size slide

  45. 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?

    View full-size slide

  46. 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

    View full-size slide

  47. 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

    View full-size slide

  48. 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

    View full-size slide

  49. 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

    View full-size slide

  50. 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.

    View full-size slide

  51. Backup slides for Demo 1

    View full-size slide

  52. back to slides

    View full-size slide

  53. Backup slides for Demo 2

    View full-size slide

  54. back to slides

    View full-size slide

  55. Addon slides for (optional) Demo 2c

    View full-size slide

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

    View full-size slide

  57. 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

    View full-size slide

  58. back to slides

    View full-size slide