#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter service
    name:device.py 处理设备
    author:rabin
"""
from demeter.core import *
from demeter.mqtt import *
class Device(object):

	# 新增网关时，增加状态和电源
	def upGatewayStatus(self, farm_id, gateway_id, hardware_id):
		if hardware_id and gateway_id > 0:
			info = Demeter.service('common').list('device_info', search={'hardware_id':hardware_id})
			if not info:
				# 网关状态
				insert = {}
				insert['farm_id'] = farm_id
				insert['name'] = '网关状态'
				insert['hardware_id'] = hardware_id
				insert['gateway_id'] = gateway_id
				insert['hardware_type'] = 5
				insert['value'] = '0'
				insert['type_id'] = 0
				insert['status'] = False
				Demeter.service('common').update('device_info', None, insert)

				# 电源
				insert = {}
				insert['farm_id'] = farm_id
				insert['name'] = '电源状态'
				insert['hardware_id'] = hardware_id
				insert['gateway_id'] = gateway_id
				insert['hardware_type'] = 4
				insert['value'] = '0'
				insert['type_id'] = 8
				insert['status'] = False
				Demeter.service('common').update('device_info', None, insert)
			
	# 批量处理开关
	def switchMul(self, value):
		if value['devices']:
			model = Demeter.model('device_info')
			value['devices'] = tuple(eval(value['devices']))
			if value['oper'] == 1:
				switch = 1
			else:
				switch = 0
			for v in value['devices']:
				self.switch(v, switch)
	# 处理开关
	def switch(self, device_id, switch=1):
		model = Demeter.model('device_info')
		model.id = device_id
		info = model.select(type='fetchone')
		if info:
			model.id = device_id
			model.update(value=switch)
			model = Demeter.model('device_gateway')
			model.id = info['gateway_id']
			gateway_info = model.select(type='fetchone')

			if info['type_id'] > 0:
				model = Demeter.model('device_type')
				model.id = info['type_id']
				type_info = model.select(type='fetchone')
				if type_info:
					info['hardware_id'] = str(info['hardware_id'])
					switch = str(switch)
					gateway_info['hardware_id'] = str(gateway_info['hardware_id'])
					# 这里要向服务器发送pub请求了,暂时使用临时文件代替
					Demeter.temp(key=type_info['key'], name=info['hardware_id'], value=switch)
					#pub
					#pub = Pub()
					key = 'update/' + type_info['key'] + '/' + gateway_info['hardware_id']  + '/' + info['hardware_id']
					value = switch
					#pub.push(key, value, 2)