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

class Handle(object):

	# 设置数据
	def set(self, master, server):
		master.set_timeout(6.0)
		server['server_time'] = int(server['server_time'])
		while(True):
			self.run(master, server)
			if server['server_time'] > 0:
					time.sleep(server['server_time'])

	def run(self, master, server):
		gateway = Demeter.service('common').list('device_gateway', search={'server_id':server['id']})
		if gateway:
			for v in gateway:
				if v['product_id']:
					self.runCode(master, v)

	def runCode(self, master, gateway):
		code = Demeter.service('common').list('setting_modbus_code', search={'product_id':gateway['product_id']})
		if code:
			for v in code:
				if v['register_read_address']:
					try:
						self.setValue(v, master, gateway)
					except:
						pass

	# 发送数据
	def send(self, master, server, type_info, info, value):
		master.set_timeout(6.0)
		master.set_verbose(True)
		code = Demeter.service('common').one('setting_modbus_code', id=info['code_id'])
		if not code:
			return ''
		write_address = code['register_write_address'].split("\r\n")
		if not info['code_index']:
			info['code_index'] = 0
		code = self.getCode(write_address[info['code_index']], code, 2)
		result = ''
		if code['register_type']:
			#print(value)
			value = int(value)
			master.execute(int(code['slave_id']), int(code['register_type']), int(code['register_address']), output_value=value)
			result = True
			'''
			read_address = code['register_read_address'].split("\r\n")
			if info['code_index'] not in read_address:
				return True
			code = self.getCode(read_address, code)
			result = master.execute(int(code['slave_id']), int(code['register_type']), int(code['register_address']), int(code['register_length']))
			'''
			gateway = Demeter.service('common').one('device_gateway', id=info['gateway_id'])
			self.setValue(code, master, gateway)
		return result

	def setValue(self, code, master, gateway):
		config = {}
		config['parent'] = gateway['hardware_id']
		address = code['register_read_address'].split("\r\n")
		device_type_key = code['device_type_key'].split("\r\n")
		exp = code['exp'].split("\r\n")

		j = 0
		for i in address:
			device_type = device_type_key[j]
			device_type = Demeter.service('common').one('setting_device_type', key=device_type)
			config['type'] = device_type['key']

			info = Demeter.service('common').one('device_info', gateway_id=gateway['id'], code_id=code['id'], code_index=j)
			hardware = Demeter.service('common').one('hardware_type', id=info['hardware_type'])
			config['method'] = hardware['key']
			config['child'] = info['hardware_id']
			code = self.getCode(i, code)
			code['exp'] = exp[j]
			value = self.getValue(code, master, info)
			#print(value)
			
			j = j + 1
			name = info['name']
			Demeter.service('device').save(config, value, name, device_type)

	def getValue(self, code, master, info):

		temp = master.execute(int(code['slave_id']), int(code['register_type']), int(code['register_address']), int(code['register_length']))
		#value = struct.unpack('>f', struct.pack('>HH', temp[0], temp[1]))
		#value = str(round(temp[0], 2))
		#value = str(temp)
		value = str(temp[0])
		if value and value != '0':
			if 'exp' in code and code['exp']:
				value = Demeter.exp(code['exp'], value)
			if 'exp' in info and info['exp'] and info['exp'] != '-1':
				value = Demeter.exp(info['exp'], value)
			value = str(round(float(value), 2))
		#Demeter.echo('value:' + str(value) + '||temp:' + str(temp) + '||size:' + str(len(temp)))
		#print(value)
		return value

	def getCode(self, address, code, type = 1):
		(code['register_type'],code['register_address'],code['register_length']) = address.split(',')
		code['register_type'] = int(code['register_type'])
		if type == 1:
			if code['register_type'] == 1:
				# 线圈
				code['register_type'] = mdef.READ_COILS
			elif code['register_type'] == 2:
				code['register_type'] = mdef.READ_DISCRETE_INPUTS
			elif code['register_type'] == 3:
				code['register_type'] = mdef.READ_HOLDING_REGISTERS
			elif code['register_type'] == 4:
				code['register_type'] = mdef.READ_INPUT_REGISTERS
		else:
			if code['register_type'] == 1:
				# 线圈
				code['register_type'] = mdef.WRITE_SINGLE_COIL
			elif code['register_type'] == 2:
				code['register_type'] = mdef.WRITE_MULTIPLE_COILS
			elif code['register_type'] == 3:
				code['register_type'] = mdef.WRITE_SINGLE_REGISTER
			elif code['register_type'] == 4:
				code['register_type'] = mdef.WRITE_MULTIPLE_REGISTERS
		return code