heshui.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. import datetime
  4. import logging
  5. import time
  6. from apilib.utils_datetime import to_datetime, timestamp_to_dt
  7. from apps.web.constant import Const, MQTT_TIMEOUT, DeviceCmdCode
  8. from apps.web.core.adapter.base import fill_2_hexByte, MqttSmartBox
  9. from apps.web.core.exceptions import ServiceException
  10. from apps.web.core.networking import MessageSender
  11. from apps.web.device.models import Device
  12. logger = logging.getLogger(__name__)
  13. class HeshuiChongdian(MqttSmartBox):
  14. def __init__(self, device):
  15. super(HeshuiChongdian, self).__init__(device)
  16. def analyze_event_data(self, data):
  17. if 'FB' == data[0:2]:
  18. return {'cmdCode':'FB','port':3}
  19. elif 'FD' in data[0:2]:
  20. if len(data) > 2:
  21. leftTime = int(data[2:6], 16)
  22. else:
  23. leftTime = -1
  24. return {'cmdCode':'FD','port':3, 'leftTime':leftTime}
  25. elif '01' in data[0:2]:
  26. return {'cmdCode':'01','usedTime':int(data[2:4],16),'port':1}
  27. elif '02' in data[0:2]:
  28. return {'cmdCode':'02','usedTime':int(data[2:4],16),'port':2}
  29. return None
  30. def get_port_info(self,line):
  31. if str(line) in ['1','2']:
  32. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  33. if ctrInfo is None or (not ctrInfo.has_key(str(line))):
  34. return {'port':line,'leftTime':0}
  35. portInfo = ctrInfo.get(str(line))
  36. if portInfo.has_key('startTime') and portInfo.has_key('needTime'):
  37. startTime = to_datetime(portInfo['startTime'])
  38. needTime = portInfo['needTime']
  39. leftTime = round((needTime - (datetime.datetime.now() - startTime).total_seconds())/60.0,2)
  40. if leftTime <= 0:
  41. return {'port':line,'leftTime':0}
  42. return {'port':line,'leftTime':leftTime}
  43. else:
  44. return {'port':line,'leftTime':0}
  45. def get_port_status(self, force = False):
  46. portDict = {}
  47. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  48. if ctrInfo.has_key('1') and ctrInfo['1'].has_key('startTime') and ctrInfo['1'].has_key('needTime'):
  49. portDict.update({'1':{'status':Const.DEV_WORK_STATUS_WORKING}})
  50. startTime = to_datetime(ctrInfo['1'].get('startTime'))
  51. if (datetime.datetime.now() - startTime).total_seconds() >= 60:
  52. portDict.update({'1':{'status':Const.DEV_WORK_STATUS_IDLE}})
  53. else:
  54. portDict.update({'1':{'status':Const.DEV_WORK_STATUS_WORKING}})
  55. elif ctrInfo.has_key('1') and ctrInfo['1'].has_key('status') and ctrInfo['1']['status'] == Const.DEV_WORK_STATUS_FORBIDDEN:
  56. portDict.update({'1':{'status':Const.DEV_WORK_STATUS_FORBIDDEN}})
  57. else:
  58. portDict.update({'1':{'status':Const.DEV_WORK_STATUS_IDLE}})
  59. if ctrInfo.has_key('2') and ctrInfo['2'].has_key('startTime') and ctrInfo['2'].has_key('needTime'):
  60. portDict.update({'2':{'status':Const.DEV_WORK_STATUS_WORKING}})
  61. startTime = to_datetime(ctrInfo['2'].get('startTime'))
  62. if (datetime.datetime.now() - startTime).total_seconds() >= 60:
  63. portDict.update({'2':{'status':Const.DEV_WORK_STATUS_IDLE}})
  64. else:
  65. portDict.update({'2':{'status':Const.DEV_WORK_STATUS_WORKING}})
  66. elif ctrInfo.has_key('2') and ctrInfo['2'].has_key('status') and ctrInfo['2']['status'] == Const.DEV_WORK_STATUS_FORBIDDEN:
  67. portDict.update({'2':{'status':Const.DEV_WORK_STATUS_FORBIDDEN}})
  68. else:
  69. portDict.update({'2':{'status':Const.DEV_WORK_STATUS_IDLE}})
  70. return portDict
  71. def lock_unlock_port(self, port, lock=True):
  72. if lock:
  73. Device.update_dev_control_cache(self._device['devNo'],
  74. {str(port): {'status': Const.DEV_WORK_STATUS_FORBIDDEN}})
  75. else:
  76. Device.update_dev_control_cache(self._device['devNo'], {str(port): {'status': Const.DEV_WORK_STATUS_IDLE}})
  77. def start_device(self, package, openId, attachParas):
  78. #: 首先检查设备是否在线
  79. unit = package.get('unit',u'分钟')
  80. coins = package.get('price')
  81. port = int(attachParas.get('chargeIndex'))
  82. if unit == u'分钟':#如果单位为分钟,就认为是充电
  83. needTimeInput = int(package['time'])
  84. needTime = needTimeInput * 60
  85. serialType = 'charger'
  86. funCode = '0A'
  87. data = fill_2_hexByte(hex(needTimeInput), 4)
  88. elif unit == u'秒':#如果单位是秒,就认为是接水
  89. needTime = int(package['time'])
  90. serialType = 'water'
  91. if port == 1:
  92. funCode = '01'
  93. else:
  94. funCode = '02'
  95. data = ''
  96. else:
  97. raise ServiceException({'result': 2, 'description': u'套餐单位错误,无法启动哦'})
  98. devInfo = MessageSender.send(device = self.device, cmd = 220, payload = {
  99. 'IMEI': self._device['devNo'],
  100. 'serialType': serialType,
  101. "funCode": funCode,
  102. 'data': data
  103. }, timeout = MQTT_TIMEOUT.START_DEVICE)
  104. if devInfo.has_key('rst') and devInfo['rst'] != 0:
  105. if devInfo['rst'] == -1:
  106. raise ServiceException({'result': 2, 'description': u'设备正在玩命找网络,您的金币还在,重试不需要重新付款,建议您试试旁边其他设备,或者稍后再试哦'})
  107. elif devInfo['rst'] == 1:
  108. raise ServiceException({'result': 2, 'description': u'设备正在忙,无响应,您的金币还在,重试不需要重新付款,请试试其他线路,或者请稍后再试哦'})
  109. start_timestamp = int(time.time())
  110. if serialType == 'charger':
  111. devInfo['finishedTime'] = start_timestamp + int(needTime)
  112. else:
  113. devInfo['finishedTime'] = start_timestamp + 60
  114. value = {
  115. 'openId': openId,
  116. 'startTime': timestamp_to_dt(start_timestamp).strftime('%Y-%m-%d %H:%M:%S'),
  117. 'serialType': serialType,
  118. 'needTime': needTime,
  119. 'coins': coins,
  120. 'vCardId': self._vcard_id,
  121. 'status': Const.DEV_WORK_STATUS_WORKING,
  122. 'finishedTime': devInfo['finishedTime']
  123. }
  124. if 'linkedRechargeRecordId' in attachParas:
  125. item = {
  126. 'rechargeRcdId': str(attachParas['linkedRechargeRecordId'])
  127. }
  128. value['payInfo'] = [item]
  129. logger.info('port value is %s' % value)
  130. Device.update_dev_control_cache(self._device['devNo'],{str(port):value})
  131. return devInfo
  132. def set_standard_pulse(self, standardPulse):
  133. standardPulse = fill_2_hexByte(hex(int(standardPulse)))
  134. MessageSender.send(self.device, DeviceCmdCode.OPERATE_DEV_SYNC,
  135. {'IMEI': self._device['devNo'], "funCode": '6b', 'data': standardPulse})
  136. def set_standard_count_and_time(self, standardCount, standardTime):
  137. standardCount = fill_2_hexByte(hex(int(standardCount)), num=2)
  138. standardTime = fill_2_hexByte(hex(int(standardTime)), num=2)
  139. MessageSender.send(self.device, DeviceCmdCode.OPERATE_DEV_SYNC,
  140. {'IMEI': self._device['devNo'], "funCode": 'f5', 'data': standardCount + standardTime})
  141. def set_unit_pulse_detection(self):
  142. MessageSender.send(self.device, DeviceCmdCode.OPERATE_DEV_SYNC,
  143. {'IMEI': self._device['devNo'], "funCode": 'b7', 'data': 'caca'})
  144. def set_device_function_param(self, request, lastSetConf):
  145. if 'standardPulse' in request.POST:
  146. standardPulse = request.POST['standardPulse']
  147. if standardPulse != '':
  148. self.set_standard_pulse(standardPulse)
  149. if 'standardCount' in request.POST and 'standardTime' in request.POST:
  150. standardCount = request.POST['standardCount']
  151. standardTime = request.POST['standardTime']
  152. if standardCount != '' and standardTime != '':
  153. self.set_standard_count_and_time(standardCount, standardTime)
  154. def get_dev_setting(self):
  155. device = Device.objects(devNo=self._device['devNo']).first()
  156. return {'isMainboardDetection': device.otherConf.get('isMainboardDetection', False)}
  157. def set_device_function(self, request, lastSetConf):
  158. if 'unitPulseDetection' in request.POST:
  159. self.set_unit_pulse_detection()
  160. if 'isMainboardDetection' in request.POST:
  161. isMainboardDetection = request.POST['isMainboardDetection']
  162. device = Device.objects(devNo=self._device['devNo']).first()
  163. device.otherConf['isMainboardDetection'] = isMainboardDetection
  164. device.save()