# -*- coding: utf-8 -*-
from demeter.core import *
import modbus_tk
import modbus_tk.modbus_tcp as modbus_tcp
import modbus_tk.defines as mdef
import time
import random
import struct
import serial

class Tcp(object):

	# 启动客户端
	def start(self):
		while(True):
			self.run()
			time.sleep(100)

	def run(self):
		server = Demeter.service('common').list('setting_server', search={'server_type':2})
		if server:
			modbus = Demeter.path + 'modbus.py'
			for v in server:
				command = 'python3 ' + modbus + ' -m tcp_client -i ' + str(v['id'])

				check = "ps aux|grep '"+command+"'|grep -v entrypoint|grep -v grep|grep -v process|awk '{print $1}'"
				check = Shell.popen(check)
				if not check:
					Shell.popen(command, sub=True, bg=True)

	def client(self, id):
		server = Demeter.service('common').one('setting_server', id=id)
		master = modbus_tcp.TcpMaster(host=server['server_host'], port=int(server['server_port']))
		Demeter.service('handle', 'modbus').set(master, server)

	def send(self, server, type_info, info, value):
		master = modbus_tcp.TcpMaster(host=server['server_host'], port=int(server['server_port']))
		Demeter.service('handle', 'modbus').send(master, type_info, info, value)