tcp.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # -*- coding: utf-8 -*-
  2. from demeter.core import *
  3. import modbus_tk
  4. import modbus_tk.modbus_tcp as modbus_tcp
  5. import modbus_tk.defines as mdef
  6. import time
  7. import random
  8. import struct
  9. import serial
  10. class Tcp(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':2})
  18. if server:
  19. modbus = Demeter.path + 'modbus.py'
  20. for v in server:
  21. command = 'python3 ' + modbus + ' -m tcp_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 server(self, id):
  27. server = Demeter.service('common').one('setting_server', id=id)
  28. # 启动服务
  29. server = modbus_tcp.TcpServer(port=8010)
  30. server.start()
  31. slave_1 = server.add_slave(1)
  32. slave_1.add_block('block1', modbus_tk.defines.HOLDING_REGISTERS, 0, 16)
  33. while 1:
  34. time.sleep(0.5)
  35. def client(self, id):
  36. server = Demeter.service('common').one('setting_server', id=id)
  37. master = modbus_tcp.TcpMaster(host=server['server_host'], port=int(server['server_port']))
  38. Demeter.service('handle', 'modbus').set(master, server)
  39. def send(self, server, type_info, info, value):
  40. master = modbus_tcp.TcpMaster(host=server['server_host'], port=int(server['server_port']))
  41. Demeter.service('handle', 'modbus').send(master, type_info, info, value)