__load__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. # -*- coding: utf-8 -*-
  2. """
  3. demeter load
  4. author:rabin
  5. """
  6. from demeter.web import *
  7. from datetime import *
  8. class Load(Base):
  9. KEYS = ('user', 'farm')
  10. def setting(self):
  11. self.user()
  12. def user(self):
  13. ajax = self.input('ajax')
  14. if ajax:
  15. self.data['ajax'] = True
  16. else:
  17. self.data['ajax'] = False
  18. self.data['auth'] = True
  19. if 'user' in self.data['setting'] and self.data['setting']['user']:
  20. self.data['setting']['userInfo'] = self.service('common').one('farm_user', id=self.data['setting']['user'].decode())
  21. self.data['setting']['farm'] = self.data['setting']['userInfo']['farm_id']
  22. else:
  23. return
  24. if 'farm' in self.data['setting'] and self.data['setting']['farm']:
  25. self.data['setting']['farmInfo'] = self.service('common').one('farm', id=self.data['setting']['farm'])
  26. self.data['setting']['farmInfo']['gateways'] = ''
  27. if self.data['setting']['farmInfo']['gateway']:
  28. self.data['setting']['farmInfo']['gateways'] = tuple(eval(self.data['setting']['farmInfo']['gateway']))
  29. self.data['setting']['msgNum'] = len(self.service('common').list('msg', search={'status':False, "farm_id":self.data['setting']['farm']}, limit='0,100'))
  30. if self.data['setting']['msgNum'] > 99:
  31. self.data['setting']['msgNum'] = str(99) + '+'
  32. #self.data['setting']['msg'] = self.service('common').one('msg', type_id=3)
  33. self.data['setting']['web'] = Demeter.config['web']['url']
  34. self.data['setting']['farmurl'] = Demeter.config['web']['farmurl']
  35. cur = 'main'
  36. if '/' in self.request.uri:
  37. temp = self.request.uri.split('/')
  38. slen = len(temp)
  39. if slen > 1 and temp[1]:
  40. cur = temp[1]
  41. self.data['setting']['cur'] = cur
  42. class Device(object):
  43. @staticmethod
  44. def init(self, search={}):
  45. type = self.input('type')
  46. id = self.input('id')
  47. if not id:
  48. self.view('404.html')
  49. return (None, type)
  50. if 'stat' in self.request.uri:
  51. self.data['device_cur'] = 'stat'
  52. elif 'log' in self.request.uri:
  53. self.data['device_cur'] = 'log'
  54. elif 'pic' in self.request.uri:
  55. self.data['device_cur'] = 'pic'
  56. else:
  57. self.data['device_cur'] = 'data'
  58. self.data['show'] = True
  59. self.data['url'] = Device.url('type='+type+'&id=' + id)
  60. if not search:
  61. search = {}
  62. self.data['info'] = {}
  63. self.data['device'] = []
  64. if type == 'gateway':
  65. self.data['info'] = self.service('common').one('device_gateway', id=id)
  66. if not self.data['info']:
  67. self.view('404.html')
  68. return (None, type)
  69. search['gateway_id'] = id
  70. self.data['device'] = Device.get(self, search=search)
  71. if self.data['device_cur'] in ('stat', 'log'):
  72. self.data['pic'] = Device.get(self, search={'gateway_id':id, 'hardware_type':6})
  73. elif type == 'page':
  74. self.data['info'] = self.service('common').one('device_page', id=id)
  75. if not self.data['info']:
  76. self.view('404.html')
  77. return (None, type)
  78. search['page_id'] = id
  79. self.data['group'] = self.service('common').list('device_group', search={'page_id':id}, order='inorder asc,cdate desc')
  80. if self.data['group']:
  81. Device.group(self, search)
  82. else:
  83. self.data['info'] = self.data['setting']['farmInfo']
  84. if not self.data['info']:
  85. self.view('404.html')
  86. return (None, type)
  87. self.data['device'] = Device.get(self, search=search)
  88. if not self.data['device'] and not self.data['info']:
  89. self.view('404.html')
  90. return (None, type)
  91. self.data['input'] = {}
  92. self.data['input']['type'] = type
  93. self.data['input']['id'] = id
  94. return (id, type)
  95. @staticmethod
  96. def set(self):
  97. if 'condition' in self.request.uri:
  98. self.data['set_cur'] = 'condition'
  99. elif 'timing' in self.request.uri:
  100. self.data['set_cur'] = 'timing'
  101. elif 'loop' in self.request.uri:
  102. self.data['set_cur'] = 'loop'
  103. else:
  104. self.data['set_cur'] = 'mul'
  105. self.data['url'] = Device.setUrl()
  106. @staticmethod
  107. def setCronOper(self):
  108. self.data['oper'] = ({'id':1, 'name':'打开'},{'id':2, 'name':'关闭'})
  109. self.data['looptype'] = ({'id':1, 'name':'按日周期', 'list':'每天'},{'id':2, 'name':'按周周期', 'list':'每周'}, {'id': 3, 'name': '按月周期', 'list':'每月'})
  110. self.data['opers'] = ({'id':1, 'name':'无操作'}, {'id':2, 'name':'打开'},{'id':3, 'name':'关闭'})
  111. self.data['week'] = ({'id':1, 'name':'周一'},{'id':2, 'name':'周二'}, {'id': 3, 'name': '周三'}, {'id': 4, 'name': '周四'}, {'id': 5, 'name': '周五'}, {'id': 6, 'name': '周六'}, {'id': 7, 'name': '周日'})
  112. self.data['condition'] = ({'id':1, 'name':'大于', 'exp':'>'}, {'id':2, 'name':'小于', 'exp':'<'},{'id':3, 'name':'等于','exp':'='})
  113. self.data['day'] = []
  114. for i in range(31):
  115. i = i + 1
  116. self.data['day'].append({'id':i, 'name':i})
  117. self.data['hour'] = []
  118. for i in range(24):
  119. i = i + 1
  120. self.data['hour'].append({'id':i, 'name':Demeter.hour(i)})
  121. self.data['minute'] = []
  122. for i in range(60):
  123. self.data['minute'].append({'id':i, 'name':Demeter.hour(i)})
  124. @staticmethod
  125. def get(self, search):
  126. if 'id--ins' in search and search['id--ins']:
  127. search['id--ins'] = tuple(eval(search['id--ins']))
  128. #order='inorder asc, type_id asc,udate asc,id asc'
  129. return self.service('common').list('device_info', state=True, search=search, order='cdate desc,udate asc,hardware_id asc', limit='0,10000')
  130. @staticmethod
  131. def getByGateway(self, search={}):
  132. device = Device.get(self, search=search)
  133. result = {}
  134. if device:
  135. for value in device:
  136. if value['gateway_id'] not in result:
  137. result[value['gateway_id']] = []
  138. result[value['gateway_id']].append(value)
  139. return result
  140. @staticmethod
  141. def data(self):
  142. id, type = Device.init(self)
  143. if not id:
  144. return
  145. method = type + '_data'
  146. if hasattr(Device, method):
  147. func = getattr(Device, method)
  148. data = func(self, id)
  149. else:
  150. self.view('404.html')
  151. return
  152. #self.data = dict(self.data, **data)
  153. @staticmethod
  154. def gateway_data(self, id):
  155. power = []
  156. sensor = []
  157. control = []
  158. self.data['stat'] = {}
  159. self.data['pic'] = []
  160. self.data['camera'] = []
  161. if self.data['device']:
  162. for value in self.data['device']:
  163. if value['type_id']:
  164. type_info = self.service('common').one('setting_device_type', id=value['type_id'])
  165. value['unit'] = type_info['unit']
  166. value['typeName'] = type_info['name']
  167. # 获取网关状态
  168. if value['hardware_type'] == 5:
  169. power.append(value)
  170. # 获取电源设备
  171. if value['hardware_type'] == 4:
  172. #value['value'] = Demeter.exp(value['out_exp'], value['value'])
  173. power.append(value)
  174. """
  175. if not self.data['stat']:
  176. self.data['stat'] = value
  177. """
  178. # 获取采集设备
  179. if value['hardware_type'] == 2:
  180. #value['value'] = Demeter.exp(value['out_exp'], value['value'])
  181. sensor.append(value)
  182. if not self.data['stat']:
  183. self.data['stat'] = value
  184. # 获取控制设备
  185. if value['hardware_type'] == 3:
  186. if value['value'] == '1.0':
  187. value['value'] = '1'
  188. control.append(value)
  189. # 获取摄像头
  190. if value['hardware_type'] == 6:
  191. value['value'] = value['value'] + '?' + Demeter.date(Demeter.time(), '%Y%m%d%H')
  192. self.data['pic'].append(value)
  193. # 获取摄像机
  194. if value['hardware_type'] == 7:
  195. self.data['camera'].append(value)
  196. """
  197. if power:
  198. power.reverse()
  199. """
  200. self.data['list'] = ({'name': '设备状态', 'device': power}, {'name': '数据采集', 'device': sensor}, {'name': '实时设备控制', 'device': control})
  201. @staticmethod
  202. def page_data(self, id):
  203. self.data['list'] = self.data['group']
  204. @staticmethod
  205. def group(self, search):
  206. self.data['show'] = False
  207. self.data['pic'] = []
  208. self.data['camera'] = []
  209. self.data['stat'] = {}
  210. for key, value in enumerate(self.data['group']):
  211. if value['devices']:
  212. search['id--ins'] = value['devices']
  213. if self.data['device_cur'] == 'stat':
  214. search['hardware_type--ins'].append(6)
  215. self.data['group'][key]['device'] = Device.get(self, search=search)
  216. if self.data['group'][key]['device']:
  217. for k, v in enumerate(self.data['group'][key]['device']):
  218. if v['hardware_type'] == 2 or v['hardware_type'] == 4:
  219. #v['value'] = Demeter.exp(v['out_exp'], v['value'])
  220. if v['hardware_type'] == 2 and self.data['info']['stat'] == True and not self.data['stat']:
  221. self.data['stat'] = v
  222. self.data['show'] = True
  223. if v['type_id'] > 0:
  224. type_info = self.service('common').one('setting_device_type', id=v['type_id'])
  225. self.data['group'][key]['device'][k]['unit'] = type_info['unit']
  226. self.data['group'][key]['device'][k]['typeName'] = type_info['name']
  227. if self.data['device_cur'] == 'data':
  228. if v['hardware_type'] == 6:
  229. slen = len(self.data['group'][key]['device'])
  230. if slen < 2:
  231. del self.data['group'][key]['device']
  232. v['name'] = self.data['group'][key]['name']
  233. v['value'] = v['value'] + '?' + Demeter.date(Demeter.time(), '%Y%m%d%H')
  234. self.data['pic'].append(v)
  235. if v['hardware_type'] == 7:
  236. slen = len(self.data['group'][key]['device'])
  237. if slen < 2:
  238. del self.data['group'][key]['device']
  239. v['name'] = self.data['group'][key]['name']
  240. self.data['camera'].append(v)
  241. if self.data['device_cur'] == 'stat':
  242. if v['hardware_type'] == 6:
  243. self.data['pic'] = True
  244. else:
  245. self.data['device'].append(v)
  246. else:
  247. self.data['device'].append(v)
  248. @staticmethod
  249. def pic(self):
  250. id, type = Device.init(self, search={'hardware_type':6})
  251. if not id:
  252. return
  253. state = Device.get(self, search={'hardware_type--ins':(2,4)})
  254. if state:
  255. self.data['show'] = True
  256. device = self.input('device')
  257. if not device:
  258. #如果没有,就获取第一个
  259. self.data['deviceInfo'] = self.data['device'][0]
  260. else:
  261. self.data['deviceInfo'] = self.service('common').one('device_info', id=device)
  262. if not self.data['deviceInfo']:
  263. self.view('404.html')
  264. return
  265. self.data['pic'] = self.service('common').list('device_pic', search={'device_id':self.data['deviceInfo']['id']}, page={'num':12}, order='sdate desc')
  266. if self.data['pic']:
  267. for key, value in enumerate(self.data['pic']):
  268. self.data['pic'][key]['cdates'] = Demeter.date(value['sdate'])
  269. @staticmethod
  270. def statBase(self, deviceInfo={}, device = False):
  271. if not device:
  272. device = self.input('device')
  273. method = self.input('method', 'maxmin')
  274. if not device:
  275. #如果没有,就获取sensor的第一个
  276. self.data['deviceInfo'] = deviceInfo
  277. else:
  278. self.data['deviceInfo'] = self.service('common').one('device_info', id=device)
  279. if not self.data['deviceInfo']:
  280. self.view('404.html')
  281. return
  282. self.data['type'] = self.service('common').one('setting_device_type', id=self.data['deviceInfo']['type_id'])
  283. model = Demeter.model('data', 'tsdb')
  284. self.data['group'] = model.dateConfig()
  285. search_group = self.input('group')
  286. search_start = self.input('start')
  287. search_end = self.input('end')
  288. search = {}
  289. search['device'] = self.data['deviceInfo']['id']
  290. if search_group:
  291. search['group'] = search_group
  292. else:
  293. search['group'] = '1'
  294. if search_start:
  295. search['start'] = search_start
  296. if search_end:
  297. search['end'] = search_end
  298. search['type'] = type
  299. search['id'] = id
  300. self.data['search'] = search
  301. self.data['statList'] = model.getData(method, search, self.data['deviceInfo'])
  302. return self.data
  303. @staticmethod
  304. def stat(self):
  305. id, type = Device.init(self, search={'hardware_type--ins':[2,4]})
  306. if not id:
  307. return
  308. device = self.input('device')
  309. Device.statBase(self, self.data['device'][0], device)
  310. self.data['url'] = Device.url('type='+type+'&id=' + id)
  311. @staticmethod
  312. def out(self):
  313. id, type = Device.init(self, search={'hardware_type--ins':[2,4]})
  314. if not id:
  315. return
  316. out = self.input('out')
  317. if not out:
  318. device = self.inputs('device')
  319. data = []
  320. header = []
  321. datas = {}
  322. header.append('日期')
  323. for i in device:
  324. result = Device.statBase(self, self.data['device'][0], i)
  325. if result['statList']:
  326. header.append(result['deviceInfo']['name'])
  327. for t,v in result['statList'][0]['data']['rows']:
  328. if t not in datas:
  329. datas[t] = [t,v]
  330. else:
  331. datas[t].append(v)
  332. self.data['url'] = Device.url('type='+type+'&id=' + id)
  333. if datas:
  334. import csv,codecs
  335. import uuid
  336. dates = sorted(datas.keys())
  337. newData = []
  338. for i in dates:
  339. newData.append(datas[i])
  340. data = newData
  341. data.insert(0, header)
  342. fileData = data
  343. day = str(date.today())
  344. day = day.split('-')
  345. file_name = self.data['info']['name'] + '.csv'
  346. file_path = day[0] + '/' + day[1] + '/' + day[2]
  347. file_path = File.mkdirs(os.path.join(Demeter.path, 'runtime','upload', file_path)) + '/' + file_name
  348. with open(file_path, 'w') as f:
  349. f.write(codecs.BOM_UTF8)
  350. writer = csv.writer(f)
  351. for row in fileData:
  352. writer.writerow(row)
  353. url = self.request.protocol + "://" + self.request.host
  354. file_path = url + file_path.replace(Demeter.path + 'runtime', '')
  355. self.set_header("Content-Type","text/csv,charset=UTF-8")
  356. self.set_header('Content-Disposition', 'attachment; filename=' + file_name)
  357. self.redirect(file_path)
  358. else:
  359. self.data['search'] = {}
  360. @staticmethod
  361. def log(self):
  362. id, type = Device.init(self)
  363. if not id:
  364. return
  365. ids = []
  366. device_type = {}
  367. device_hard = {}
  368. device_list = []
  369. for value in self.data['device']:
  370. ids.append(value['id'])
  371. value['cdates'] = Demeter.date(value['udate'], '%Y.%m.%d')
  372. if value['type_id']:
  373. info = self.service('common').one('setting_device_type', id=value['type_id'])
  374. if info['id'] not in device_type:
  375. device_type[info['id']] = {'name':info['name'], 'num':1, 'cdate':value['cdates']}
  376. else:
  377. num = device_type[info['id']]['num'] + 1
  378. device_type[info['id']] = {'name':info['name'], 'num':num, 'cdate':value['cdates']}
  379. elif '网关' in value['name']:
  380. value['name'] = '通讯网关'
  381. device_list.append({'name':value['name'], 'num':1, 'cdate':value['cdates']})
  382. elif value['hardware_type'] > 0:
  383. info = self.service('common').one('hardware_type', id=value['hardware_type'])
  384. if info['id'] not in device_hard:
  385. device_hard[info['id']] = {'name':info['name'], 'num':1, 'cdate':value['cdates']}
  386. else:
  387. num = device_hard[info['id']]['num'] + 1
  388. device_hard[info['id']] = {'name':info['name'], 'num':num, 'cdate':value['cdates']}
  389. if device_hard:
  390. for key, value in device_hard.items():
  391. device_list.append({'name':value['name'], 'num':value['num'], 'cdate':value['cdate']})
  392. if device_type:
  393. for key, value in device_type.items():
  394. device_list.append({'name':value['name'], 'num':value['num'], 'cdate':value['cdate']})
  395. self.data['list'] = device_list
  396. # 获取设备日志
  397. self.data['logs'] = self.service('common').list('msg', state=True, search={'device_id-input-ins':ids}, page={'num':6})
  398. if self.data['logs']:
  399. for key, value in enumerate(self.data['logs']):
  400. type_info = self.service('common').one('msg_type', id=value['type_id'])
  401. self.data['logs'][key]['type'] = type_info['name']
  402. self.data['logs'][key]['cdates'] = Demeter.date(value['cdate'])
  403. @staticmethod
  404. def url(param):
  405. config = {}
  406. config['data'] = '/device/data?' + param;
  407. config['stat'] = '/device/stat?' + param;
  408. config['log'] = '/device/log?' + param;
  409. config['pic'] = '/device/pic?' + param;
  410. config['out'] = '/device/out?' + param + '&out=1';
  411. return config
  412. @staticmethod
  413. def setUrl():
  414. config = {}
  415. config['mul'] = '/device/set_mul'
  416. config['timing'] = '/device/set_timing'
  417. config['loop'] = '/device/set_loop'
  418. config['condition'] = '/device/set_condition'
  419. return config