__load__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter load
  5. author:rabin
  6. """
  7. from demeter.web 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'] > 0:
  20. self.data['setting']['userInfo'] = self.service('common').one('farm_user', id=self.data['setting']['user'])
  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'] > 0:
  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'] or 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='inorder asc, type_id asc,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'] > 0:
  164. type_info = self.service('common').one('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. control.append(value)
  187. # 获取摄像头
  188. if value['hardware_type'] == 6:
  189. value['value'] = value['value'] + '?' + Demeter.date(Demeter.time(), '%Y%m%d%H')
  190. self.data['pic'].append(value)
  191. # 获取摄像机
  192. if value['hardware_type'] == 7:
  193. self.data['camera'].append(value)
  194. """
  195. if power:
  196. power.reverse()
  197. """
  198. self.data['list'] = ({'name': '设备状态', 'device': power}, {'name': '数据采集', 'device': sensor}, {'name': '实时设备控制', 'device': control})
  199. @staticmethod
  200. def page_data(self, id):
  201. self.data['list'] = self.data['group']
  202. @staticmethod
  203. def group(self, search):
  204. self.data['show'] = False
  205. self.data['pic'] = []
  206. self.data['camera'] = []
  207. self.data['stat'] = {}
  208. for key, value in enumerate(self.data['group']):
  209. if value['devices']:
  210. search['id--ins'] = value['devices']
  211. if self.data['device_cur'] == 'stat':
  212. search['hardware_type--ins'].append(6)
  213. self.data['group'][key]['device'] = Device.get(self, search=search)
  214. if self.data['group'][key]['device']:
  215. for k, v in enumerate(self.data['group'][key]['device']):
  216. if v['hardware_type'] == 2 or v['hardware_type'] == 4:
  217. #v['value'] = Demeter.exp(v['out_exp'], v['value'])
  218. if v['hardware_type'] == 2 and self.data['info']['stat'] == True and not self.data['stat']:
  219. self.data['stat'] = v
  220. self.data['show'] = True
  221. if v['type_id'] > 0:
  222. type_info = self.service('common').one('device_type', id=v['type_id'])
  223. self.data['group'][key]['device'][k]['unit'] = type_info['unit']
  224. self.data['group'][key]['device'][k]['typeName'] = type_info['name']
  225. if self.data['device_cur'] == 'data':
  226. if v['hardware_type'] == 6:
  227. slen = len(self.data['group'][key]['device'])
  228. if slen < 2:
  229. del self.data['group'][key]['device']
  230. v['name'] = self.data['group'][key]['name']
  231. v['value'] = v['value'] + '?' + Demeter.date(Demeter.time(), '%Y%m%d%H')
  232. self.data['pic'].append(v)
  233. if v['hardware_type'] == 7:
  234. slen = len(self.data['group'][key]['device'])
  235. if slen < 2:
  236. del self.data['group'][key]['device']
  237. v['name'] = self.data['group'][key]['name']
  238. self.data['camera'].append(v)
  239. if self.data['device_cur'] == 'stat':
  240. if v['hardware_type'] == 6:
  241. self.data['pic'] = True
  242. else:
  243. self.data['device'].append(v)
  244. else:
  245. self.data['device'].append(v)
  246. @staticmethod
  247. def pic(self):
  248. id, type = Device.init(self, search={'hardware_type':6})
  249. if not id:
  250. return
  251. state = Device.get(self, search={'hardware_type--ins':(2,4)})
  252. if state:
  253. self.data['show'] = True
  254. device = self.input('device')
  255. if not device:
  256. #如果没有,就获取第一个
  257. self.data['deviceInfo'] = self.data['device'][0]
  258. else:
  259. self.data['deviceInfo'] = self.service('common').one('device_info', id=device)
  260. if not self.data['deviceInfo']:
  261. self.view('404.html')
  262. return
  263. self.data['pic'] = self.service('common').list('device_pic', search={'device_id':self.data['deviceInfo']['id']}, page={'num':12}, order='sdate desc')
  264. if self.data['pic']:
  265. for key, value in enumerate(self.data['pic']):
  266. self.data['pic'][key]['cdates'] = Demeter.date(value['sdate'])
  267. @staticmethod
  268. def statBase(self, deviceInfo={}, device = False):
  269. if not device:
  270. device = self.input('device')
  271. method = self.input('method', 'maxmin')
  272. if not device:
  273. #如果没有,就获取sensor的第一个
  274. self.data['deviceInfo'] = deviceInfo
  275. else:
  276. self.data['deviceInfo'] = self.service('common').one('device_info', id=device)
  277. if not self.data['deviceInfo']:
  278. self.view('404.html')
  279. return
  280. self.data['type'] = self.service('common').one('device_type', id=self.data['deviceInfo']['type_id'])
  281. model = Demeter.model('data', 'tsdb')
  282. self.data['group'] = model.dateConfig()
  283. search_group = self.input('group')
  284. search_start = self.input('start')
  285. search_end = self.input('end')
  286. search = {}
  287. search['device'] = self.data['deviceInfo']['id']
  288. if search_group:
  289. search['group'] = search_group
  290. else:
  291. search['group'] = '1'
  292. if search_start:
  293. search['start'] = search_start
  294. if search_end:
  295. search['end'] = search_end
  296. search['type'] = type
  297. search['id'] = id
  298. self.data['search'] = search
  299. self.data['statList'] = model.getData(method, search, self.data['deviceInfo'])
  300. return self.data
  301. @staticmethod
  302. def stat(self):
  303. id, type = Device.init(self, search={'hardware_type--ins':[2,4]})
  304. if not id:
  305. return
  306. device = self.input('device')
  307. Device.statBase(self, self.data['device'][0], device)
  308. self.data['url'] = Device.url('type='+type+'&id=' + id)
  309. @staticmethod
  310. def out(self):
  311. id, type = Device.init(self, search={'hardware_type--ins':[2,4]})
  312. if not id:
  313. return
  314. out = self.input('out')
  315. if not out:
  316. device = self.inputs('device')
  317. data = []
  318. header = []
  319. datas = {}
  320. header.append('日期')
  321. for i in device:
  322. result = Device.statBase(self, self.data['device'][0], i)
  323. if result['statList']:
  324. header.append(result['deviceInfo']['name'])
  325. for t,v in result['statList'][0]['data']['rows']:
  326. if t not in datas:
  327. datas[t] = [t,v]
  328. else:
  329. datas[t].append(v)
  330. self.data['url'] = Device.url('type='+type+'&id=' + id)
  331. if datas:
  332. import csv,codecs
  333. from datetime import *
  334. import uuid
  335. dates = sorted(datas.keys())
  336. newData = []
  337. for i in dates:
  338. newData.append(datas[i])
  339. data = newData
  340. data.insert(0, header)
  341. fileData = data
  342. day = str(date.today())
  343. day = day.split('-')
  344. file_name = self.data['info']['name'] + '.csv'
  345. file_path = day[0] + '/' + day[1] + '/' + day[2]
  346. file_path = File.mkdirs(os.path.join(Demeter.path, 'runtime','upload', file_path)) + '/' + file_name
  347. with open(file_path, 'w') as f:
  348. f.write(codecs.BOM_UTF8)
  349. writer = csv.writer(f)
  350. for row in fileData:
  351. writer.writerow(row)
  352. url = self.request.protocol + "://" + self.request.host
  353. file_path = url + file_path.replace(Demeter.path + 'runtime', '')
  354. self.set_header("Content-Type","text/csv,charset=UTF-8")
  355. self.set_header('Content-Disposition', 'attachment; filename=' + file_name)
  356. self.redirect(file_path)
  357. else:
  358. self.data['search'] = {}
  359. @staticmethod
  360. def log(self):
  361. id, type = Device.init(self)
  362. if not id:
  363. return
  364. ids = []
  365. device_type = {}
  366. device_hard = {}
  367. device_list = []
  368. for value in self.data['device']:
  369. ids.append(value['id'])
  370. value['cdates'] = Demeter.date(value['udate'], '%Y.%m.%d')
  371. if value['type_id'] > 0:
  372. info = self.service('common').one('device_type', id=value['type_id'])
  373. if info['id'] not in device_type:
  374. device_type[info['id']] = {'name':info['name'], 'num':1, 'cdate':value['cdates']}
  375. else:
  376. num = device_type[info['id']]['num'] + 1
  377. device_type[info['id']] = {'name':info['name'], 'num':num, 'cdate':value['cdates']}
  378. elif '网关' in value['name']:
  379. value['name'] = '通讯网关'
  380. device_list.append({'name':value['name'], 'num':1, 'cdate':value['cdates']})
  381. elif value['hardware_type'] > 0:
  382. info = self.service('common').one('hardware_type', id=value['hardware_type'])
  383. if info['id'] not in device_hard:
  384. device_hard[info['id']] = {'name':info['name'], 'num':1, 'cdate':value['cdates']}
  385. else:
  386. num = device_hard[info['id']]['num'] + 1
  387. device_hard[info['id']] = {'name':info['name'], 'num':num, 'cdate':value['cdates']}
  388. if device_hard:
  389. for key, value in device_hard.items():
  390. device_list.append({'name':value['name'], 'num':value['num'], 'cdate':value['cdate']})
  391. if device_type:
  392. for key, value in device_type.items():
  393. device_list.append({'name':value['name'], 'num':value['num'], 'cdate':value['cdate']})
  394. self.data['list'] = device_list
  395. # 获取设备日志
  396. self.data['logs'] = self.service('common').list('msg', state=True, search={'device_id-input-ins':ids}, page={'num':6})
  397. if self.data['logs']:
  398. for key, value in enumerate(self.data['logs']):
  399. type_info = self.service('common').one('msg_type', id=value['type_id'])
  400. self.data['logs'][key]['type'] = type_info['name']
  401. self.data['logs'][key]['cdates'] = Demeter.date(value['cdate'])
  402. @staticmethod
  403. def url(param):
  404. config = {}
  405. config['data'] = '/device/data?' + param;
  406. config['stat'] = '/device/stat?' + param;
  407. config['log'] = '/device/log?' + param;
  408. config['pic'] = '/device/pic?' + param;
  409. config['out'] = '/device/out?' + param + '&out=1';
  410. return config
  411. @staticmethod
  412. def setUrl():
  413. config = {}
  414. config['mul'] = '/device/set_mul'
  415. config['timing'] = '/device/set_timing'
  416. config['loop'] = '/device/set_loop'
  417. config['condition'] = '/device/set_condition'
  418. return config