├── LICENSE ├── PythonCLX_PIDSimulator.pyw ├── README.md └── requirements.txt /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Destination2Unknown 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /PythonCLX_PIDSimulator.pyw: -------------------------------------------------------------------------------- 1 | import threading 2 | import time 3 | import random 4 | import customtkinter as ctk 5 | import numpy as np 6 | import matplotlib.pyplot as plt 7 | from matplotlib import animation 8 | from scipy.integrate import odeint 9 | from pylogix import PLC 10 | 11 | 12 | class PeriodicInterval(threading.Thread): 13 | """ 14 | A class for running a task function periodically at a specified interval. 15 | """ 16 | 17 | def __init__(self, task_function, period): 18 | """ 19 | Initialize the PeriodicInterval thread. 20 | """ 21 | super().__init__() 22 | self.daemon = True 23 | self.task_function = task_function 24 | self.period = period 25 | self.i = 0 26 | self.t0 = time.time() 27 | self.stop_event = threading.Event() 28 | self.locker = threading.Lock() 29 | self.start() 30 | 31 | def sleep(self): 32 | """ 33 | Sleep for the remaining time to meet the specified period. 34 | """ 35 | self.i += 1 36 | delta = self.t0 + self.period * self.i - time.time() 37 | if delta > 0: 38 | time.sleep(delta) 39 | 40 | def run(self): 41 | """ 42 | Start the thread and execute the task_function periodically. 43 | """ 44 | while not self.stop_event.is_set(): 45 | with self.locker: 46 | self.task_function() 47 | self.sleep() 48 | 49 | def stop(self): 50 | """ 51 | Set the stop event to terminate the periodic task execution. 52 | """ 53 | self.stop_event.set() 54 | 55 | 56 | class FOPDTModel(object): 57 | def __init__(self, CV, ModelData): 58 | """ 59 | Initialize the FOPDTModel. 60 | """ 61 | self.CV = CV 62 | self.Gain, self.TimeConstant, self.DeadTime, self.Bias = ModelData 63 | 64 | def calc(self, PV, ts): 65 | """ 66 | Calculate the derivative of the process variable. 67 | """ 68 | if (ts - self.DeadTime) <= 0: 69 | um = 0 70 | elif int(ts - self.DeadTime) >= len(self.CV): 71 | um = self.CV[-1] 72 | else: 73 | um = self.CV[int(ts - self.DeadTime)] 74 | dydt = (-(PV - self.Bias) + self.Gain * um) / (self.TimeConstant) 75 | return dydt 76 | 77 | def update(self, PV, ts): 78 | """ 79 | Update the process variable using the model. 80 | """ 81 | y = odeint(self.calc, PV, ts) 82 | return y[-1] 83 | 84 | 85 | class PIDSimForCLX(object): 86 | def __init__(self): 87 | self.reset() 88 | self.gui_setup() 89 | model = (float(self.model_gain.get()), float(self.model_tc.get()), float(self.model_dt.get()), float(self.model_bias.get())) 90 | self.process = FOPDTModel(self.CV, model) 91 | self.comm = PLC() 92 | 93 | def reset(self): 94 | self.scan_count = 0 95 | self.PV = np.zeros(0) 96 | self.CV = np.zeros(0) 97 | self.SP = np.zeros(0) 98 | self.looper = None 99 | self.anim = None 100 | 101 | def gui_setup(self): 102 | self.root = ctk.CTk() 103 | self.root.title("PID Simulator for CLX") 104 | ctk.set_appearance_mode("system") 105 | ctk.set_default_color_theme("blue") 106 | self.screen_width = self.root.winfo_screenwidth() 107 | self.screen_height = self.root.winfo_screenheight() 108 | self.offset = 7 109 | self.toolbar = 73 110 | 111 | # Configure GUI window size and appearance 112 | self.root.resizable(True, True) 113 | self.root.geometry(f"{int(self.screen_width/2)}x{self.screen_height-self.toolbar}+{-self.offset}+0") 114 | ctk.set_appearance_mode("System") 115 | ctk.set_default_color_theme("blue") 116 | 117 | # Add a frame 118 | self.main_frame = ctk.CTkFrame(self.root) 119 | self.main_frame.pack(expand=True, fill=ctk.BOTH) 120 | 121 | # Text tags setup 122 | self.pv_text = ctk.StringVar() 123 | self.cv_text = ctk.StringVar() 124 | self.sp_text = ctk.StringVar() 125 | self.gui_status = ctk.StringVar() 126 | self.pvtag = ctk.CTkEntry(self.main_frame, width=250) 127 | self.cvtag = ctk.CTkEntry(self.main_frame, width=250) 128 | self.sptag = ctk.CTkEntry(self.main_frame, width=250) 129 | self.ip = ctk.CTkEntry(self.main_frame) 130 | self.slot = ctk.CTkEntry(self.main_frame, width=60) 131 | self.model_gain = ctk.CTkEntry(self.main_frame, width=60) 132 | self.model_tc = ctk.CTkEntry(self.main_frame, width=60) 133 | self.model_dt = ctk.CTkEntry(self.main_frame, width=60) 134 | self.model_bias = ctk.CTkEntry(self.main_frame, width=60) 135 | # Default Values 136 | self.sptag.insert(0, "SP") 137 | self.pvtag.insert(0, "PID_PV") 138 | self.cvtag.insert(0, "PID_CV") 139 | self.ip.insert(0, "192.168.123.100") 140 | self.slot.insert(0, "2") 141 | self.model_gain.insert(0, "1.45") 142 | self.model_tc.insert(0, "62.3") 143 | self.model_dt.insert(0, "10.1") 144 | self.model_bias.insert(0, "13.5") 145 | 146 | # Column 0 147 | # CTkLabels 148 | ctk.CTkLabel(self.main_frame, text="Tag").grid(row=0, column=0, padx=10, pady=10, sticky=ctk.NSEW) 149 | ctk.CTkLabel(self.main_frame, text="SP:").grid(row=1, column=0, padx=10, pady=10, sticky=ctk.NSEW) 150 | ctk.CTkLabel(self.main_frame, text="PV:").grid(row=2, column=0, padx=10, pady=10, sticky=ctk.NSEW) 151 | ctk.CTkLabel(self.main_frame, text="CV:").grid(row=3, column=0, padx=10, pady=10, sticky=ctk.NSEW) 152 | # Row 4 = Button 153 | # Row 5 = Button 154 | ctk.CTkLabel(self.main_frame, text="PLC IP Address:").grid(row=6, column=0, padx=10, pady=10, sticky=ctk.W) 155 | ctk.CTkLabel(self.main_frame, text="PLC Slot:").grid(row=7, column=0, padx=10, pady=10, sticky=ctk.W) 156 | ctk.CTkLabel(self.main_frame, text="Model Gain:").grid(row=8, column=0, padx=10, pady=10, sticky=ctk.W) 157 | ctk.CTkLabel(self.main_frame, text="Time Constant:").grid(row=9, column=0, padx=10, pady=10, sticky=ctk.W) 158 | ctk.CTkLabel(self.main_frame, text="Dead Time:").grid(row=10, column=0, padx=10, pady=10, sticky=ctk.W) 159 | ctk.CTkLabel(self.main_frame, text="Model Bias:").grid(row=11, column=0, padx=10, pady=10, sticky=ctk.W) 160 | 161 | # Column 1 162 | # CTkLabels 163 | ctk.CTkLabel(self.main_frame, text="Value").grid(row=0, column=1, padx=10, pady=10, sticky=ctk.NSEW) 164 | ctk.CTkLabel(self.main_frame, textvariable=self.sp_text).grid(row=1, column=1, padx=10, pady=10, sticky=ctk.NSEW) 165 | ctk.CTkLabel(self.main_frame, textvariable=self.pv_text).grid(row=2, column=1, padx=10, pady=10, sticky=ctk.NSEW) 166 | ctk.CTkLabel(self.main_frame, textvariable=self.cv_text).grid(row=3, column=1, padx=10, pady=10, sticky=ctk.NSEW) 167 | # Row 4 = Button 168 | # Row 5 = Button 169 | self.ip.grid(row=6, column=1, padx=10, pady=10, sticky=ctk.NSEW) 170 | self.slot.grid(row=7, column=1, padx=10, pady=10, sticky=ctk.W) 171 | self.model_gain.grid(row=8, column=1, padx=10, pady=10, sticky=ctk.W) 172 | self.model_tc.grid(row=9, column=1, padx=10, pady=10, sticky=ctk.W) 173 | self.model_dt.grid(row=10, column=1, padx=10, pady=10, sticky=ctk.W) 174 | self.model_bias.grid(row=11, column=1, padx=10, pady=10, sticky=ctk.W) 175 | ctk.CTkLabel(self.main_frame, text="Last Error:").grid(row=12, column=0, padx=10, columnspan=1, pady=10, sticky=ctk.W) 176 | ctk.CTkLabel(self.main_frame, textvariable=self.gui_status, wraplength=375).grid(row=12, column=1, padx=10, columnspan=6, pady=10, sticky=ctk.W) 177 | ctk.CTkLabel(self.main_frame, text="Seconds").grid(row=9, column=1, padx=30, pady=10, sticky=ctk.E) 178 | ctk.CTkLabel(self.main_frame, text="Seconds").grid(row=10, column=1, padx=30, pady=10, sticky=ctk.E) 179 | 180 | # Column 2 181 | # Actual PLC TagName 182 | ctk.CTkLabel(self.main_frame, text="PLC Tag").grid(row=0, column=2, padx=10, pady=10) 183 | self.sptag.grid(row=1, column=2, padx=10, pady=10, sticky=ctk.NSEW) 184 | self.pvtag.grid(row=2, column=2, padx=10, pady=10, sticky=ctk.NSEW) 185 | self.cvtag.grid(row=3, column=2, padx=10, pady=10, sticky=ctk.NSEW) 186 | 187 | # Buttons 188 | # Start Button Placement 189 | self.button_start = ctk.CTkButton(self.main_frame, text="Start Simulator", command=lambda: [self.start()]) 190 | self.button_start.grid(row=4, column=0, columnspan=1, padx=10, pady=10, sticky=ctk.NSEW) 191 | 192 | # Stop Button Placement 193 | self.button_stop = ctk.CTkButton(self.main_frame, text="Stop Simulator", command=lambda: [self.stop()]) 194 | self.button_stop.grid(row=4, column=1, columnspan=1, padx=10, pady=10, sticky=ctk.NSEW) 195 | self.button_stop.configure(state=ctk.DISABLED) 196 | 197 | # Trend Button Placement 198 | self.button_livetrend = ctk.CTkButton(self.main_frame, text="Show Trend", command=lambda: [self.show_live_trend()]) 199 | self.button_livetrend.grid(row=5, column=0, columnspan=2, padx=10, pady=10, sticky=ctk.NSEW) 200 | self.button_livetrend.configure(state=ctk.DISABLED) 201 | 202 | def start(self): 203 | try: 204 | self.pre_flight_checks() 205 | 206 | except Exception as e: 207 | self.gui_status.set(str(e)) 208 | 209 | else: 210 | self.looper = PeriodicInterval(self.thread_get_data, 0.1) 211 | self.live_trend() 212 | 213 | def pre_flight_checks(self): 214 | self.comm.IPAddress = self.ip.get() 215 | self.comm.ProcessorSlot = int(self.slot.get()) 216 | self.comm.SocketTimeout = 10.0 217 | 218 | self.read_tag_list = [self.cvtag.get(), self.sptag.get()] 219 | self.write_tag = self.pvtag.get() 220 | 221 | ret = self.comm.Read([self.cvtag.get(), self.sptag.get(), self.pvtag.get()]) 222 | if any(x.Value is None for x in ret): 223 | raise Exception("Check PLC and Tag Configuration") 224 | else: 225 | self.comm.SocketTimeout = 0.5 226 | 227 | self.reset() 228 | self.gui_status.set("") 229 | self.process.Gain = float(self.model_gain.get()) 230 | self.process.TimeConstant = float(self.model_tc.get()) * 10 # Due to sample rate of 0.1 seconds 231 | self.process.DeadTime = float(self.model_dt.get()) * 10 # Due to sample rate of 0.1 seconds 232 | self.process.Bias = float(self.model_bias.get()) 233 | # Configure Gui 234 | self.button_stop.configure(state=ctk.NORMAL) 235 | self.button_livetrend.configure(state=ctk.DISABLED) 236 | self.button_start.configure(state=ctk.DISABLED) 237 | self.ip.configure(state=ctk.DISABLED) 238 | self.slot.configure(state=ctk.DISABLED) 239 | self.model_gain.configure(state=ctk.DISABLED) 240 | self.model_tc.configure(state=ctk.DISABLED) 241 | self.model_dt.configure(state=ctk.DISABLED) 242 | self.model_bias.configure(state=ctk.DISABLED) 243 | self.pvtag.configure(state=ctk.DISABLED) 244 | self.cvtag.configure(state=ctk.DISABLED) 245 | self.sptag.configure(state=ctk.DISABLED) 246 | 247 | def thread_get_data(self): 248 | try: 249 | ret = self.comm.Read(self.read_tag_list) 250 | ret_values = [x.Value for x in ret] 251 | ret_states = [x.Status for x in ret] 252 | gui_tags = [self.cv_text, self.sp_text] 253 | for i in range(len(ret_values)): 254 | if ret_states[i] == "Success": 255 | gui_tags[i].set(round(ret_values[i], 3)) 256 | else: 257 | self.gui_status.set(ret_states[i]) 258 | if not all(x == "Success" for x in ret_states): 259 | raise Exception(ret_states[0] + " " + ret_states[1]) 260 | # Store Data when it is read 261 | self.CV = np.append(self.CV, ret_values[0]) 262 | self.SP = np.append(self.SP, ret_values[1]) 263 | # Send CV to Process 264 | self.process.CV = self.CV 265 | ts = [self.scan_count, self.scan_count + 1] 266 | # Get new PV value 267 | if self.PV.size > 1: 268 | pv = self.process.update(self.PV[-1], ts) 269 | else: 270 | pv = self.process.update(float(self.model_bias.get()), ts) 271 | # Add Noise between -0.1 and 0.1 272 | noise = (random.randint(0, 10) / 100) - 0.05 273 | # Store PV 274 | self.PV = np.append(self.PV, pv[0] + noise) 275 | # Write PV to PLC 276 | write = self.comm.Write(self.write_tag, self.PV[-1]) 277 | if write.Status == "Success": 278 | self.pv_text.set(round(write.Value, 2)) 279 | else: 280 | self.gui_status.set(write.Status) 281 | 282 | except Exception as e: 283 | self.gui_status.set("Error: " + str(e)) 284 | 285 | else: 286 | self.scan_count += 1 287 | 288 | def stop(self): 289 | try: 290 | self.button_start.configure(state=ctk.NORMAL) 291 | self.button_livetrend.configure(state=ctk.DISABLED) 292 | self.button_stop.configure(state=ctk.DISABLED) 293 | self.ip.configure(state=ctk.NORMAL) 294 | self.slot.configure(state=ctk.NORMAL) 295 | self.model_gain.configure(state=ctk.NORMAL) 296 | self.model_tc.configure(state=ctk.NORMAL) 297 | self.model_dt.configure(state=ctk.NORMAL) 298 | self.pvtag.configure(state=ctk.NORMAL) 299 | self.cvtag.configure(state=ctk.NORMAL) 300 | self.sptag.configure(state=ctk.NORMAL) 301 | self.model_bias.configure(state=ctk.NORMAL) 302 | if self.anim and len(plt.get_fignums()) > 0: 303 | self.anim.pause() 304 | self.anim = None 305 | if self.looper: 306 | self.looper.stop() 307 | self.looper = None 308 | time.sleep(0.1) 309 | self.comm.Close() 310 | plt.close("all") 311 | 312 | except Exception as e: 313 | self.gui_status.set("Stop Error: " + str(e)) 314 | 315 | def live_trend(self): 316 | # Set up the figure 317 | fig = plt.figure() 318 | self.ax = plt.axes() 319 | (SP,) = self.ax.plot([], [], lw=2, color="Red", label="SP") 320 | (CV,) = self.ax.plot([], [], lw=2, color="Green", label="CV") 321 | (PV,) = self.ax.plot([], [], lw=2, color="Blue", label="PV") 322 | 323 | # Setup Func 324 | def init(): 325 | SP.set_data([], []) 326 | PV.set_data([], []) 327 | CV.set_data([], []) 328 | plt.ylabel("EU") 329 | plt.xlabel("Time (min)") 330 | plt.suptitle("Live Data") 331 | plt.legend(loc="upper right") 332 | 333 | # Loop here 334 | def animate(i): 335 | try: 336 | x = np.arange(len(self.SP), dtype=int) 337 | x = x / 600 # Convert mS to Minutes 338 | SP.set_data(x, self.SP) 339 | CV.set_data(x, self.CV) 340 | PV.set_data(x, self.PV) 341 | self.ax.relim() 342 | self.ax.autoscale_view() 343 | except Exception as e: 344 | self.gui_status.set("Plot Error: " + str(e)) 345 | 346 | # Live Data 347 | self.anim = animation.FuncAnimation(fig, animate, init_func=init, frames=60, interval=1000) 348 | 349 | mngr = plt.get_current_fig_manager() 350 | mngr.window.geometry(f"{int(self.screen_width/2)}x{self.screen_height-self.toolbar}+{int(self.screen_width/2)-self.offset+1}+0") 351 | plt.gcf().canvas.mpl_connect("close_event", self.on_plot_close) 352 | plt.show() 353 | 354 | def on_plot_close(self, event): 355 | if self.looper: 356 | self.button_livetrend.configure(state=ctk.NORMAL) 357 | 358 | def show_live_trend(self): 359 | self.button_livetrend.configure(state=ctk.DISABLED) 360 | open_plots = plt.get_fignums() 361 | if len(open_plots) == 0: 362 | self.live_trend() 363 | 364 | 365 | if __name__ == "__main__": 366 | gui_app = PIDSimForCLX() 367 | gui_app.root.mainloop() 368 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PythonCLX_PIDSimulator 2 | 3 | 4 | GUI: 5 | 6 | 7 | ![PID_Sim](https://github.com/Destination2Unknown/PythonCLX_PIDSimulator/assets/92536730/1e441359-a999-41a2-b821-1571d1576793) 8 | 9 | 10 | 11 | SP and CV are Read from the PLC - PV is written to the PLC 12 | 13 | 14 | ![PID2](https://user-images.githubusercontent.com/92536730/154962569-95818268-1a2a-4ed5-b7cf-19ce847b40db.png) 15 | 16 | 17 | Trend: 18 | 19 | 20 | ![image](https://user-images.githubusercontent.com/92536730/154958077-527e4e79-6add-4fdc-bab9-9b7ee979cb87.png) 21 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | customtkinter 2 | numpy 3 | matplotlib 4 | scipy 5 | pylogix --------------------------------------------------------------------------------