 Hello and welcome to PyCon India 2020 Hedrabad stage. Welcome to day one of the conference which is packed with amazing talks and keynotes for all of you, and I hope everyone's having a great time. So let the festivities begin. We have the first talk of the day by Jonas Newbert on Python and Programmable Logic Controllers, a step-by-step guide. Jonas is a software developer and automation engineer from California. Welcome Jonas, over to you. Hello, PyCon India. Also, hello to my cat who just decided to join us, the on-site audience. I'm super excited to be one of the first talks after the keynote. I hope I can get anywhere close to the level of the keynote. The title of my talk is Python and PLCs. Obviously, with a title like that, the first thing you have to do is figure out what is the PLC. So I'm going to do that before I even start to talk or introduce myself. This is a PLC. It's a stock photo. So you can think of a PLC as a type of computing device. We've got, I don't know, smartphones, laptops, gaming consoles, and then there's PLCs. It's a class of device that can do computation. If you ever find a computing device and you're not quite sure if it's a PLC or not, if it has lots of colorful wires coming out of it, it probably is one. PLC stands for Programmable Logic Controller. And there's actually a piece of trivia that I only learned quite recently, which is that back in the 1960s, when PLCs were first invented, they were called PCs for Programmable Controller. There wasn't really any other Programmable Controller around, so that was a fine name. And of course, then in the 80s, the personal computer became really popular. Everybody called that PC and the people who were doing Programmable Controller stuff were like, that doesn't work. We have to find out, like we have to find a new name. Let's stick a word in the middle. Maybe like Programmable, I don't know, Logic Controller. And that's where this acronym PLC was actually coined. The story does raise a question. Like if these things have been around since the 1960s and they're apparently common, like, where are they? We can't see them anywhere in the real world. And the answer is that they are hiding in industrial settings. They are often used in factories. If you walk around a factory floor, you might see electrical panels like this one. And quite often, there would be a PLC hiding in there, like this example for the window-tinting machine or the circuit board assembly machine. They're also in the built environment. If you go to a theme park, PLCs might be controlling the rides in many buildings. They control the elevators, the escalators. And the other common example that gets used quite frequently is oil platforms where PLCs control the flow of oils and things through all the pipes and all that stuff that's involved in drilling for oil. The operating principle, like what's going on in PLCs, is relatively simple. Basically, you have sensors that are wired up through electrical signals to the PLC. And those electrical signals might be something like if you're in an elevator, you press the button to signal which flow you want to go to. And that generates an electrical signal that travels to the PLC and becomes a variable there. Similarly, if you stick your arm into the closing door of an elevator, you are breaking a light curtain, which is another sensor that sends an electrical signal. And again, this becomes a variable in the PLC. Then remember, it's called a programmable logic controller. So somebody programmed that PLC, in the case of the elevator, to have logic that says stop closing the door if there's an arm in the way. So this logic gets executed, some output variables come about, they get converted back into electrical signals, and they get sent to the actuators. So the elevator, whatever the motor or the thing that's closing the door, might get a signal to say stop, or the display that tells you which flow you're currently at. That might be controlled by a PLC, or for example a little ding sound that comes up sometimes when you arrive at the floor just before the door opens. That would also be an output from the PLC. Similar example, oil platforms, the inputs there would be pressure sensors and flow sensors, and the outputs would be valves that control the flow of liquid. All right, we've taken care of that. Everybody now knows what a PLC is, so let's start the actual talk. First slide, as usual, the sort of introduction. My name is Jonas. I'm a software engineer, automation engineer. I work in the biotech industry. So what that means is that I write software that controls robots that do science. And I'm from Germany originally, but I now live in Oakland, California, which means that right now the time is 12.55 a.m. So my big challenge for today is just to stay away to the end of the talk sessions. And honestly, right now I'm not quite sure if I will make it, but I'll try. Anyway, why am I sort of coming halfway around the world to give you a talk about Python and PLCs? It's a bit of a long story, but the gist is I've been giving talks at Python conferences about industrial automation topics for the past few years. It's something I'm really interested in. Last year, I gave a talk at Python US and it was very high level and introduction to what are PLCs? What can you do with them? What can you do with them as a Python developer? What libraries are available? So high level concept. And something really interesting happened after the talk went up on YouTube. I suddenly started getting a lot of very different questions that were highly specific like people working with Python and PLCs who got stuck on a certain step or weren't quite sure which library to use or how to use it. And like 90% of those came from India. So I started asking some questions and I found out that apparently in India it's somewhat more common for Python developers to encounter industrial equipment like PLCs. And apparently it's especially common in universities that class projects or team projects involve a software engineering component which you might do in Python and an equipment component which might be a PLC. And that's why I got all these questions. So I figured, well, why not go to the place where all these good questions are coming from and give a talk about PLCs there? And that's what I'm doing today. So the plan here is to give a bit of a more hands-on practical example of how to get started to address some of those questions that I've been receiving. So we've already taken care of the intro part of the talk. We know what a PLC is. Part one will be a mini tutorial. And what we'll be doing is, I'll be using this PLC that I have here in my home setup. We'll program it to blink this traffic light. At the start it's gonna be blinking red one second on, one second off. And after that we'll be using the laptop with Python to make the PLC changes behavior so that this is more of a blinking red but instead yellow or green and so on. The second part of the talk after we're done with the demo, I am calling it the FAQ section. Basically I'm trying to address some of those questions that I've been receiving since my previous talk and also some of the common stumbling blocks that I encounter when I work on PLC projects. The link where you can follow along with the slides if that's what you wanna do on the screen here, I also posted that in Hopin. If you want to contact me of course do so and so they pop in on these chat platforms you're using at this conference. Or if you watch this later on YouTube you can ping me on the internet. I'm pretty active on Twitter or by email on the two methods I prefer. But let's dive right in. Part one, the mini tutorial, the blinking traffic signal. We're basically gonna go from Xero to having the laptop talk Python to the PLC. There will be six steps. And the first one is that we just have to figure out what kind of PLC are we using. And I'm seeing that on the live stream at least mine the slides are lagging a little bit behind so the real slide will come in a second. So the step one, figure out what PLC you're using. Mine here, if I just look here actually has a model number on it. It says P1 540 and I purchased it from a manufacturer called Automation Direct. The reason this is important is that there are about I would say like 50 brands of PLCs that you can currently buy in the world. Some are very popular and some are a little bit more niche. But each one is slightly different. Like the naming conventions are different. Like some numbering thing is different. Maybe the types of protocols supported and how they are supported might differ. So it's pretty important that as a first step you figure out what it is. You get the documentation for the PLC that you're using and maybe some of the training material and just get sort of the lay of the land for what the device is that you're working with. One of the things you'll find out is how to connect to it. And that's step two. We have to establish some kind of connection to the PLC. Now I'm using an ethernet connection today because I purchased a PLC that has an ethernet connection. Some others use a serial port protocols you know RS232 or something like this. So do whatever is right for your setup obviously. In my case I connected an ethernet cable to the PLC. I connected that to this Netgear router here. There's another ethernet cable that goes straight to my laptop. And then I configured the PLC to have an IP address on my local network which is 192.168.1.9. And my laptop has a neighboring IP address and I put the subnet masks in and all this good stuff. And then just before the talk I did a quick check and then just did a ping from my laptop and it worked. So that's obviously step one. We have to have connectivity. Sorry, that's step two. Going to step three now. We have to program the PLC to do something because remember it's a programmable device. When it comes from the factory, there's nothing on it. It's like somebody has to tell it what this logic is. We're expecting to execute on there. You'll be using vendor software for that. So what that means is it's not like Python. You don't get to pick your own text editor. And in fact, so I'm going to switch to this vendor software that I have to use to program this PLC just to show you what that looks like. But a quick warning here. When I switch over to that other program, you'll see a non-Python language. And I know this is a Python conference so if this is too much, cover your eyes for a minute. But it's actually a pretty cool thing what we're gonna see. It's a language called ladder logic. It's a graphical programming language. It's super common in the world of PLCs for programming. I'm using it in the example that's coming up. And I don't expect you to understand everything that's going on. I will, in fact, I will point out a couple of specific things. So let's do that. I'm just going to switch over to this program. And now this little delay that we're having might be a problem. So I'm just looking at my screen where I see the stream. But in the first row that's gonna come up on the screen in the second, you'll see that a variable called blink interval millisecond gets used. And that's a millisecond value for how fast you want to blink. And the code here, it does something sort of not very important. It scales it to an internal value. Lines two and three are timers that basically, one timer for how long the light will be on, one timer for how long it will be off. And then the final line at the bottom here we will see another variable called the blink color. And blink color drives which ones of the output signals will be energized. So if blink color equals one, the red light will be blinking. If blink color equals two, the yellow light will be blinking. And if blink color equals three, green light will be blinking. So the takeaway here is there are two variables that play blink interval milliseconds and blink color in those other ones we care about. In fact, I have already programmed the PLC so I'm gonna switch this to running. And in the video, you'll now see my traffic signal blinking, which brings us to step four. But first, I should point out steps one through three might be information gathering in your situation. What that means is it's usually not the software developer's job to do those steps. You usually end up in a situation where somebody else has already installed a PLC in a factory, for example, they've already put a program on, they've already figured these things out. I did include them because maybe your situation is different, maybe your university, you just get that stuff given. And in those situations, you might actually have to do some of this ladder logic programming yourself and you have to figure these things out. In most organizations where you're at, whether that's university or you're working at a company or your company is sending you to a customer, the brand of PLC is already fixed because most companies only work with one vendor of PLC so that they don't have to do training for multiple products. Whichever situation you're in, steps one, two, three, you either did them or you've figured out what somebody else did, step four is where you are getting involved. And what's happening here is that you have to assign the PLC program variables to Modbus registers. Now there's new word items, right? To Modbus, so let's talk about that real quick. Modbus is a technique and a protocol that's almost as old as PLCs are and it's a way for PLCs to share the content of variables in their code with any other device on the network. It could be another PLC or a server or my laptop, which is what we're doing today. You can imagine what's happening inside the PLC to be that the processor of the PLC does two things. In fact, in modern PLCs, it's usually actually two different cores that are doing this. One half of the job is to execute this ladder logic program. It's just over and over and over. Go to the top, work through the bottom, start at the top again. That's one half of what the PLC does and that's ultimately what makes this traffic that link right now. The other half of it is the part of the processor that handles all the network traffic. Like when I send a ping to the PLC, it responds. And another thing it does is that it maintains this long list of registers where it can store values and other devices on the network can access them with read and write. And these registers are the Modbus registers. So the way this is set up is that the ladder logic synchronizes with this table of registers what the variable values are. And any device on the network can then ask questions about their values. The terminology in the Modbus protocol is that in this case, the PLC is the slave and my laptop is the master. And apparently that was super cool terminology for a computer communication protocol in the 60s. Honestly, to me, the nomenclature of client and server makes more sense. The PLC is the server because it holds the truth of what these variables or these registers are and clients such as my laptop will later be able to interact with them. Of course, I told you that I want my variables to be in Modbus registers. I haven't told the PLC yet. So that's our next job. And for that, I go back to my programming software. This actually has a list. Actually, let's not do that yet. Let's first look at how the Modbus protocol works. This is also important. So what are these registers? We basically got two types of data. We've got very weird terminology. They didn't call it Booleans and floating points and such back then. The gist is you can either have one bit values or 16 bit values. And we're dealing with numbers. We want milliseconds and one, two, three for the colors. So we're going to use 16 bits and we want read and write. So therefore, we're going to use a holding register. In fact, we're using two holding registers because we care about those two variables that I pointed out earlier. The first variable that we want to make available by our Modbus on the network is the blink color. We're going to put this into our first holding register using the table that I screenshotted from Wikipedia. We find out that the Modbus address needs to be 1 in the 40,000 range. And of course, Python starts indexing at 0. So in Python, we're going to refer to the same Modbus register as 0. And for the blink interval millisecond, the plan is to stick this into the second holding register of the Modbus system. So the Modbus address will be 2 in the 40,000 range. And in Python, we'll refer to it as 1. So now we're going to the PLC and set this up. So the PLC actually has this very convenient list of all variables that we use. And blink color and blink interval millisecond are right at the top. In fact, you can see the initial values, the default values are 1 for blinking red and 1,000 for being on the second, not the second. So that's what it's doing. And I'm going in here and use the suggested values on the PLC to actually assign it these Modbus register addresses. So we told the PLC now that we wanted to share the value of those variables in those Modbus registers. We actually have to really tell the PLC this. I'm stopping it, reprogramming it. I'm telling it, hey, just going to change. You're supposed to share these variables with the world. It's programming it. And when it's done, it's going to start blinking again. Here we go. Which means we can now finally start accessing these registers, these values that we want to tinker with over the network. And the way we do this is that we use Python for it. So we now need a Python implementation of the Modbus protocol on the laptop. So that's the next step. You actually, to do this, have a whole list of options. This is a review of all the actively maintained Modbus implementations I could find on PyPI. PyModbus is by far the most popular. Lots of stars, and GitHub, and downloads, and all that good stuff. I am actually using the third one on the list, PyModbus TCP. And the reason is just that it has a much simpler API and has some nice debug output that makes the demo more interesting. Whatever you do, here are some criteria that might matter for you. Some of them support ethernet, Modbus only. Others support serial port, Modbus only, and such things. Maybe the license matters. So you can pick yours from this list. Interestingly, the second one from the bottom is actually an interesting one, because it's a Modbus implementation in MicroPython. So you can actually use the Modbus protocol when programming microcontrollers with Python, which is like this somewhat new thing that you can do. Anyway, just as we're using PyModbus TCP, and once we pip install that, we will do some Python to interact with it. And because I'm doing good on time, I'm going to do this as a live demo. So pip install PyModbus TCP. I've already installed it. So just telling me this, I open the Python channel, run this auto-complete. And from the module that we just, from a package that we just installed, we get the Modbus client. We instantiate the client. And this is where we have to tell our client here what the IP address of the PLC is. And that's why I told you earlier in so much detail what the networking is. I also said that ebook flag and an auto-open flag. And this is just to make the demo more smooth and interesting. This is not essential. Right. PLC is sharing the variable values and the Modbus registers. I've got a client to talk to the PLC and Modbus. The first thing I'm going to do is to check what's in the first holding register. And that should be the value of 1, because it's blinking red. So let's do that. Read, holding, registers. And we only want the first one, which is 0. So you can actually see, this is the content of the Modbus protocol, what it sent and what it received. And what you basically see here is it's a very simple protocol, because there are barely any bytes getting sent back and forth. And we asked it for what's in the first holding register, and that comes to value of 1. That makes sense. It's blinking red. How about we change that? Let's write a register. Let's write the 0 with 1. And let's set it to 2 instead. And it immediately stops blinking in yellow. So what happens is that my laptop sent a message to PLC to change the value of this register. Inside the PLC, the ladder logic immediately picked up the new value of this variable. And it sets the electrical signals according to make yellow blink. And of course, we can do the same with green. And then we can go back to red. And then we can do the same with the second holding register, which, remember, that's the number of milliseconds that it's on and off. And currently at 1 second to 1,000 milliseconds, I'm going to put it at 500. And I was blinking twice as fast. In fact, that's making me a little bit nervous, so I'm bumping it up to 2 seconds. And now it's lower. All right, I do realize this is not rocket science. This is like the hello world of this setup. I showed this to you because it gives you these six steps that you can follow like a recipe, like some kind of checklist. Even if you have a different kind of PLC, or you're using a serial port instead of Ethernet, or you use a different communication protocol, you can use this as a guide how to get started with your PLC and start communicating with it from Python. Whenever I give these kind of instructions or talks on this topic, the very first question that I get, and that's what's launching us into the second part of this FAQ section, the very first question that I get is, do I have to do this ladder logic stuff? Can I just program my PLC in Python? The answer is no. And there are two explanations. One for people who follow the rules and one for people who don't follow the rules. Let's do the first one first. There's a standard, IEC 61131, which defines in a great amount of detail what a PLC is and what it needs to be able to do. That standard has a list of languages that you can use to program PLCs and Python isn't on it. I get it, you might say, well, it's an old standard, let's break the rules, let's program it in Python anyway. There's a reason Python is not on there. One defining trait of PLCs is that they execute the logic that's on them in real time. Now, real time often gets misunderstood as meaning very fast. And while that is often true, it's very fast. Real time actually means that it's predictable. So every time this ladder logic program gets scanned and then scanned again and again and again, the execution time of every single instruction in there is almost the same with a very small amount of variance. And that's important because when you're in that elevator, you stick your arm into the door and you change the signal that comes from the light curtain. You don't want the PLC to take a second to respond because it's also getting like some modbus commands on the network and it was busy, you know, doing multi-threading or whatever. You want it to stop immediately and not crush your arm. And PLCs tend to be used in applications where this predictability and this real-time nature is very important. And Python is not really a language made for that. Like by default, it's certainly not a real-time language. Maybe you could make it somehow, but it's not. And that's why Python is not a language for programming the PLC itself. This slide shows what my mental model is for understanding what's meant to be done on the PLC and ladder logic and what's meant to be done in Python. I think of it as two controllers. The inner loop is running on the PLC. It's sort of like milliseconds for iterations, maybe faster. It handles the interface with the real world of the sensors and actuators. It's doing the timing critical and safety critical things. And you might actually not be able to change the logic because there's so much paperwork and regulations preventing you from doing that, just to ensure the safety of whatever this PLC is controlling that it's basically part of the machine. That's the inner control loop. And then there's the outer one. And that's the one that might be running on the server or in the cloud or in a laptop. And that only gets to tweak certain parameters of what's happening inside this logic of the PLC. Such as in our case, we got to tweak the color and the blinking interval and nothing else. We never changed the structure of the ladder logic that's programmed in the PLC. And the reason Python is a really good choice for this outer control loop is that you can tap into the rest of the Python ecosystem. You can do machine learnings, Keras, and Pandas, and analyze data, connect to databases. Ping API has changed the color of the blinking based on the weather in your favorite time or something like that. All Python makes is very easy, and that's why Python is a good fit here. I should point out, I made one of the arrows on here is not filled, it's sort of like just an outline. In most situations, when you interface to PLC, it's from Python code, you only ever read. You never write. When you only read, that's really what's meant by these buzzwords like, you know, there's IoT, and then there's industrial IoT. So the industrial internet of things or industry 4.0 or condition monitoring, like these are basically buzzwords that say, somebody connects to a PLC, just reads all the values all the time, stores it all in a database, and then does analysis on it. That's basically what industrial IoT is, and that's what happens most of the time. It's relatively rare, I think, that you actually change the values of the PLC, but I figured I'd show you in the demo anyway, so that your experts can pull that trick when it's needed. I'm heading towards the end of the time here, so let's speed up. Second question, is Modbus the only PLC communication protocol? It's not, not by far. There's a Wikipedia page that lists all the automation protocols, and I mean, there's gotta be 100 on that list. They fall into two buckets. The first category are the ones, protocols that you can run on standard Ethernet networking hardware, like the one that you plug your laptop in to get on the internet. And then there's the other group of protocols that require specialized hardware. For the first category, most of those protocols, you find the Python implementation. You just take the name of the protocol, you put it into that PyPI search box, and you find one or more implementations of it. And if you check on some of my previous talks, if you wanna look them up on the internet, I sometimes have a review slide in there that gives you an overview of what these protocols are about Python implementation success. Another question, help. My Python script won't connect to the PLC. I do realize it's not a question, but it happens a lot, so I wanted to include it here. Many problems you encounter when working with PLCs aren't actually PLC problems, they are networking problems. So one thing that's pretty important is that you make sure you know the basics of your networking situation. Know all the IP addresses involved, all the port numbers for the protocols you're working with, understand how the subnet masks work, know what firewalls are installed, and also keep in mind, many PLCs are not connected to the network at all. They're kept off the internet and even off the office network to protect them from hackers. And it might look like they're connected. It might be plugged into the same switch, but the switch might be configured to not pass traffic from your laptop to the PLC. So these are all things I've run into before, so make sure you understand the networking situation before you try sending commands over the network. Another question is the Raspberry Pi question. Why can't you do this with the Raspberry Pi? Raspberry Pi can do blinking of lights. And the answer is out of the box, devices like the Raspberry Pi just don't meet the requirements that PLCs are designed for. They don't have the real-time code execution. They might not survive in the type of temperatures or humidity that PLCs are installed in, or in factories you often deal with electromagnetic interference. You can modify Raspberry Pies to meet those criteria, but then it looks like a PLC and it also costs as much money. So if you have those requirements that weren't using a PLC, you have to use a PLC. If you don't, you don't. Second to last question, can I simulate a PLC because you might be interested in working on this stuff? He's on a story to interrupt you, but you have just a minute to go. So if you can quickly wrap up, that'll be great. Yeah, that's the plan. I've got a minute and 20 seconds on my timer and I'm gonna be done in that time. So yeah, can I simulate a PLC? You might want to do that because buying a PLC is expensive, it's industrial. You might not even be able to purchase it at all because they only sell to companies. So I prepared this slide here for you. I'm not gonna go through it, you can screenshot it. This are a couple of options you have for trying out ladder logic and some of those other things without actually having a physical PLC for yourself. And at the bottom, I have a link to a Reddit thread where lots of people collect really good material for getting started with PLC programming. And finally, this is a message I get a lot. Can you help me with my PLC question? Two answers to that. The first one is I'm not a PLC expert. I've worked with a few PLCs on a few simple projects, but in most cases, I actually cannot help you. But if you email me or anybody else or you try to ask on the forum or ask Google, make sure to include the relevant information that makes the other person able to answer your question. What brand of PLC are you using? What program do you use to program the PLC? What communication protocol? Maybe include a Python script to illustrate what you're trying to do even if it doesn't work. And if you can, if it's not in the confidential setup like at work, maybe take a photo or do a sketch of what it is you're doing. That will really help the other person understand what you're trying to do and maybe it will be able to answer your question. And with that, I'm on my last slide right at the end of my time. I'm gonna be available on, you know, Sula and Hopin to answer your questions or if you watch this later, you can find me on Twitter with my contact details on this slide. Thank you very much. Thank you for the amazing talk, Jonas. And thank you for joining us even at this odd time.