data.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. # -*- coding: utf-8 -*-
  2. """
  3. demeter database
  4. name:data.py
  5. author:rabin
  6. """
  7. from demeter.core import *
  8. from .__load__ import *
  9. import datetime
  10. import calendar
  11. #DROP MEASUREMENT "data_4_10021011"
  12. #DROP MEASUREMENT "data_2_10022011"
  13. class Data(Model):
  14. __table__ = 'data'
  15. def setTable(self, data=False):
  16. if data and 'farm' in data:
  17. self.table = self.__table__ + '_' + str(data['farm']) + '_' + str(data['device']) + '1'
  18. def insert(self, data):
  19. self.setTable(data)
  20. json = self.insert_json(data)
  21. self.db.write_points(json)
  22. value = str(data['farm']) + '__' + str(data['device']) + '__' + str(data['hard']) + '__' + str(data['type']) + '__' + str(data['gateway']) + '__' + str(data['source']) + '__' + str(data['value'])
  23. Demeter.service('core', 'zeus').rsync(self.table, value)
  24. def insert_json(self, data):
  25. json = [
  26. {
  27. "measurement": self.table,
  28. "tags": {
  29. "hard": data['hard'],
  30. "type":data['type'],
  31. "gateway": data['gateway']
  32. },
  33. #"time": data['time'],
  34. "fields": {
  35. 'source' : float(data['source']),
  36. 'value' : float(data['value'])
  37. }
  38. }]
  39. return json
  40. def get(self, farm, device, col='value', search='', exp=''):
  41. data = {}
  42. data['farm'] = farm
  43. data['device'] = device
  44. self.setTable(data)
  45. if search:
  46. search = ' where ' + search
  47. sql = 'select ' + col + ' from ' + self.table + search
  48. data = self.db.query(sql)
  49. value = []
  50. time = []
  51. rows = []
  52. utc_format = '%Y-%m-%dT%H:%M:%S'
  53. local_format = "%Y-%m-%d %H:%M:%S"
  54. if 'series' in data.raw and data.raw['series'][0]['values']:
  55. for values in data.raw['series'][0]['values']:
  56. if values[1]:
  57. v = float(round(values[1], 2))
  58. v = Demeter.exp(exp, v)
  59. temp = values[0].split('.')
  60. uformat = utc_format
  61. if len(temp) <= 1:
  62. uformat = utc_format + 'Z'
  63. utc = Demeter.mktime(temp[0], uformat) + 3600*8
  64. date = Demeter.date(utc, local_format)
  65. value.append(v)
  66. time.append(date)
  67. rows.append([date, v])
  68. return {'time':time, 'value':value, 'rows':rows}
  69. def getData(self, method, data, config):
  70. search = ''
  71. col = 'value'
  72. utc_format = '%Y-%m-%dT%H:%M:%SZ'
  73. if ('start' in data and data['start']) or ('end' in data and data['end']):
  74. if 'start' in data and data['start']:
  75. start = Demeter.mktime(data['start'])
  76. startDate = Demeter.date(start - 3600*8, utc_format)
  77. search = 'time > \'' + str(startDate) + '\''
  78. if 'end' in data and data['end']:
  79. end = Demeter.mktime(data['end'])
  80. endDate = Demeter.date(end - 3600*8, utc_format)
  81. search = search + ' and time < \'' + str(endDate) + '\''
  82. search = search + self.group(self.day(start, end))
  83. else:
  84. now = Demeter.time()
  85. search = search + self.group(self.day(start, now))
  86. elif 'group' in data and data['group']:
  87. value = data['group']
  88. time = 'time > now()'
  89. search = time + ' - ' + value + 'd' + self.group(int(value))
  90. result = []
  91. if method == 'avg':
  92. col = 'mean(value) as value'
  93. result.append(self.load(config, search, col, '平均'))
  94. elif method == 'maxmin':
  95. col = 'max(value) as value'
  96. result.append(self.load(config, search, col, '最高'))
  97. col = 'min(value) as value'
  98. result.append(self.load(config, search, col, '最低'))
  99. else:
  100. col = 'value'
  101. if 'group' in search:
  102. temp = search.split('group')
  103. search = temp[0]
  104. result.append(self.load(config, search, col, '明细'))
  105. return result
  106. def load(self, config, search, col, name):
  107. result = {}
  108. result['data'] = self.get(config['farm_id'], config['hardware_id'], search=search, col=col)
  109. result['name'] = name
  110. if result['data']:
  111. result['data']['time'] = json.dumps(result['data']['time'])
  112. result['data']['value'] = json.dumps(result['data']['value'])
  113. return result
  114. def group(self, day):
  115. if day >= 180:
  116. return ' group by time(10d)'
  117. elif day >= 30:
  118. return ' group by time(1d)'
  119. elif day >= 7:
  120. return ' group by time(60m)'
  121. elif day >= 1:
  122. return ' group by time(10m)'
  123. else:
  124. return ' group by time(1m)'
  125. def day(self, start, end):
  126. return math.ceil(round(float((end - start) / (3600*24))))
  127. def dateConfig(self):
  128. return [{'id':'1', 'name':'一天'},{'id':'7', 'name':'一周'},{'id':'30', 'name':'一个月'},{'id':'180', 'name':'半年'}]