rtu.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # -*- coding: utf-8 -*-
  2. from demeter.core import *
  3. import modbus_tk
  4. import modbus_tk.modbus_rtu as modbus_rtu
  5. import modbus_tk.defines as mdef
  6. import time
  7. import random
  8. import struct
  9. import serial
  10. class Rtu(object):
  11. # 启动客户端
  12. def start(self):
  13. while(True):
  14. self.run()
  15. time.sleep(100)
  16. def run(self):
  17. server = Demeter.service('common').list('setting_server', search={'server_type':3})
  18. if server:
  19. modbus = Demeter.path + 'modbus.py'
  20. for v in server:
  21. command = 'python3 ' + modbus + ' -m rtu_client -i ' + str(v['id'])
  22. check = "ps aux|grep '"+command+"'|grep -v entrypoint|grep -v grep|grep -v process|awk '{print $1}'"
  23. check = Shell.popen(check)
  24. if not check:
  25. Shell.popen(command, sub=True, bg=True)
  26. def client(self, id):
  27. server = Demeter.service('common').one('setting_server', id=id)
  28. port,baudrate = self.port(server['server_port'])
  29. master = modbus_rtu.RtuMaster(serial.Serial(port, baudrate=baudrate, bytesize=8, parity='N', stopbits=1, xonxoff=0))
  30. Demeter.service('handle', 'modbus').set(master, server)
  31. def send(self, server, type_info, info, value):
  32. master = modbus_rtu.RtuMaster(serial.Serial(port, baudrate=baudrate, bytesize=8, parity='N', stopbits=1, xonxoff=0))
  33. Demeter.service('handle', 'modbus').send(master, server, type_info, info, value)
  34. def port(self, port):
  35. baudrate = 4800
  36. if ':' in port:
  37. data = port.split(':')
  38. port = data[0]
  39. baudrate = int(data[1])
  40. return (port, baudrate)