chazuo.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. import datetime
  4. import time
  5. from decimal import Decimal
  6. from apilib.monetary import RMB
  7. from apilib.utils_AES import EncryptDate
  8. from apps.web.constant import DeviceCmdCode, Const, MQTT_TIMEOUT, ErrorCode
  9. from apps.web.core.adapter.base import SmartBox
  10. from apps.web.core.exceptions import ServiceException
  11. from apps.web.core.networking import MessageSender
  12. from apps.web.device.models import Device, DeviceType
  13. from apps.web.user.models import Card, ServiceProgress, ConsumeRecord
  14. cardKey = 'FR4e1OFCnDdrYA7u'
  15. class ChargingSocketBox(SmartBox):
  16. def __init__(self, device):
  17. super(ChargingSocketBox, self).__init__(device)
  18. def translate_funcode(self, fun_code):
  19. fun_codeDict = {
  20. '01': u'查询所有端口状态',
  21. '02': u'查询端口详细信息',
  22. '03': u'上报投币充电事件',
  23. '04': u'上报刷卡事件',
  24. '05': u'上报充电结束事件',
  25. '06': u'远程停止充电',
  26. '07': u'远程启动充电',
  27. '08': u'查询投币总额',
  28. '09': u'清除投币总数',
  29. '0A': u'查询订单信息',
  30. }
  31. return fun_codeDict.get(fun_code, '')
  32. def translate_event_cmdcode(self, cmdCode):
  33. cmdDict = {
  34. }
  35. return cmdDict.get(cmdCode, '')
  36. def check_dev_status(self, attachParas=None):
  37. if attachParas.get('isTempPackage') == True:
  38. washConfig = self.device.get('tempWashConfig', {})
  39. else:
  40. washConfig = self.device.get('washConfig', {})
  41. packageId = attachParas.get('packageId')
  42. if not packageId: # 此时为快捷启动充电之前已经校验过一次
  43. return
  44. package = washConfig.get(packageId)
  45. self._check_package(package)
  46. port = int(attachParas['chargeIndex'])
  47. port_stat = self.get_port_status_from_dev().get(str(port), {})
  48. if port_stat.get('status') not in [Const.DEV_WORK_STATUS_CONNECTED, Const.DEV_WORK_STATUS_WORKING]:
  49. raise ServiceException({'result': 2, 'description': u'请先连接充电插座,再启动充电'})
  50. if package.get('name') == '充满自停' and package.get('coins') == 0 and package.get('price') == 0:
  51. if port_stat.get('status') == Const.DEV_WORK_STATUS_WORKING:
  52. raise ServiceException({'result': 2, 'description': u'当前端口已处于工作状态,无法使用充满自停套餐, 请换个端口进行充电'})
  53. def get_port_info(self, port):
  54. data = {'fun_code': 2, 'port': int(port)}
  55. devInfo = self.send_mqtt(data)
  56. portInfo = devInfo.get('data', {})
  57. result = {}
  58. pay_unit = self.show_pay_unit
  59. exec_orders = portInfo.get('exec_orders', [])
  60. _wait = []
  61. for exec_order in exec_orders:
  62. if exec_order['status'] == 'running':
  63. result['voltage'] = round(portInfo.get('volt', 0), 2)
  64. result['power'] = round(portInfo.get('watt', 0), 2)
  65. result['ampere'] = round((portInfo.get('ampr', 0) * 0.001), 2)
  66. result['coins'] = '{}'.format(round(exec_order['amount'] / 100.0, 2))
  67. result['usedTime'] = round(exec_order.get('time', 0) / 60.0, 1)
  68. result['usedElec'] = round(exec_order.get('elec', 0) * 0.000001, 4)
  69. result['startTime'] = datetime.datetime.fromtimestamp(int(exec_order['exec_time'])).strftime(
  70. '%m-%d %H:%M:%S')
  71. if exec_order['chrmt'] == 'TIME':
  72. result['leftTime'] = round(exec_order.get('left_time', 0) / 60.0, 1)
  73. result['needTime'] = '{}分钟'.format(round(exec_order['amount_time'] / 60.0, 1))
  74. elif exec_order['chrmt'] == 'ELEC':
  75. result['needElec'] = round(exec_order.get('amount_elec', 0) * 0.000001, 2)
  76. result['leftElec'] = round(exec_order.get('left_elec', 0) * 0.000001, 4)
  77. else:
  78. pass
  79. if exec_order['order_type'] == 'apps_start':
  80. result['consumeType'] = 'mobile'
  81. result['consumeMoney'] = '{}{}'.format(round(exec_order.get('money', 0) * 0.01, 2), pay_unit)
  82. result['leftMoney'] = '{}{}'.format(round(exec_order.get('left_money', 0) * 0.01, 2),
  83. pay_unit)
  84. try:
  85. orderNo = exec_order['id']
  86. order = ConsumeRecord.objects.filter(orderNo=orderNo).first()
  87. if not order:
  88. result['nickName'] = '经销商上分'
  89. else:
  90. result['nickName'] = order.user.nickname
  91. package = order.package
  92. if package.get('name') == '充满自停' and package.get('coins') == 0 and package.get(
  93. 'price') == 0: # 后付费
  94. result['consumeType'] = 'postpaid'
  95. result['needTime'] = '充满自停'
  96. result.pop('needElec', None)
  97. result.pop('leftMoney', None)
  98. result.pop('leftTime', None)
  99. result.pop('leftElec', None)
  100. except:
  101. pass
  102. if exec_order['order_type'] == 'card_start':
  103. result['consumeType'] = 'card'
  104. result['cardNo'] = exec_order['card_no']
  105. result['cardConsumeMoney'] = '{}{}'.format(round(exec_order.get('money', 0) * 0.01, 2),
  106. pay_unit)
  107. result['cardLeftMoney'] = '{}{}'.format(round(exec_order.get('left_money', 0) * 0.01, 2),
  108. pay_unit)
  109. result['cardBalance'] = '{}{}'.format(round(exec_order['balance'] * 0.01, 2), pay_unit)
  110. try:
  111. card = Card.objects.get(cardNo=exec_order['card_no'])
  112. result['nickName'] = card.cardName or card.nickName
  113. except:
  114. pass
  115. else:
  116. pass
  117. if exec_order['status'] == 'waiting':
  118. _one = {}
  119. if exec_order['chrmt'] == 'TIME':
  120. _one['leftTime'] = round(exec_order.get('left_time', 0) / 60.0, 1)
  121. _one['needTime'] = '{}分钟'.format(round(exec_order['amount_time'] / 60.0, 1))
  122. elif exec_order['chrmt'] == 'ELEC':
  123. _one['leftElec'] = round(exec_order.get('left_elec', 0) * 0.000001, 4)
  124. _one['needElec'] = round(exec_order.get('amount_elec', 0) * 0.000001, 2)
  125. else:
  126. pass
  127. if exec_order['order_type'] == 'apps_start':
  128. _one['consumeType'] = 'mobile'
  129. _one['coins'] = '{}{}'.format(round(exec_order['amount'] / 100.0, 2), pay_unit)
  130. try:
  131. order = ConsumeRecord.objects.filter(orderNo=exec_order['id']).first()
  132. if not order:
  133. _one['nickName'] = '经销商上分'
  134. else:
  135. _one['nickName'] = order.user.nickname
  136. except Exception:
  137. pass
  138. elif exec_order['order_type'] == 'card_start':
  139. _one['consumeType'] = 'card'
  140. _one['coins'] = '{}{}'.format(round(exec_order['amount'] / 100.0, 2), pay_unit)
  141. _one['cardNo'] = exec_order['card_no']
  142. _one['cardBalance'] = '{}{}'.format(round(exec_order['balance'] * 0.01, 2), pay_unit)
  143. try:
  144. card = Card.objects.get(cardNo=exec_order['card_no'])
  145. _one['nickName'] = card.cardName or card.nickName
  146. except:
  147. pass
  148. else:
  149. pass
  150. _wait.append(_one)
  151. if _wait:
  152. result['waittingOrder'] = _wait
  153. return result
  154. def send_mqtt(self, data, cmd=DeviceCmdCode.OPERATE_DEV_SYNC, timeout=10):
  155. """
  156. 发送mqtt 指令默认210 返回data
  157. """
  158. payload = {'IMEI': self.device.devNo, 'data': data}
  159. result = MessageSender.send(self.device, cmd,
  160. payload=payload, timeout=timeout)
  161. if not result.has_key('rst'):
  162. raise ServiceException({'result': 2, 'description': u'报文异常'})
  163. if result['rst'] == -1:
  164. raise ServiceException({'result': 2, 'description': u'充电桩正在玩命找网络,请您稍候再试'})
  165. if result['rst'] == 1:
  166. raise ServiceException({'result': 2, 'description': u'串口通讯失败,您稍候再试,或者联系客服'})
  167. if result['rst'] == 2:
  168. raise ServiceException({'result': 2, 'description': u'订单已满'})
  169. if result['rst'] == 3:
  170. raise ServiceException({'result': 2, 'description': u'端口已被禁用'})
  171. if result['rst'] == 4:
  172. raise ServiceException({'result': 2, 'description': u'检测插头未连接,请先插上插头后再使用'})
  173. if result['rst'] == 5:
  174. raise ServiceException({'result': 2, 'description': u'计费类型无效'})
  175. if result['rst'] == 7:
  176. raise ServiceException({'result': 2, 'description': u'端口计量故障'})
  177. else:
  178. if cmd in [DeviceCmdCode.OPERATE_DEV_NO_RESPONSE, DeviceCmdCode.PASSTHROUGH_OPERATE_DEV_NO_RESPONSE]:
  179. return
  180. if result.get('data') == '00':
  181. raise ServiceException({'result': 2, 'description': u'设备操作失败.请重试'})
  182. else:
  183. return result
  184. def check_params_range(self, params, minData=None, maxData=None, desc=''):
  185. # type:(str,float,float,str) -> str
  186. """
  187. 检查参数,返回字符串参数
  188. """
  189. if params is None:
  190. raise ServiceException({'result': 2, 'description': u'{} 参数错误(值为空).'.format(desc)})
  191. if not isinstance(params, Decimal):
  192. params = Decimal(params)
  193. if not minData and maxData:
  194. if not isinstance(maxData, Decimal):
  195. maxData = Decimal(maxData)
  196. if params <= maxData:
  197. return '%g' % params
  198. else:
  199. raise ServiceException(
  200. {'result': 2, 'description': u'%s超出可选范围(值为: %s),可选最大值为%g' % (desc, params, maxData)})
  201. if not maxData and minData:
  202. if not isinstance(minData, Decimal):
  203. minData = Decimal(minData)
  204. if minData <= params:
  205. return '%g' % params
  206. else:
  207. raise ServiceException(
  208. {'result': 2, 'description': u'%s超出可选范围(值为: %s),可选最小值为%g' % (desc, params, minData)})
  209. if not minData and not maxData:
  210. return '%g' % params
  211. else:
  212. if not isinstance(minData, Decimal):
  213. minData = Decimal(minData)
  214. if not isinstance(maxData, Decimal):
  215. maxData = Decimal(maxData)
  216. if minData <= params <= maxData:
  217. return '%g' % params
  218. else:
  219. raise ServiceException(
  220. {'result': 2, 'description': u'%s参数超出可选范围(值为: %s),可取范围为%g-%g' % (desc, params, minData, maxData)})
  221. def test(self, coins):
  222. data = {'fun_code': 0x07, 'order_id': '1111', 'coins': coins, 'port': 1, 'time': 60}
  223. devInfo = self.send_mqtt(data)
  224. return devInfo
  225. def _check_package(self, package):
  226. """
  227. 获取设备启动的发送数据 根据设备的当前模式以及套餐获取
  228. :param package:
  229. :return:
  230. """
  231. unit = package.get('unit')
  232. _time = package.get('time')
  233. chrmt = self.device['otherConf'].get('chrmt')
  234. if not chrmt:
  235. chrmt = self.get_dev_setting().get('chrmt')
  236. # 按时间计费
  237. if chrmt == 'TIME' or chrmt == 'POWER':
  238. billingType = 'time'
  239. if unit == u'小时':
  240. _time = _time * 60
  241. elif unit == u'天':
  242. _time = _time * 24 * 60
  243. elif unit == u'秒':
  244. _time = _time / 60
  245. elif unit == u'分钟':
  246. _time = _time
  247. else:
  248. raise ServiceException({'result': 2, 'description': u'套餐单位错误,应选取单位(时间),请联系经销商'})
  249. # 按电量计费
  250. elif chrmt == 'ELEC':
  251. billingType = 'elec'
  252. if unit != u'度':
  253. raise ServiceException({'result': 2, 'description': u'套餐单位错误,应选取单位(度),请联系经销商'})
  254. else:
  255. _time = _time * 100
  256. else:
  257. raise ServiceException({'result': 2, 'description': u'套餐单位错误,应选取单位(时间,度),请联系经销商'})
  258. return _time, unit, billingType
  259. # 访问设备,获取设备端口信息
  260. def get_port_status_from_dev(self):
  261. data = {'fun_code': 0x01, 'all': True}
  262. devInfo = self.send_mqtt(data)
  263. portData = devInfo['data']['port_stat']
  264. result = {}
  265. for k, v in portData.items():
  266. if v == 'idle':
  267. result[k] = {'status': Const.DEV_WORK_STATUS_IDLE}
  268. elif v == 'link':
  269. result[k] = {'status': Const.DEV_WORK_STATUS_CONNECTED}
  270. elif v == 'busy':
  271. result[k] = {'status': Const.DEV_WORK_STATUS_WORKING}
  272. elif v == 'fault':
  273. result[k] = {'status': Const.DEV_WORK_STATUS_FAULT}
  274. elif v == 'forbid':
  275. result[k] = {'status': Const.DEV_WORK_STATUS_FORBIDDEN}
  276. else:
  277. result[k] = {'status': Const.DEV_WORK_STATUS_FAULT}
  278. allPorts, usedPorts, usePorts = self.get_port_static_info(result)
  279. Device.update_dev_control_cache(self._device['devNo'],
  280. {'allPorts': allPorts, 'usedPorts': usedPorts, 'usePorts': usePorts})
  281. # 这里存在多线程更新缓存的场景,可能性比较低,但是必须先取出来,然后逐个更新状态,然后再记录缓存
  282. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  283. for strPort, info in result.items():
  284. if ctrInfo.has_key(strPort):
  285. ctrInfo[strPort].update({'status': info['status']})
  286. else:
  287. ctrInfo[strPort] = info
  288. Device.update_dev_control_cache(self._device['devNo'], ctrInfo)
  289. return result
  290. def get_port_status(self, force=False):
  291. if force:
  292. return self.get_port_status_from_dev()
  293. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  294. if not ctrInfo.has_key('allPorts'):
  295. self.get_port_status_from_dev()
  296. ctrInfo = Device.get_dev_control_cache(self._device['devNo'])
  297. allPorts = ctrInfo.get('allPorts', 2)
  298. statusDict = {}
  299. for ii in range(allPorts):
  300. tempDict = ctrInfo.get(str(ii + 1), {})
  301. if tempDict.has_key('status'):
  302. statusDict[str(ii + 1)] = {'status': tempDict.get('status')}
  303. elif tempDict.has_key('isStart'):
  304. if tempDict['isStart']:
  305. statusDict[str(ii + 1)] = {'status': Const.DEV_WORK_STATUS_WORKING}
  306. else:
  307. statusDict[str(ii + 1)] = {'status': Const.DEV_WORK_STATUS_IDLE}
  308. else:
  309. statusDict[str(ii + 1)] = {'status': Const.DEV_WORK_STATUS_IDLE}
  310. allPorts, usedPorts, usePorts = self.get_port_static_info(statusDict)
  311. Device.update_dev_control_cache(self._device['devNo'],
  312. {'allPorts': allPorts, 'usedPorts': usedPorts, 'usePorts': usePorts})
  313. return statusDict
  314. def start_device(self, package, openId, attachParas):
  315. if attachParas is None:
  316. raise ServiceException({'result': 2, 'description': u'请您选择合适的充电线路、电池类型信息'})
  317. if not attachParas.has_key('chargeIndex'):
  318. raise ServiceException({'result': 2, 'description': u'请您选择合适的充电线路'})
  319. port = int(attachParas['chargeIndex'])
  320. _time, unit, billingType = self._check_package(package)
  321. if package.get('name') == '充满自停' and package.get('coins') == 0 and package.get('price') == 0:
  322. coins = 10 * 100
  323. else:
  324. coins = int(float(package['coins']) * 100) # 单位为分
  325. if attachParas.get('onPoints'):
  326. orderNo = ConsumeRecord.make_no() + self.device.owner.username
  327. else:
  328. orderNo = attachParas.get('orderNo')
  329. data = {
  330. 'fun_code': 0x07,
  331. 'port': port,
  332. 'amount': coins,
  333. 'order_id': orderNo
  334. }
  335. devInfo = self.send_mqtt(data, timeout=MQTT_TIMEOUT.START_DEVICE)
  336. ctrInfo = Device.get_dev_control_cache(self.device.devNo)
  337. lineInfo = ctrInfo.get(str(port), {})
  338. if not lineInfo or lineInfo.get('status') == Const.DEV_WORK_STATUS_IDLE:
  339. lineInfo = {
  340. 'port': str(port),
  341. 'status': Const.DEV_WORK_STATUS_WORKING,
  342. 'order_type': 'apps_start',
  343. 'startTime': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  344. 'orderNo': orderNo,
  345. }
  346. Device.update_port_control_cache(self._device['devNo'], lineInfo)
  347. devInfo['consumeOrderNo'] = orderNo
  348. devInfo['sequanceNo'] = orderNo
  349. if billingType == 'time':
  350. devInfo['finished_time'] = int(time.time()) + _time * 60
  351. else:
  352. devInfo['finished_time'] = int(time.time()) + 3600 * 12
  353. devInfo['ignoreService'] = True
  354. devInfo['servicedInfo'] = {
  355. 'chargeIndex': port
  356. }
  357. return devInfo
  358. def active_deactive_port(self, port, active):
  359. if active:
  360. raise ServiceException({'result': 2, 'description': u'该设备不支持直接打开端口'})
  361. return self.stop_charging_port(port)
  362. # 停止该端口下的所有任务
  363. def stop_charging_port(self, port):
  364. data = {'fun_code': 0x06, 'port': port}
  365. devInfo = self.send_mqtt(data)
  366. if devInfo['rst'] == 0:
  367. Device.update_dev_control_cache(self._device['devNo'], {str(port): {'status': Const.DEV_WORK_STATUS_IDLE}})
  368. return True if devInfo['rst'] == 0 else False
  369. def analyze_event_data(self, data):
  370. if data['fun_code'] == '32': # 成功启动设备需要回复该事件
  371. return data['order']
  372. if data['fun_code'] == '34': # 如果是结束事件,需要把reason翻译出来
  373. descDict = {
  374. 'outofmoney': u'购买的充电时间或电量用完了',
  375. 'userstop': u'用户远程结束充电',
  376. 'adminstop': u'管理员远程结束充电',
  377. 'dealerstop': u'经销商远程结束充电',
  378. 'unplug': u'未检测到充电器, 结束充电',
  379. 'wattoverload': u'功率过载, 结束充电',
  380. 'voltoverload': u'电压过载, 结束充电',
  381. 'amproverload': u'电流过载, 结束充电',
  382. 'machoverload': u'整机功率过载, 结束充电',
  383. 'tempexcursion': u'温度过载, 结束充电',
  384. 'stopforfull': u'充满自停, 结束充电'
  385. }
  386. order = data['order']
  387. order['reasonDesc'] = descDict.get(str(order['cause_desc']), u'')
  388. data['order'] = order
  389. return data
  390. def ack_event(self, order_id, fun_code):
  391. data = {'order_id': order_id, 'fun_code': fun_code}
  392. self.send_mqtt(data)
  393. def get_card_pwd(self):
  394. devInfo = self.send_mqtt({'fun_code': 17})
  395. data = devInfo.get('data', {})
  396. card_cur_key = data.get('card_cur_key')
  397. enObj = EncryptDate(cardKey)
  398. card_cur_key = enObj.decrypt(card_cur_key)
  399. return {'card_pwd': card_cur_key}
  400. def set_device_function(self, request, lastSetConf):
  401. if request.POST.has_key('clearSum'):
  402. self.clear_dev_feecount()
  403. elif request.POST.has_key('reboot'):
  404. self.reboot_device()
  405. def set_device_function_param(self, request, lastSetConf):
  406. """
  407. 设置参数 对于计费模式做一下转换 顺便服务器保留一份
  408. :param request:
  409. :param lastSetConf:
  410. :return:
  411. """
  412. # 服务器侧的参数 先处理掉
  413. if request.POST.get('id_card_oncefee') is not None:
  414. id_card_oncefee = request.POST['id_card_oncefee']
  415. if not id_card_oncefee:
  416. raise ServiceException({'result': 2, 'description': u'在线卡单次刷卡金额不能为0'})
  417. Device.get_collection().update_one(filter={'devNo': self.device.devNo},
  418. update={'$set': {
  419. 'otherConf.id_card_oncefee': round(float(id_card_oncefee), 2),
  420. }})
  421. Device.invalid_device_cache(self.device.devNo)
  422. if request.POST.get('refundProtection') is not None:
  423. refundProtection = request.POST['refundProtection']
  424. Device.get_collection().update_one(filter={'devNo': self.device.devNo},
  425. update={'$set': {
  426. 'otherConf.refundProtection': round(float(refundProtection), 2),
  427. }})
  428. Device.invalid_device_cache(self.device.devNo)
  429. if request.POST.get('minAfterStartCoins') is not None:
  430. minAfterStartCoins = request.POST['minAfterStartCoins']
  431. Device.get_collection().update_one(filter={'devNo': self.device.devNo},
  432. update={'$set': {
  433. 'otherConf.minAfterStartCoins': round(float(minAfterStartCoins), 2),
  434. }})
  435. Device.invalid_device_cache(self.device.devNo)
  436. # 参数发向设备 11, 16指令
  437. setconfig1 = {'fun_code': 11}
  438. setconfig2 = {'fun_code': 16}
  439. # 音量适配
  440. if request.POST.get('volume_list'):
  441. volume_list = request.POST.get('volume_list')
  442. volumes = {}
  443. self.check_params_range(params=request.POST.get('volume'), minData=0.0, maxData=7.0, desc='语音音量参数')
  444. volumes.update({'default': int(request.POST.get('volume'))})
  445. for obj in volume_list:
  446. self.check_params_range(params=obj['volume'], minData=0.0, maxData=7.0, desc='音量参数')
  447. volumes.update({'{}-{}'.format(obj['start'], obj['end']): int(obj['volume'])})
  448. setconfig1.update({'volumes': volumes})
  449. # 计价模式适配
  450. chrmt = request.POST.get('chrmt')
  451. package_time = request.POST.get('package_time', [])
  452. package_elec = request.POST.get('package_elec', [])
  453. package_power = request.POST.get('package_power', [])
  454. if chrmt:
  455. price = {'ELEC': int(float(package_elec[0]['elec']) * 1000000)}
  456. # 组织功率收费价格参数
  457. TIME = []
  458. if chrmt == 'POWER': # 主板实际并没有power计费方式 实际为功率分档模式的换一种显示
  459. for _item in package_power:
  460. if float(_item['price']) == 0:
  461. raise ServiceException({'result': 2, 'description': u'计费参数设置(按功率收费)价格不能为0'})
  462. TIME.append(
  463. [int(_item['power']), round(1.0 / float(_item['price']) * 60 * 60, 1)]
  464. # 价格倍率 * 固定时间(60分钟) * 60秒
  465. )
  466. if not TIME:
  467. raise ServiceException({'result': 2, 'description': u'计费参数设置(按功率收费)缺少收费标准'})
  468. setconfig1['chrmt'] = 'TIME'
  469. elif chrmt == 'TIME': # 时间模式下 的时间计费规则
  470. for _item in package_time:
  471. TIME.append(
  472. [int(_item['power']), int(_item['time']) * 60]
  473. )
  474. if not TIME:
  475. raise ServiceException({'result': 2, 'description': u'计费参数设置(按时间收费)缺少收费标准'})
  476. price['TIME'] = TIME
  477. setconfig1['chrmt'] = 'TIME'
  478. elif chrmt == 'ELEC': # 同样也处理一次时间计费规则 用于下发给设备
  479. for _item in package_time:
  480. TIME.append(
  481. [int(_item['power']), int(_item['time']) * 60]
  482. )
  483. setconfig1['chrmt'] = 'ELEC'
  484. price['TIME'] = TIME
  485. setconfig1.update({'price': price})
  486. if request.POST.get('auto_close') is not None:
  487. setconfig1.update({'auto_close': request.POST.get('auto_close')})
  488. if request.POST.get('float_time') or request.POST.get('float_watt') or request.POST.get('check_time'):
  489. float_charge = {}
  490. if request.POST.get('float_time'):
  491. float_charge['float_time'] = int(request.POST.get('float_time'))
  492. if request.POST.get('float_watt'):
  493. float_charge['float_watt'] = int(request.POST.get('float_watt'))
  494. if request.POST.get('check_time'):
  495. float_charge['check_time'] = int(request.POST.get('check_time'))
  496. setconfig1.update({'float_charge': float_charge})
  497. if request.POST.get('port_max_watt'):
  498. setconfig1.update({'port_max_watt': int(request.POST.get('port_max_watt'))})
  499. if request.POST.get('port_max_ampr'):
  500. setconfig1.update({'port_max_ampr': int(request.POST.get('port_max_ampr'))})
  501. if request.POST.get('mach_max_watt'):
  502. setconfig1.update({'mach_max_watt': int(request.POST.get('mach_max_watt'))})
  503. if request.POST.get('mach_max_temp'):
  504. setconfig1.update({'mach_max_temp': int(request.POST.get('mach_max_temp'))})
  505. if request.POST.get('mach_max_volt'):
  506. setconfig1.update({'mach_max_volt': int(request.POST.get('mach_max_volt'))})
  507. if request.POST.get('noload_check_watt') or request.POST.get('noload_check_time'):
  508. noload_check = {}
  509. if request.POST.get('noload_check_watt'):
  510. noload_check['watt'] = int(request.POST.get('noload_check_watt'))
  511. if request.POST.get('noload_check_time'):
  512. noload_check['time'] = int(request.POST.get('noload_check_time'))
  513. setconfig1.update({'noload_check': noload_check})
  514. if request.POST.get('card_pwd'):
  515. card_pwd = request.POST.get('card_pwd')
  516. card_pwd2 = request.POST.get('card_pwd2')
  517. if card_pwd != card_pwd2:
  518. raise ServiceException({'result': 2, 'description': u'两次密码输入不一致'})
  519. self.check_pwd(card_pwd)
  520. enObj = EncryptDate(cardKey)
  521. setconfig2.update({'card_cur_key': enObj.encrypt(card_pwd)})
  522. self.send_mqtt(setconfig1)
  523. unit_price = None
  524. if chrmt == 'TIME':
  525. unit_price = {'unit': '分钟', 'value': max(map(lambda _: _[1] / 60.0, setconfig1['price']['TIME']))}
  526. elif chrmt == 'POWER':
  527. unit_price = {'unit': '分钟', 'value': max(map(lambda _: _[1] / 60.0, setconfig1['price']['TIME']))}
  528. elif chrmt == 'ELEC':
  529. unit_price = {'unit': '度', 'value': round(setconfig1['price']['ELEC'] / 1000000.0, 2)}
  530. if unit_price:
  531. Device.get_collection().update_one(filter={'devNo': self.device.devNo},
  532. update={'$set': {
  533. 'otherConf.unit_price': unit_price,
  534. 'otherConf.chrmt': chrmt,
  535. }})
  536. Device.invalid_device_cache(self.device.devNo)
  537. if request.POST.get('card_refund', None) is not None:
  538. setconfig2.update({'card_refund': request.POST.get('card_refund')})
  539. if request.POST.get('card_disable', None) is not None:
  540. setconfig2.update({'card_disable': request.POST.get('card_disable')})
  541. if request.POST.get('card_timeout'):
  542. setconfig2.update({'card_timeout': int(request.POST.get('card_timeout'))})
  543. if request.POST.get('card_oncefee'):
  544. setconfig2.update({'card_oncefee': int(float(request.POST.get('card_oncefee')) * 100)})
  545. self.send_mqtt(setconfig2)
  546. def get_dev_setting(self):
  547. """
  548. 获取参数显示在前台
  549. :return:
  550. """
  551. # 服务器侧的参数
  552. otherConf = self.device['otherConf']
  553. # 获取主板侧的参数
  554. devInfo = self.send_mqtt({'fun_code': 12})
  555. # 参数整合
  556. data = dict()
  557. # ID卡刷卡一次的费用
  558. data['id_card_oncefee'] = otherConf.get('id_card_oncefee', 1)
  559. data['refundProtection'] = otherConf.get('refundProtection', 5)
  560. data['minAfterStartCoins'] = otherConf.get('minAfterStartCoins', 0)
  561. configs = devInfo['data']
  562. # 价格适配
  563. price_for_time = configs['price']['TIME']
  564. package_time = []
  565. chrmt = configs.get('chrmt')
  566. # 按功率分档收费显示
  567. for _item in price_for_time:
  568. package_time.append({'power': _item[0], 'time': round(_item[1] / 60.0, 1)})
  569. # 按电量收费
  570. price_for_elec = round(configs['price']['ELEC'] / 1000000.0, 4)
  571. package_elec = [{'elec': price_for_elec, 'price': 1}] # 电量的固定单位是1
  572. # 按功率收费显示
  573. package_power = []
  574. for _item in price_for_time:
  575. package_power.append({'power': _item[0], 'price': round(1.0 / (_item[1] / 60.0 / 60.0), 2)})
  576. # 计费规则的添加 有就显示服务器的, 没有就显示主板的
  577. data.update({
  578. 'package_time': package_time,
  579. 'package_elec': package_elec,
  580. 'package_power': package_power,
  581. 'chrmt': otherConf.get('chrmt', chrmt) # 以缓存的为准
  582. })
  583. # 浮充参数的添加
  584. float_charge = configs.get('float_charge', {})
  585. data.update(float_charge)
  586. data['auto_close'] = configs.get('auto_close', {})
  587. data['mach_max_watt'] = configs.get('mach_max_watt', 0)
  588. data['port_max_ampr'] = configs.get('port_max_ampr', 0)
  589. data['port_max_watt'] = configs.get('port_max_watt', 0)
  590. data['mach_max_volt'] = configs.get('mach_max_volt', 0)
  591. data['mach_max_temp'] = configs.get('mach_max_temp', 0)
  592. # 空载适配
  593. data.update({
  594. 'noload_check_watt': int(configs['noload_check'].get('watt', 0)),
  595. 'noload_check_time': int(configs['noload_check'].get('time', 0)),
  596. })
  597. # 音量适配
  598. volume_list = []
  599. for k, v in configs['volumes'].items():
  600. item = {}
  601. if k == 'default':
  602. continue
  603. if '-' in k:
  604. item['start'], item['end'] = k.split('-')
  605. item['volume'] = v
  606. volume_list.append(item)
  607. data.update({
  608. 'volume': configs['volumes']['default'],
  609. 'volume_list': volume_list
  610. })
  611. # 17 指令
  612. devInfo = self.send_mqtt({'fun_code': 17})
  613. configs2 = devInfo.get('data')
  614. data['card_curmode'] = configs2['card_curmode']
  615. data['card_refund'] = configs2['card_refund']
  616. data['card_disable'] = configs2['card_disable']
  617. # data['card_token'] = configs2['card_token']
  618. data['card_timeout'] = configs2['card_timeout']
  619. data['card_oncefee'] = round(configs2['card_oncefee'] / 100.0, 2)
  620. state = self.get_dev_consume_count()
  621. data.update(state)
  622. return data
  623. def get_dev_consume_count(self):
  624. data = {'fun_code': 8}
  625. devInfo = self.send_mqtt(data)
  626. total_card = round(devInfo.get('data', {}).get('total_card', 0) * 0.01, 2)
  627. return {'total_card': total_card}
  628. def reset_total_card(self):
  629. data = {
  630. 'fun_code': 9
  631. }
  632. self.send_mqtt(data)
  633. def set_max_watt(self, max_watt):
  634. self.send_mqtt({'fun_code': 11, 'max_watt': int(max_watt)})
  635. def lock_unlock_port(self, port, lock=True):
  636. portInfo = self.get_port_info(port)
  637. if portInfo and portInfo['status'] == Const.DEV_WORK_STATUS_WORKING and lock:
  638. raise ServiceException({'result': 2, 'description': u'端口正忙,请先关闭端口后,再禁止端口'})
  639. typeStr = not lock
  640. self.send_mqtt({'port': int(port), 'enable': typeStr, 'fun_code': 13})
  641. def check_pwd(self, pwd):
  642. if len(pwd) != 6:
  643. raise ServiceException({'result': 2, 'description': u'密码必须是6位纯数字密码'})
  644. for char in pwd:
  645. if not (char >= '0' and char <= '9'):
  646. raise ServiceException({'result': 2, 'description': u'密码必须是6位纯数字密码'})
  647. return
  648. def get_card_mode(self):
  649. devInfo = self.send_mqtt({'fun_code': 17})
  650. MAP_MODE = {
  651. 'NORMAL': 0,
  652. 'ISSUE': 1,
  653. 'MODKEY': 2,
  654. }
  655. result = {}
  656. result['card_mode'] = MAP_MODE.get(devInfo['data']['card_curmode'])
  657. return result
  658. def set_card_mode(self, setConf):
  659. cardMode = int(setConf.get('card_mode'))
  660. data = {'fun_code': 16}
  661. if cardMode == 0:
  662. data.update({'card_curmode': {'mod': 'NORMAL'}})
  663. elif cardMode == 1: # 格式化为离线卡
  664. self.check_pwd(setConf['new_pwd'])
  665. newPwd = setConf['new_pwd']
  666. if not str(setConf['balance']).isdigit():
  667. raise ServiceException({'result': 2, 'description': u'余额必须是数字'})
  668. balance = int(setConf['balance'])
  669. if not (balance >= 0 and balance <= 5000):
  670. raise ServiceException({'result': 2, 'description': u'余额必须在0和5000元之间'})
  671. card_dft_val = balance * 100 # 硬件模块记录的单位是角
  672. enObj = EncryptDate(cardKey)
  673. data.update({'card_curmode': {'mod': 'ISSUE', 'cfg': {'card_new_key': enObj.encrypt(str(newPwd)),
  674. 'card_dft_val': card_dft_val}}})
  675. elif cardMode == 2:
  676. self.check_pwd(setConf['new_pwd'])
  677. oldPwd = setConf.get('old_pwd', '')
  678. newPwd = setConf.get('new_pwd', '')
  679. enObj = EncryptDate(cardKey)
  680. data.update({'card_curmode': {'mod': 'MODKEY', 'cfg': {'card_old_key': enObj.encrypt(str(oldPwd)),
  681. 'card_new_key': enObj.encrypt(str(newPwd))}}})
  682. self.send_mqtt(data)
  683. def response_card_charge_result(self, cardNo, result):
  684. self.send_mqtt({'fun_code': 36, 'card_no': cardNo, 'result': result})
  685. def recharge_card(self, cardNo, money, orderNo=None):
  686. self.send_mqtt(
  687. {'fun_code': 36, 'result': 1, 'card_no': cardNo, 'charge': int(money * 100), 'order_id': orderNo})
  688. card = Card.objects.filter(cardNo=cardNo, dealerId=self.device.ownerId).first()
  689. balance = card.balance + money
  690. return {
  691. 'result': ErrorCode.SUCCESS,
  692. 'description': ''
  693. }, balance
  694. def response_card_balance(self, cardNo, amount, balance, result):
  695. return self.send_mqtt({'fun_code': 35, 'card_no': cardNo, 'balance': RMB.yuan_to_fen(balance),
  696. 'result': result, 'amount': RMB.yuan_to_fen(amount)})
  697. def get_current_use(self, **kw):
  698. base_data = kw.get('base_data')
  699. spDict = kw.get('spDict')
  700. sp = ServiceProgress.objects.filter(device_imei=self.device.devNo, port=spDict['port']).first()
  701. data = {'fun_code': 2, 'port': spDict.get('port')}
  702. devInfo = self.send_mqtt(data)
  703. portInfo = devInfo.get('data', {})
  704. exec_orders = portInfo.get('exec_orders', [])
  705. running_order = None
  706. waiting_order = []
  707. for exec_order in exec_orders: # 第一层筛选
  708. if exec_order['id'] not in sp.consumes:
  709. sp.consumes.remove(exec_order['id'])
  710. if exec_order['status'] == 'running':
  711. running_order = exec_order
  712. elif exec_order['status'] == 'waiting':
  713. waiting_order.append(exec_order)
  714. if len(sp.consumes) == 0: # 上一单没有正常结束 刷新此单的状态
  715. if running_order:
  716. sp.consumes.append(running_order['id'])
  717. sp.start_time = running_order['exec_time']
  718. sp.isFinished = False
  719. sp.finished_time = sp.start_time + running_order['amount_time']
  720. if waiting_order:
  721. for wait_one in waiting_order:
  722. sp.consumes.append(wait_one['id'])
  723. sp.finished_time = sp.start_time + wait_one['amount_time']
  724. sp.save()
  725. pay_unit = self.show_pay_unit
  726. result_list = [] # 数据整理返回
  727. for exec_order in exec_orders:
  728. item = {}
  729. item.update(base_data)
  730. item['orderNo'] = exec_order['id']
  731. item['port'] = exec_order['port']
  732. if exec_order['status'] == 'running':
  733. item['voltage'] = round(portInfo.get('volt', 0), 2)
  734. item['power'] = round(portInfo.get('watt', 0), 2)
  735. item['ampere'] = round((portInfo.get('ampr', 0) * 0.001), 2)
  736. item['usedTime'] = round(exec_order.get('time', 0) / 60.0, 1)
  737. # item['elec'] = round(exec_order.get('elec', 0) * 0.000001, 4)
  738. if exec_order['chrmt'] == 'TIME':
  739. item['needTime'] = '{}分钟'.format(round(exec_order.get('amount_time', 0) / 60.0, 1))
  740. item['leftTime'] = round(exec_order.get('left_time', 0) / 60.0, 1)
  741. elif exec_order['chrmt'] == 'ELEC':
  742. item['needElec'] = round(exec_order.get('amount_elec', 0) * 0.000001, 2)
  743. item['leftElec'] = round(exec_order.get('left_elec', 0) * 0.000001, 4)
  744. else:
  745. pass
  746. if exec_order['order_type'] == 'apps_start':
  747. item['consumeMoney'] = '{}{}'.format(round(exec_order.get('money', 0) * 0.01, 2), pay_unit)
  748. item['leftMoney'] = '{}{}'.format(round(exec_order.get('left_money', 0) * 0.01, 2), pay_unit)
  749. item['order'] = {
  750. 'orderNo': exec_order['id'], # 停止按钮传订单停单用
  751. 'coin': '{}{}'.format(round(exec_order.get('amount', 0) * 0.01, 2), pay_unit),
  752. 'port': exec_order['port'],
  753. 'consumeType': 'mobile',
  754. }
  755. try:
  756. orderNo = exec_order['id']
  757. order = ConsumeRecord.objects.filter(orderNo=orderNo).first()
  758. package = order.package
  759. if package.get('name') == '充满自停' and package.get('coins') == 0 and package.get(
  760. 'price') == 0: # 后付费
  761. item['order'] = {
  762. 'orderNo': exec_order['id'], # 停止按钮传订单停单用
  763. 'coin': '{}{}'.format(0, pay_unit),
  764. 'port': exec_order['port'],
  765. 'consumeType': 'postpaid'
  766. }
  767. item['needTime'] = '充满自停'
  768. item.pop('needElec', None)
  769. item.pop('leftMoney', None)
  770. item.pop('leftTime', None)
  771. item.pop('leftElec', None)
  772. elif order.attachParas.get('vCardId'):
  773. item['order']['consumeType'] = 'mobile_vcard'
  774. except:
  775. pass
  776. elif exec_order['order_type'] == 'card_start':
  777. item['cardNo'] = exec_order['card_no']
  778. item['cardConsumeMoney'] = exec_order['card_no']
  779. item['cardConsumeMoney'] = '{}{}'.format(round(exec_order.get('money', 0) * 0.01, 2), pay_unit)
  780. item['cardLeftMoney'] = '{}{}'.format(round(exec_order.get('left_money', 0) * 0.01, 2), pay_unit)
  781. item['order'] = {
  782. 'orderNo': exec_order['id'], # 停止按钮传订单停单用
  783. 'coin': '{}{}'.format(round(exec_order.get('amount', 0) * 0.01, 2), pay_unit),
  784. 'port': exec_order['port'],
  785. 'consumeType': 'card',
  786. }
  787. else:
  788. pass
  789. elif exec_order['status'] == 'waiting':
  790. if exec_order['chrmt'] == 'TIME':
  791. item['needTime'] = '{}分钟'.format(round(exec_order.get('amount_time', 0) / 60.0, 1))
  792. item['leftTime'] = round(exec_order.get('left_time', 0) / 60.0, 1)
  793. elif exec_order['chrmt'] == 'ELEC':
  794. item['needElec'] = round(exec_order.get('amount_elec', 0) * 0.000001, 2)
  795. item['leftElec'] = round(exec_order.get('left_elec', 0) * 0.000001, 2)
  796. item['desc'] = '此订单已经下发到设备上,上一单运行完毕就会自动运行此订单'
  797. item['order'] = {
  798. 'orderNo': exec_order['id'], # 停止按钮传订单停单用
  799. 'coin': '{}币'.format(round(exec_order.get('amount', 0) * 0.01, 2)),
  800. 'port': exec_order['port'],
  801. 'consumeType': 'card' if 'cardNo' in exec_order else 'mobile',
  802. }
  803. if 'cardNo' in exec_order:
  804. item['cardNo'] = exec_order['card_no']
  805. item.update(DeviceType.get_services_button(self.device['devType']['id']))
  806. result_list.append(item)
  807. return result_list
  808. def isHaveStopEvent(self):
  809. return True
  810. def stop_by_order(self, port, orderNo):
  811. data = {'fun_code': 4, 'order_id': orderNo, 'operator': 'user'}
  812. self.send_mqtt(data)
  813. def clear_dev_feecount(self):
  814. data = {'fun_code': 0x09, 'total_coin': True, 'total_card': True}
  815. self.send_mqtt(data)
  816. def reboot_device(self):
  817. # 重启单片机
  818. MessageSender.send(self.device, DeviceCmdCode.SET_DEVINFO, {'reset_mcu': True})
  819. # 重启模块
  820. MessageSender.send(self.device, DeviceCmdCode.SET_DEVINFO, {'restart': True})
  821. @property
  822. def show_pay_unit(self):
  823. """
  824. 前台显示付费的时候,目前有不同的客户希望 显示不同的单位 有的显示金币 有的显示元, 这个地方处理下
  825. :return:
  826. """
  827. if self.device['otherConf'].get('pay_unit'):
  828. return self.device['otherConf'].get('pay_unit')
  829. return u'币'
  830. def get_port_using_detail(self, port, ctrInfo, isLazy=False):
  831. return self.get_port_info(port)
  832. def stop(self, port=None):
  833. return self.stop_charging_port(int(port))
  834. # def __translate_status_from_str(self, status):
  835. # dictConf = {
  836. # 'idle': Const.DEV_WORK_STATUS_IDLE,
  837. # 'busy': Const.DEV_WORK_STATUS_WORKING,
  838. # 'forbid': Const.DEV_WORK_STATUS_FORBIDDEN,
  839. # 'fault': Const.DEV_WORK_STATUS_FAULT,
  840. # 'running': Const.DEV_WORK_STATUS_WORKING
  841. # }
  842. # return dictConf.get(status, Const.DEV_WORK_STATUS_IDLE)
  843. #
  844. # def get_many_port_info(self, portList):
  845. # data = {'fun_code': 1, 'all': True}
  846. # devInfo = self.send_mqtt(data)
  847. # portInfo = devInfo['data']
  848. # portParam = portInfo.get('port_param', {})
  849. # exec_queue = portInfo.get('exec_queue', {})
  850. #
  851. # pay_unit = self.show_pay_unit
  852. # resultDict = {}
  853. # for port, exec_orders in exec_queue.items():
  854. # if port not in portList:
  855. # continue
  856. # result = {'index': port}
  857. # onePortParam = portParam.get(port, {})
  858. # _wait = []
  859. # for exec_order in exec_orders:
  860. # if exec_order['status'] == 'running':
  861. #
  862. # result['voltage'] = round(onePortParam.get('volt', 0), 2)
  863. # result['power'] = round(onePortParam.get('watt', 0), 2)
  864. # result['ampere'] = round((onePortParam.get('ampr', 0) * 0.001), 2)
  865. # result['devTemp'] = round((portInfo.get('mach_temp', 0)), 2)
  866. # result['status'] = self.__translate_status_from_str(exec_order['status'])
  867. # result['usedTime'] = round(exec_order.get('time', 0) / 60.0, 2)
  868. # result['usedElec'] = round(exec_order.get('elec', 0) * 0.000001, 4)
  869. # result['coins'] = '{}'.format(round(exec_order['amount'] / 100.0, 2))
  870. #
  871. # if 'left_time' in exec_order:
  872. # result['leftTime'] = round(exec_order.get('left_time', 0) / 60.0, 2)
  873. #
  874. # elif 'left_elec' in exec_order:
  875. # result['leftElec'] = round(exec_order.get('left_elec', 0) * 0.000001, 4)
  876. #
  877. # if exec_order['order_type'] == 'apps_start':
  878. # result['consumeType'] = 'mobile'
  879. # result['consumeMoney'] = '{}{}'.format(round(exec_order.get('money', 0) * 0.01, 2),
  880. # pay_unit)
  881. # result['leftMoney'] = '{}{}'.format(round(exec_order.get('left_money', 0) * 0.01, 2),
  882. # pay_unit)
  883. # try:
  884. # orderNo = exec_order['id']
  885. # order = ConsumeRecord.objects.filter(orderNo=orderNo).first()
  886. # if not order:
  887. # result['nickName'] = '经销商上分'
  888. # else:
  889. # result['nickName'] = order.user.nickname
  890. # except Exception:
  891. # pass
  892. #
  893. # if exec_order['order_type'] == 'card_start':
  894. # result['consumeType'] = 'card'
  895. # try:
  896. # card = Card.objects.get(cardNo=exec_order['card_no'])
  897. # result['nickName'] = card.cardName or card.nickName
  898. # except:
  899. # pass
  900. # result['cardNo'] = exec_order['card_no']
  901. # result['cardConsumeMoney'] = '{}{}'.format(round(exec_order.get('money', 0) * 0.01, 2),
  902. # pay_unit)
  903. # result['cardLeftMoney'] = '{}{}'.format(round(exec_order.get('left_money', 0) * 0.01, 2),
  904. # pay_unit)
  905. # result['cardBalance'] = '{}{}'.format(round(exec_order['balance'] * 0.01, 2), pay_unit)
  906. #
  907. #
  908. # elif exec_order['status'] == 'waiting':
  909. # _one = {}
  910. # if exec_order['order_type'] == 'apps_start':
  911. # _one['consumeType'] = 'mobile'
  912. # try:
  913. # order = ConsumeRecord.objects.filter(orderNo=exec_order['id']).first()
  914. # if not order:
  915. # _one['nickName'] = '经销商上分'
  916. # else:
  917. # _one['nickName'] = order.user.nickname
  918. # except Exception:
  919. # pass
  920. # elif exec_order['order_type'] == 'card_start':
  921. # _one['consumeType'] = 'card'
  922. # _one['cardNo'] = exec_order['card_no']
  923. # _one['cardBalance'] = '{}{}'.format(round(exec_order['balance'] * 0.01, 2), pay_unit)
  924. #
  925. # try:
  926. # card = Card.objects.get(cardNo=exec_order['card_no'])
  927. # _one['nickName'] = card.cardName or card.nickName
  928. # except Exception:
  929. # pass
  930. #
  931. # if 'amount_time' in exec_order:
  932. # _one['needTime'] = '{}分钟'.format(round(exec_order['amount_time'] / 60.0, 1))
  933. # if 'amount_elec' in exec_order:
  934. # _one['needElec'] = '{}度'.format(round(exec_order['amount_elec'] / 1000000.0, 2))
  935. # if 'amount' in exec_order:
  936. # _one['coins'] = '{}{}'.format(round(exec_order['amount'] / 100.0, 2), pay_unit)
  937. # if 'create_time' in exec_order:
  938. # _one['createTime'] = datetime.datetime.fromtimestamp(
  939. # int(exec_order['create_time'])).strftime('%m-%d %H:%M:%S')
  940. #
  941. # _wait.append(_one)
  942. #
  943. # if _wait:
  944. # result['waittingOrder'] = _wait
  945. #
  946. # resultDict[port] = result
  947. #
  948. # return resultDict