Last active
September 21, 2017 22:55
-
-
Save Felhamed/466e66e775529a074e6d5919af34881c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| # modbus_thread | |
| # start a thread for polling a set of registers, display result on console | |
| # exit with ctrl+c | |
| import time | |
| from threading import Thread, Lock | |
| from pyModbusTCP.client import ModbusClient | |
| SERVER_HOST = "localhost" | |
| SERVER_PORT = 502 | |
| # set global | |
| regs = [] | |
| # init a thread lock | |
| regs_lock = Lock() | |
| # modbus polling thread | |
| def polling_thread(): | |
| global regs | |
| c = ModbusClient(host=SERVER_HOST, port=SERVER_PORT) | |
| # polling loop | |
| while True: | |
| # keep TCP open | |
| if not c.is_open(): | |
| c.open() | |
| # do modbus reading on socket | |
| reg_list = c.read_holding_registers(0,10) | |
| # if read is ok, store result in regs (with thread lock synchronization) | |
| if reg_list: | |
| with regs_lock: | |
| regs = reg_list | |
| # 1s before next polling | |
| time.sleep(1) | |
| # start polling thread | |
| tp = Thread(target=polling_thread) | |
| # set daemon: polling thread will exit if main thread exit | |
| tp.daemon = True | |
| tp.start() | |
| # display loop (in main thread) | |
| while True: | |
| # print regs list (with thread lock synchronization) | |
| with regs_lock: | |
| print(regs) | |
| # 1s before next print | |
| time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment