chuifengji.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. import time
  4. from apilib.utils_datetime import timestamp_to_dt
  5. from apilib.utils_json import JsonResponse
  6. from apps.web.constant import DeviceCmdCode, Const, MQTT_TIMEOUT
  7. from apps.web.core.adapter.base import SmartBox, fill_2_hexByte
  8. from apps.web.core.exceptions import ServiceException
  9. from apps.web.core.networking import MessageSender
  10. from apps.web.device.models import Device
  11. class ChuifengjiBox(SmartBox):
  12. def __init__(self, device):
  13. super(ChuifengjiBox, self).__init__(device)
  14. def test(self, coins):
  15. devInfo = MessageSender.send(self.device, DeviceCmdCode.OPERATE_DEV_SYNC,
  16. {'IMEI': self._device['devNo'], "funCode": 'C1',
  17. 'data': '01' + '01' + '00' + '01' + '00' + '0000'})
  18. return devInfo
  19. def get_port_info_from_dev(self, line):
  20. hexPort = fill_2_hexByte(hex(int(line)), 2)
  21. devInfo = MessageSender.send(self.device, DeviceCmdCode.OPERATE_DEV_SYNC,
  22. {'IMEI': self._device['devNo'], 'funCode': 'C1', 'data': hexPort + '01000000'})
  23. if devInfo.has_key('rst') and devInfo['rst'] != 0:
  24. if devInfo['rst'] == -1:
  25. raise ServiceException({'result': 2, 'description': u'设备正在玩命找网络,您的金币还在,重试不需要重新付款,建议您试试旁边其他设备,或者稍后再试哦'})
  26. elif devInfo['rst'] == 1:
  27. raise ServiceException({'result': 2, 'description': u'设备正忙没有响应,您的金币还在,重试不需要重新付款,建议您试试旁边其他设备,或者稍后再试哦'})
  28. data = devInfo['data']
  29. status = data[8:10]
  30. hour = int(data[10:12], 16)
  31. minute = int(data[12:14], 16)
  32. second = int(data[14:16], 16)
  33. leftTime = hour * 60 * 60 + minute * 60 + second
  34. if status == '01':
  35. return {'port': line, 'leftTime': leftTime, 'status': Const.DEV_WORK_STATUS_IDLE}
  36. elif status == '02':
  37. return {'port': line, 'leftTime': leftTime, 'status': Const.DEV_WORK_STATUS_WORKING}
  38. elif status == '03':
  39. return {'port': line, 'leftTime': leftTime, 'status': Const.DEV_WORK_STATUS_PAUSE}
  40. else:
  41. return {'port': line, 'leftTime': leftTime, 'status': Const.DEV_WORK_STATUS_WORKING}
  42. def get_port_info(self, line):
  43. result = {str(line): {}}
  44. if str(line) in ['1', '2']:
  45. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  46. infoFromDev = self.get_port_info_from_dev(line)
  47. infoFromCache = ctrInfo.get(str(line), {})
  48. infoFromCache.update(infoFromDev)
  49. return {str(line): infoFromDev}
  50. return result
  51. def get_port_status_from_dev(self):
  52. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  53. result = {}
  54. line1Info = self.get_port_info(1)
  55. ctrInfo.update({'1': {'status': line1Info['1']['status']}})
  56. result['1'] = {'status': line1Info['1']['status']}
  57. line2Info = self.get_port_info(2)
  58. ctrInfo.update({'2': {'status': line2Info['2']['status']}})
  59. result['2'] = {'status': line2Info['2']['status']}
  60. Device.update_dev_control_cache(self._device['devNo'], ctrInfo)
  61. return result
  62. def get_port_status(self, force = False):
  63. if force:
  64. return self.get_port_status_from_dev()
  65. portDict = {}
  66. portStatus = self.get_port_status_from_dev()
  67. portDict.update({'1': {'status': portStatus['1']['status']}})
  68. portDict.update({'2': {'status': portStatus['2']['status']}})
  69. return portDict
  70. def start_device(self, package, openId, attachParas):
  71. #: 首先检查设备是否在线
  72. unit = package.get('unit', u'分钟')
  73. coins = package.get('price')
  74. port = int(attachParas.get('chargeIndex'))
  75. hexPort = fill_2_hexByte(hex(port), 2)
  76. if unit == u'分钟': # 如果单位为分钟,就认为是充电
  77. needTimeInput = int(package['time'])
  78. needTime = needTimeInput
  79. hour, minute = needTimeInput / 60, needTimeInput % 60
  80. hexHour, hexMinute, hexSecond = fill_2_hexByte(hex(hour), 2), fill_2_hexByte(hex(minute), 2), '00'
  81. elif unit == u'秒': # 如果单位是秒,就认为是接水
  82. needTimeInput = int(package['time'])
  83. needTime = needTimeInput / 60.0
  84. hour = needTimeInput / 3600
  85. minute = (needTimeInput % 3600) / 60
  86. second = (needTimeInput % 3600) % 60
  87. hexHour, hexMinute, hexSecond = fill_2_hexByte(hex(hour), 2), fill_2_hexByte(hex(minute),
  88. 2), fill_2_hexByte(hex(second),
  89. 2)
  90. else:
  91. raise ServiceException({'result': 2, 'description': u'套餐单位错误,无法启动哦'})
  92. devInfo = MessageSender.send(device = self.device,
  93. cmd = DeviceCmdCode.OPERATE_DEV_SYNC,
  94. payload = {
  95. 'IMEI': self._device['devNo'],
  96. "funCode": 'C1',
  97. 'data': hexPort + '01' + hexHour + hexMinute + hexSecond + '0000'
  98. }, timeout = MQTT_TIMEOUT.START_DEVICE)
  99. if devInfo.has_key('rst') and devInfo['rst'] != 0:
  100. if devInfo['rst'] == -1:
  101. raise ServiceException({'result': 2, 'description': u'设备正在玩命找网络,您的金币还在,重试不需要重新付款,建议您试试旁边其他设备,或者稍后再试哦'})
  102. elif devInfo['rst'] == 1:
  103. raise ServiceException({'result': 2, 'description': u'设备正在忙,无响应,您的金币还在,重试不需要重新付款,请试试其他线路,或者请稍后再试哦'})
  104. data = devInfo['data']
  105. leftSeconds = int(data[10:12], 16) * 3600 + int(data[12:14], 16) * 60 + int(data[14:16], 16)
  106. start_timestamp = int(time.time())
  107. devInfo['finishedTime'] = start_timestamp + leftSeconds
  108. value = {
  109. 'openId': openId,
  110. 'startTime': timestamp_to_dt(start_timestamp).strftime('%Y-%m-%d %H:%M:%S'),
  111. 'leftSeconds': leftSeconds,
  112. 'isStart': True,
  113. 'needTime': needTime,
  114. 'coins': coins,
  115. 'vCardId': self._vcard_id,
  116. 'status': Const.DEV_WORK_STATUS_WORKING,
  117. 'finishedTime': devInfo['finishedTime']
  118. }
  119. Device.update_dev_control_cache(self._device['devNo'], {str(port): value})
  120. return devInfo
  121. def count_down(self, request, dev, agent, group, devType, lastOpenId, port = None):
  122. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  123. if port is None:
  124. port1Info = ctrInfo.get('1', {})
  125. port2Info = ctrInfo.get('2', {})
  126. if port1Info.has_key('openId') and port1Info['openId'] == request.user.openId and port1Info['status'] in [
  127. Const.DEV_WORK_STATUS_WORKING, Const.DEV_WORK_STATUS_PAUSE]:
  128. port = '1'
  129. if port2Info.has_key('openId') and port2Info['openId'] == request.user.openId and port2Info['status'] in [
  130. Const.DEV_WORK_STATUS_WORKING, Const.DEV_WORK_STATUS_PAUSE]:
  131. port = '2'
  132. if port is None:
  133. return JsonResponse({'result': 0, 'description': u'请您重新扫码', 'payload': {}})
  134. resultDict = self.get_port_info_from_dev(port)
  135. portCache = ctrInfo.get(port, {})
  136. status = 'idle'
  137. if resultDict['status'] == Const.DEV_WORK_STATUS_WORKING:
  138. status = 'working'
  139. elif resultDict['status'] == Const.DEV_WORK_STATUS_PAUSE:
  140. status = 'pause'
  141. surplus = resultDict['leftTime'] / 60.0
  142. sumtime = portCache.get('leftSeconds', surplus) / 60.0
  143. orderProcessing = False
  144. if surplus == 0.0 and sumtime == 0.0:
  145. orderProcessing = True
  146. return JsonResponse(
  147. {
  148. 'result': 1,
  149. 'description': '',
  150. 'payload': {
  151. 'workStatus': status,
  152. 'surplus': surplus,
  153. 'sum': sumtime,
  154. 'name': group['groupName'],
  155. 'address': group['address'],
  156. 'code': devType.get('code'),
  157. 'orderProcessing': orderProcessing,
  158. 'logicalCode': dev['logicalCode'],
  159. 'user': 'me' if lastOpenId == request.user.openId else 'notme',
  160. 'agentFeatures': agent.features,
  161. }
  162. })
  163. def stop(self, port = None):
  164. hexPort = fill_2_hexByte(hex(int(port)), 2)
  165. devInfo = MessageSender.send(self.device, DeviceCmdCode.OPERATE_DEV_SYNC,
  166. {'IMEI': self._device['devNo'], "funCode": 'C1',
  167. 'data': hexPort + '04' + '0000000000'})
  168. if devInfo.has_key('rst') and devInfo['rst'] != 0:
  169. return JsonResponse({"result": 0, "description": u'网络连接异常,停止设备失败,请您重新尝试停掉设备', "payload": ''})
  170. data = devInfo['data']
  171. leftSeconds = int(data[10:12], 16) * 3600 + int(data[12:14], 16) * 60 + int(data[14:16], 16)
  172. devInfo['remainder_time'] = round(leftSeconds / 60.0, 2) #
  173. return devInfo
  174. def pause(self, openId, isContinue, port = None):
  175. if port is None:
  176. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  177. port1Info = ctrInfo.get('1', {})
  178. port2Info = ctrInfo.get('2', {})
  179. if port1Info.has_key('openId') and port1Info['openId'] == openId and port1Info['status'] in [
  180. Const.DEV_WORK_STATUS_WORKING, Const.DEV_WORK_STATUS_PAUSE]:
  181. port = '1'
  182. if port2Info.has_key('openId') and port2Info['openId'] == openId and port2Info['status'] in [
  183. Const.DEV_WORK_STATUS_WORKING, Const.DEV_WORK_STATUS_PAUSE]:
  184. port = '2'
  185. if port is None:
  186. return JsonResponse({'result': 0, 'description': u'请您重新扫码', 'payload': {}})
  187. hexPort = fill_2_hexByte(hex(int(port)), 2)
  188. if isContinue:
  189. tempData = '03'
  190. else:
  191. tempData = '02'
  192. devInfo = MessageSender.send(self.device, DeviceCmdCode.OPERATE_DEV_SYNC,
  193. {'IMEI': self._device['devNo'], "funCode": 'C1',
  194. 'data': hexPort + tempData + '0000000000'})
  195. if devInfo.has_key('rst') and devInfo['rst'] != 0:
  196. return JsonResponse({"result": 0, "description": u'网络连接异常,停止设备失败,请您重新尝试停掉设备', "payload": ''})
  197. data = devInfo['data']
  198. leftSeconds = int(data[10:12], 16) * 3600 + int(data[12:14], 16) * 60 + int(data[14:16], 16)
  199. devInfo['remainder_time'] = round(leftSeconds / 60.0, 2) #
  200. return devInfo
  201. def get_dev_setting(self):
  202. devInfo = MessageSender.send(self.device, DeviceCmdCode.OPERATE_DEV_SYNC,
  203. {'IMEI': self._device['devNo'], "funCode": 'C4', 'data': '00'})
  204. data = devInfo['data']
  205. startMoney = int(data[6:8], 16)
  206. startTime = int(data[8:10], 16)
  207. addTime = int(data[10:12], 16)
  208. coinMoney = int(data[12:16], 16)
  209. memorySwitch = True if int(data[16:18], 16) else False
  210. pulseSwitch = True if int(data[18:20], 16) else False
  211. return {'startMoney': startMoney, 'startTime': startTime, 'addTime': addTime, 'coinMoney': coinMoney,
  212. 'memorySwitch': memorySwitch, 'pulseSwitch': pulseSwitch}
  213. # 获取设备配置参数
  214. def set_dev_setting(self, setConf):
  215. data = fill_2_hexByte(hex(setConf['startMoney']), 2)
  216. data += fill_2_hexByte(hex(setConf['startTime']), 2)
  217. data += fill_2_hexByte(hex(setConf['addTime']), 2)
  218. if setConf['coinMoney'] == 0:
  219. data += '00'
  220. else:
  221. data += 'FF'
  222. data += '01' if setConf['memorySwitch'] else '00'
  223. data += '01' if setConf['pulseSwitch'] else '00'
  224. data += '0000'
  225. devInfo = MessageSender.send(self.device, DeviceCmdCode.OPERATE_DEV_SYNC,
  226. {'IMEI': self._device['devNo'], "funCode": 'C3', 'data': data})
  227. if devInfo.has_key('rst') and devInfo['rst'] != 0:
  228. return JsonResponse({"result": 0, "description": u'网络连接异常,停止设备失败,请您重新尝试停掉设备', "payload": ''})
  229. def set_device_function_param(self, request, lastSetConf):
  230. if request.POST.has_key('startMoney'):
  231. lastSetConf.update({'startMoney': int(request.POST.get('startMoney', 0))})
  232. lastSetConf.update({'startTime': int(request.POST.get('startTime', 0))})
  233. lastSetConf.update({'addTime': int(request.POST.get('addTime', 0))})
  234. self.set_dev_setting(lastSetConf)
  235. if request.POST.has_key('memorySwitch'):
  236. lastSetConf.update({'memorySwitch': int(request.POST.get('memorySwitch', 0))})
  237. self.set_dev_setting(lastSetConf)
  238. if request.POST.has_key('pulseSwitch'):
  239. lastSetConf.update({'pulseSwitch': int(request.POST.get('pulseSwitch', 0))})
  240. self.set_dev_setting(lastSetConf)
  241. def support_count_down(self, openId = None, port = None):
  242. if openId is None and port is None:
  243. return True
  244. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  245. try:
  246. port1Info = ctrInfo.get('1', {})
  247. port2Info = ctrInfo.get('2', {})
  248. if port1Info.has_key('openId') and port1Info['openId'] == openId and port1Info['status'] in [
  249. Const.DEV_WORK_STATUS_WORKING, Const.DEV_WORK_STATUS_PAUSE]:
  250. return True
  251. if port2Info.has_key('openId') and port2Info['openId'] == openId and port2Info['status'] in [
  252. Const.DEV_WORK_STATUS_WORKING, Const.DEV_WORK_STATUS_PAUSE]:
  253. return True
  254. except Exception, e:
  255. return False
  256. return False
  257. def set_device_function(self, request, lastSetConf):
  258. if request.POST.has_key('coinMoney'):
  259. # coinMoney = 0 if request.POST.get('coinMoney') == 'true' else 1
  260. coinMoney = int(not request.get("coinMoney", False))
  261. lastSetConf.update({'coinMoney': coinMoney})
  262. self.set_dev_setting(lastSetConf)