#!/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
from demeter.mqtt import *
# 处理定时命令、周期命令、条件控制、消息、设备状态等
timeSleep = 10
				
# 更改设备状态(离线)
def device():
	while 1:
		model = Demeter.model('device_info')
		cur = Demeter.time() - 1800
		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)
				#提醒notice
				notice(2, v)
			elif v['hardware_type'] != 7 and v['hardware_type'] != 6:
				model.update(status=False)
				#提醒notice
				notice(2, v)
		gevent.sleep(60)

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

# 同步时间，24小时同步一次
def timeSync():
	while 1:
		pub = Pub()
		key = 'time/bh'
		value = Demeter.date(Demeter.time())
		pub.push(key, value)
		gevent.sleep(3600*24)

# 用户一周没有使用的时候提醒
def userNotice():
	while 1:
		model = Demeter.model('farm_user')
		cur = Demeter.time() - 3600*24*7
		model.cdate.assgin(cur, '<=')
		model.status = True
		data = model.select()
		for v in data:
			notice(1, data)

# 用户提醒
def notice(t, data):
	pass

def handle():
	gevent.joinall([
		gevent.spawn(device),
		gevent.spawn(savePic),
		gevent.spawn(timeSync),
		#gevent.spawn(userNotice),
	])

handle()