#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter web
    name:admin.py
    author:rabin
"""
import time
from demeter.core import *
from gevent import monkey; monkey.patch_socket()
import gevent
from pic import pic
# 处理定时命令、周期命令、条件控制、消息、设备状态等
timeSleep = 10

# 开关设备
def switch(value):
	Demeter.service('device').switchMul(value)
				

# 更改设备状态(离线)
def device():
	while 1:
		model = Demeter.model('device_info')
		cur = Demeter.time() - 500
		model.cdate.assgin(cur, '<=')
		model.status = True
		data = model.select()
		for v in data:
			model.id = v['id']
			if v['hardware_type'] == 5:
				model.update(value='0', status=False)
			elif v['hardware_type'] != 7 and v['hardware_type'] != 6:
				model.update(status=False)
		gevent.sleep(60)

# 更改控制设备的超时状态
def control():
	while 1:
		model = Demeter.model('device_info')
		type_model = Demeter.model('device_type')
		cur = Demeter.time() - 10
		model.cdate.assgin(cur, '<=')
		model.hardware_type = 3
		service = Demeter.service('device')
		data = model.select()
		for v in data:
			model.id = v['id']
			if v['exp'] == '-1':
				msg = service.notice('timeout')
				service.mul(v['id'], v['type_id'], v['name'], v['cxnum'], '失败:' + msg, False)
			else:
				msg = '1'
				service.mul(v['id'], v['type_id'], v['name'], v['cxnum'], '', True)
			model.update(exp=msg)

		gevent.sleep(timeSleep)
		

def timing():
	while 1:
		model = Demeter.model('device_set_timing')
		model.status = 0
		cur = Demeter.time()
		model.zdate.assgin(cur, '<=')
		data = model.select()
		if data:
			for value in data:
				switch(value)
				model.id = value['id']
				model.update(status=1)
		gevent.sleep(timeSleep)

def loop():
	while 1:
		model = Demeter.model('device_set_loop')
		cur = Demeter.time()
		date = Demeter.date(cur, '%Y-%m-%d-%w-%H-%M')
		date = date.split('-')
		week = date[3]
		day = date[2]
		model.status = True
		model.hour = date[4]
		model.minute = date[5]
		data = model.select()
		if data:
			for value in data:
				state = False
				value['loop'] = value['loop'].split(',')
				if value['looptype'] == 2:
					if week in value['loop']:
						state = True
				elif value['looptype'] == 3:
					if day in value['loop']:
						state = True
				if state:
					switch(value)
		gevent.sleep(timeSleep)

def savePic():
	while 1:
		pic()
		gevent.sleep(1800)

def handle():
	gevent.joinall([
		gevent.spawn(timing),
		gevent.spawn(loop),
		gevent.spawn(device),
		gevent.spawn(savePic),
		gevent.spawn(control),
	])

handle()