__load__.py 16 KB

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