# -*- coding: utf-8 -*- # !/usr/bin/env python from apps.web.constant import MQTT_TIMEOUT, DeviceCmdCode from apps.web.core.adapter.base import SmartBox, fill_2_hexByte from apps.web.core.exceptions import ServiceException from apps.web.core.networking import MessageSender from apps.web.device.models import Device class FuncCode(object): CHECK_DEV = "00" PAY_DEV = "05" START_DEV = "85" class HanzhenBox(SmartBox): def __init__(self, device): super(HanzhenBox, self).__init__(device) def _send_data(self, funCode, data, cmd = DeviceCmdCode.OPERATE_DEV_SYNC, timeout = MQTT_TIMEOUT.NORMAL, orderNo = None): result = MessageSender.send(device = self.device, cmd = cmd, payload = { "IMEI": self._device["devNo"], "funCode": funCode, "data": data }, timeout = timeout) if result.has_key('rst') and result['rst'] != 0: if result['rst'] == -1: raise ServiceException({ 'result': 2, 'description': u'汗蒸机正在玩命找网络,您的金币还在,重试不需要重新付款,建议您试试旁边其他设备,或者稍后再试哦' }) elif result['rst'] == 1: raise ServiceException({ 'result': 2, 'description': u'汗蒸机正在忙,无响应,您的金币还在,请试试其他线路,或者请稍后再试哦' }) return result def __get_dev_status(self): """ 获取设备状态 数据域一共9个字节 第三个字节表示是否允许消费 00 允许 第5个字节表示设备是否正常 00 表示正常 :return: """ result = self._send_data(funCode = FuncCode.CHECK_DEV, data = "00") data = result['data'] canUse = True if data[10:12] == '00' else False isDevNormal = True if data[16:18] == '00' else False return {'canUse': canUse, 'isDevNormal': isDevNormal} @staticmethod def reverse_hex(hexCoins): """ 硬币使用高低位 :param hexCoins: :return: """ return hexCoins[2:4] + hexCoins[:2] def start_device(self, package, openId, attachParas): """ 启动设备 首先下发支付指令启动设备 得到设备回应之后 解析回应数据 要求回应指令为85 并且 回应币数和下发币数一致后 再次下发85启动指令 回应数据域为0000 :param openId: :param attachParas: :return: """ if attachParas is None: raise ServiceException({'result': 2, 'description': u'请您选择合适的商品哦'}) # hexCoins = self.reverse_hex(fill_2_hexByte(hex(int(coins)))) # 协议里面的 币数实际是分钟 真TM坑爹 unit = package['unit'] if unit != u"分钟": raise ServiceException({'result': 2, 'description': u'套餐单位错误,请联系经销商!'}) sendTime = int(package['time']) sendTimeHex = self.reverse_hex(fill_2_hexByte(hex(sendTime), 4)) # 首先将币数更新入缓存 Device.update_dev_control_cache(self._device["devNo"], {"sendTime": sendTimeHex, "openId": openId}) result = self._send_data(funCode = FuncCode.PAY_DEV, data = sendTimeHex, timeout = MQTT_TIMEOUT.START_DEVICE) return result def analyze_event_data(self, data): """ 设备上抛事件 设备上抛事件无效 :param data: :return: """ funCode = data[2:4] sendTime = data[6:10] return {"sendTime": sendTime, "funCode": funCode} def check_dev_status(self, attachParas = None): info = self.__get_dev_status() if not all([info["canUse"], info["isDevNormal"]]): raise ServiceException({ 'result': 2, 'description': u'设备故障无法启动' })