From: dxy15521469561 <1731678236@qq.com> Date: Tue, 9 Apr 2024 09:58:58 +0000 (+0800) Subject: G10联通入库 X-Git-Url: http://git.snicker.com.cn/Users/apple/Desktop/static/gitweb.css?a=commitdiff_plain;h=7bddf10c295a5c3c31fb17364d896f5b3576ec48;p=mirrors%2FASR1603_G5.git G10联通入库 G15电量播放问题 --- diff --git a/2.sdk/Helios_SDK/services/microPython/ports/quectel/core/motor.py b/2.sdk/Helios_SDK/services/microPython/ports/quectel/core/motor.py new file mode 100644 index 00000000..cd31639b --- /dev/null +++ b/2.sdk/Helios_SDK/services/microPython/ports/quectel/core/motor.py @@ -0,0 +1,112 @@ +from common import Abstract +import osTimer +import EventMesh +from machine import Pin +import utime + +from queue import Queue +import _thread +import usys + + +motor_pin = Pin(Pin.GPIO20, Pin.OUT, Pin.PULL_PD, 0) +def open_motor():#开马达 + motor_pin.write(1) + +def close_motor():#关闭马达 + motor_pin.write(0) + + + +MOTOR_TIME = 100 +class motorEventManager(Abstract):#马达事件 + def __init__(self): + self.motor_timer = osTimer() + self.motorInfo_queue = Queue() + self.motor_enable = 0#马达使能 + self.motor_total_time = 0#总的时间 + self.motor_open_time = 0 #开马达事件 + self.motor_close_time = 0#关马达事件100ms + self.motor_count = 0 + self.motor_mode = 0#模式 + _thread.start_new_thread(self.motorInfo_queue_thread, ()) + EventMesh.subscribe("publish_message_event_motorInfo",self.publish_message_event_motorInfo) + pass + + def motorInfo_queue_thread(self): + while True: + data = self.motorInfo_queue.get() + #print("ledInfo_queue:data = {}".format(data)) + if data != None: + try: + data["func"](data["data"]) + except Exception as e: + print("ledInfo_queue:ERROR:{}".format(e)) + usys.print_exception(e) + def publish_message_event_motorInfo(self,event,msg): + self.motorInfo_queue.put(msg) + + def publish_motor_event_cb(self, *args, **kwargs): + EventMesh.publish("publish_message_event_motorInfo",{"func":self.motor_fun_cb,"data":0}) + + def post_processor_after_instantiation(self): + EventMesh.subscribe("set_motor_time", self.set_motor_time)#设置参数 + EventMesh.subscribe("close_motor_infor", self.close_motor_infor)#关闭马达和定时器 + + # msg 0马达使能 1 马达振动时间100ms单位 2 震动次数 3 间隔时间振动 4 是否需要长振 5 长振时间 6间隔时间长振 7长振次数1一次 要为200ms的倍数 + def set_motor_time(self,event,msg): + open_power = EventMesh.publish("get_power_on_state")#获取开机标识 + if open_power != None: + if open_power == 0: + return + if msg != None: + self.motor_enable = msg[0] + if self.motor_enable == 1: #马达使能 + self.motor_mode = msg [1] + self.motor_total_time = msg[2]#总的时间 + self.motor_open_time = msg[3] #开马达事件 + self.motor_close_time = msg[4]#关马达事件100ms + self.motor_count = 0 + self.motor_timer.stop() + # print("motor msg",msg) + close_motor() + self.motor_timer.start(MOTOR_TIME,1,self.publish_motor_event_cb) + + def motor_fun_cb(self, data): + if self.motor_mode == 0 or self.motor_enable == 0: + close_motor() + EventMesh.publish("close_motor_infor")#关闭马达和定时器 + return + if self.motor_mode == 1:# + if self.motor_total_time > 0: + self.motor_total_time-=1 + if self.motor_total_time > 0: + open_motor() + else: + close_motor() + EventMesh.publish("close_motor_infor")#关闭马达和定时器 + return + elif self.motor_mode == 2:# + # print("self.motor_count",self.motor_count,self.motor_open_time,self.motor_close_time,self.motor_total_time) + if self.motor_count % (self.motor_open_time) < self.motor_close_time: # 4 4 2 1%4 = 1 2%4 = 2 3%4 = 3 + open_motor() + else: + close_motor() + if self.motor_count >= self.motor_total_time-1: + EventMesh.publish("close_motor_infor")#关闭马达和定时器 + return + self.motor_count+=1 + + def close_motor_infor(self,event,msg): + print("close_motor_infor!!!") + close_motor() + self.motor_enable = 0#马达使能 + self.motor_total_time = 0#总的时间 + self.motor_open_time = 0 #开马达事件 + self.motor_close_time = 0#关马达事件100ms + self.motor_count = 0 + self.motor_mode = 0#模式 + self.motor_timer.stop() + + + diff --git a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/EventMesh.py b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/EventMesh.py index 53ab6c89..e0c70919 100644 --- a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/EventMesh.py +++ b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/EventMesh.py @@ -4,9 +4,12 @@ import versions import ql_fs model = "D15" - +# model = "D10" project = "D15" +# project = "D10" +# platform = "gewu"#格物平台 不用的话选择空 如果需要联通入库的需求就要打开 不需要就得写空通过变量区分 +platform = ""#格物平台 不用的话选择空 # model = "G10W_DT_YBX_" diff --git a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/btn_device_ec800m_d15.py b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/btn_device_ec800m_d15.py index 30ec04f3..e398b13f 100644 --- a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/btn_device_ec800m_d15.py +++ b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/btn_device_ec800m_d15.py @@ -1874,6 +1874,7 @@ if EventMesh.model == "D15" : level = 100 else: level = battery[1] + data = level if data > 100: data = 100 @@ -1882,15 +1883,22 @@ if EventMesh.model == "D15" : audio_buf.index("R_READ_STEP_2")) EventMesh.publish("play_audio_file",[str_data,1])#获取播放音频文件('U:/static/audio.bin',1,1,str_data) return - - if data%10 == 0: - str_data = 'mp3files={}.mp3+{}.mp3+{}.mp3'.format(audio_buf.index("R_CUR_BATTERY_LEVEL"),audio_buf.index("R_READ_TIME_{}".format(data//10)),\ - audio_buf.index("R_READ_STEP_3")) - EventMesh.publish("play_audio_file",[str_data,1])#获取播放音频文件('U:/static/audio.bin',1,1,str_data) + if data > 10: + if data%10 == 0: + str_data = 'mp3files={}.mp3+{}.mp3+{}.mp3'.format(audio_buf.index("R_CUR_BATTERY_LEVEL"),audio_buf.index("R_READ_TIME_{}".format(data//10)),\ + audio_buf.index("R_READ_STEP_3")) + EventMesh.publish("play_audio_file",[str_data,1])#获取播放音频文件('U:/static/audio.bin',1,1,str_data) + else: + str_data = 'mp3files={}.mp3+{}.mp3+{}.mp3+{}.mp3'.format(audio_buf.index("R_CUR_BATTERY_LEVEL"),audio_buf.index("R_READ_TIME_{}".format(data//10)),\ + audio_buf.index("R_READ_STEP_3"),audio_buf.index("R_READ_TIME_{}".format(data%10))) + EventMesh.publish("play_audio_file",[str_data,1])#获取播放音频文件('U:/static/audio.bin',1,1,str_data) else: - str_data = 'mp3files={}.mp3+{}.mp3+{}.mp3+{}.mp3'.format(audio_buf.index("R_CUR_BATTERY_LEVEL"),audio_buf.index("R_READ_TIME_{}".format(data//10)),\ - audio_buf.index("R_READ_STEP_3"),audio_buf.index("R_READ_TIME_{}".format(data%10))) - EventMesh.publish("play_audio_file",[str_data,1])#获取播放音频文件('U:/static/audio.bin',1,1,str_data) + if data == 10: + str_data = 'mp3files={}.mp3+{}.mp3'.format(audio_buf.index("R_CUR_BATTERY_LEVEL"),audio_buf.index("R_READ_STEP_3")) + EventMesh.publish("play_audio_file",[str_data,1])#获取播放音频文件('U:/static/audio.bin',1,1,str_data) + else : + str_data = 'mp3files={}.mp3+{}.mp3'.format(audio_buf.index("R_CUR_BATTERY_LEVEL"),audio_buf.index("R_READ_TIME_{}".format(data))) + EventMesh.publish("play_audio_file",[str_data,1])#获取播放音频文件('U:/static/audio.bin',1,1,str_data) diff --git a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/mgr.py b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/mgr.py index 726f50a7..032281ce 100644 --- a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/mgr.py +++ b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/mgr.py @@ -44,6 +44,7 @@ from led import led_mode,open_led_green,close_led_green,open_led_red,close_led_r from queue import Queue if EventMesh.model == "D10": heartbeat_time = 7*60 #心跳时间 + gheartbeat_time = 5*60 #心跳时间 def get_autoblood_value():#血压值 data = RTC().datetime() @@ -910,7 +911,7 @@ if EventMesh.model == "D10": self.auto_temp_count = 0 - + self.test_time = 0 def post_processor_after_instantiation(self): EventMesh.debug_log("post_processor_after_instantiation:1") @@ -1115,9 +1116,14 @@ if EventMesh.model == "D10": # EventMesh.publish(constants.EVENT.START_LOCATION,constants.PROTOCOL.UD_SEND) #开始UD定位 """7分钟一次心跳""" - if math.fabs(time_tmp - self.KA_time) > heartbeat_time: #7分钟一次心跳 - self.KA_time = time_tmp - EventMesh.publish(constants.PROTOCOL.KA_SEND) + if EventMesh.platform == "gewu": + if math.fabs(time_tmp - self.KA_time) > gheartbeat_time: #7分钟一次心跳 + self.KA_time = time_tmp + EventMesh.publish(constants.PROTOCOL.KA_SEND) + else: + if math.fabs(time_tmp - self.KA_time) > heartbeat_time: #7分钟一次心跳 + self.KA_time = time_tmp + EventMesh.publish(constants.PROTOCOL.KA_SEND) """定时定位""" #EventMesh.publish("set_upload_data",3*60) @@ -1230,20 +1236,24 @@ if EventMesh.model == "D10": """电量小于0% 关机""" get_low_btn = EventMesh.publish("get_low_bat_btn")# battery = EventMesh.publish("screen_get_battery") - if battery[0] != '1': - if battery[1] == 0: - EventMesh.publish("open_power_on",2)# #未检测到sim卡15分钟后关机 - """"低电报警""" - if battery[1] <= 15 and self.low_power_AL==0: - self.low_power_AL = 1 - dev_state = EventMesh.publish("get_dev_state") + if battery != None: + power = int(battery[1]) + if battery[0] != '1': + if power == 0: + EventMesh.publish("open_power_on",2)# + """"低电报警""" + # print("low power!!!!!!!!!!! %d",self.low_power_AL) + if power <= 15 and self.low_power_AL==0: + self.low_power_AL = 1 + dev_state = EventMesh.publish("get_dev_state") + + tmp = 1 << 17 + dev_state = dev_state|tmp #第17位=1 + EventMesh.publish("set_dev_state",dev_state) + EventMesh.publish(constants.EVENT.START_LOCATION,[constants.PROTOCOL.AL_SEND,dev_state]) #开始AL定位 - tmp = 1 << 17 - dev_state = dev_state|tmp #第17位=1 - EventMesh.publish("set_dev_state",dev_state) - EventMesh.publish(constants.EVENT.START_LOCATION,[constants.PROTOCOL.AL_SEND,dev_state]) #开始AL定位 - if battery[1] >= 50: - self.low_power_AL = 0 + if power >= 50: + self.low_power_AL = 0 """未联网提示关机""" ble=EventMesh.publish(constants.EVENT.GET_CONNECT) @@ -1374,7 +1384,6 @@ if EventMesh.model == "D10": if self.pull_time == 0: self.pull_time = time_tmp - # if EventMesh.publish(constants.EVENT.GET_CONNECT) == 1:#已联网 并且不在充电 佩戴正常 不在通话就给测试心率 if EventMesh.publish(constants.EVENT.GET_CONNECT) == 1 and battery[0] != "1" and WEAR == 1 and call_state == 0: if time_tmp - self.pull_time >= 30: @@ -1604,7 +1613,7 @@ if EventMesh.model == "D10": hr_time = {} hr_time = EventMesh.publish("get_time_hr")#获取时间是否大于0 - + # print("hr_time{}".format(hr_time)) if hr_time[0] != None: self.mearsure_btn = int(hr_time[0]) self.mearsure_timer = int(hr_time[1]) @@ -2709,7 +2718,8 @@ if EventMesh.model == "D10": def get_imei(self, topic, msg): if not self.imei: self.imei = modem.getDevImei() - # self.imei = "860132060128634" #860132060128634 + + # self.imei = "866610001011658" #860132060128634 return self.imei def get_cid(self, topic, msg): @@ -3690,7 +3700,7 @@ if EventMesh.model == "D10": ujson.dump(self.read_histroy_hr_data,fd) pass else: - EventMesh.publish("set_storage_config",["old_hr",msg]) + pass @@ -3872,6 +3882,9 @@ if EventMesh.model == "D10": self.set_hr = 0 #0关闭 1手动 2 自动测量按照时间间隔测试心率 self.set_spo2 = 0 self.open_btn = 0 + if EventMesh.platform == "gewu": + self.set_time = 10*60 + self.open_btn = 1 self.set_bgautotime = 0 self.bgauto_btn = 0 read_data = EventMesh.publish("get_storage_config","measure_time") @@ -4185,6 +4198,9 @@ if EventMesh.model == "D10": class getUpLoadDataManager(Abstract):# def __init__(self): self.upload_time = 2*60*60 + if EventMesh.platform == "gewu": + self.upload_time = 10*60 + read_data = EventMesh.publish("get_storage_config","upload_time") if read_data != None: self.upload_time = read_data @@ -4198,7 +4214,10 @@ if EventMesh.model == "D10": def get_upload_data(self, event, msg): if self.upload_time == None: - self.upload_time = 2*60*60 + if EventMesh.platform == "gewu": + self.upload_time = 10*60 + else: + self.upload_time = 2*60*60 return self.upload_time class getplayAudiodStateManager(Abstract):#获取设置播放音频状态 @@ -4572,7 +4591,7 @@ if EventMesh.model == "D10": server_data = protocol.server_init() if new_ip != None: - if len(new_ip) != 0: + if len(str(new_ip)) != 0: IP = new_ip else: IP = server_data[0] @@ -4581,12 +4600,12 @@ if EventMesh.model == "D10": PORT = '' if new_com != None: - if len(new_com) != 0: - PORT = new_com + if len(str(new_com)) != 0: + PORT = str(new_com) else: - PORT = server_data[1] + PORT = str(server_data[1]) else: - PORT = server_data[1] + PORT = str(server_data[1]) UPLOAD = EventMesh.publish("get_upload_data") @@ -4598,7 +4617,12 @@ if EventMesh.model == "D10": bat = 100 Battery = str(level) +',' + str(bat) - ConnectTime = heartbeat_time//60 + ConnectTime = 0 + + if EventMesh.platform == "gewu": + ConnectTime = gheartbeat_time//60 + else: + ConnectTime = heartbeat_time//60 data1 = "Version:{}\nBuild:{}".format(versions,Build) data2 = "IMEI:{}\nIP:{}\nPORT:{}".format(IMEI,IP,PORT) diff --git a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/mgr_d15.py b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/mgr_d15.py index 5a76998f..221ec97d 100644 --- a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/mgr_d15.py +++ b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/mgr_d15.py @@ -919,7 +919,7 @@ if EventMesh.model == "D15": self.auto_temp_count = 0 - + self.low_power_AL = 0 def post_processor_after_instantiation(self): EventMesh.debug_log("post_processor_after_instantiation:1") @@ -1239,9 +1239,25 @@ if EventMesh.model == "D15": """电量小于0% 关机""" get_low_btn = EventMesh.publish("get_low_bat_btn")# battery = EventMesh.publish("screen_get_battery") - if battery[0] != '1': - if battery[1] == 0: - EventMesh.publish("open_power_on",2)# #未检测到sim卡15分钟后关机 + + if battery != None: + power = int(battery[1]) + if battery[0] != '1': + if power == 0: + EventMesh.publish("open_power_on",2)# + """"低电报警""" + # print("low power!!!!!!!!!!! %d",self.low_power_AL) + if power <= 15 and self.low_power_AL==0: + self.low_power_AL = 1 + dev_state = EventMesh.publish("get_dev_state") + + tmp = 1 << 17 + dev_state = dev_state|tmp #第17位=1 + EventMesh.publish("set_dev_state",dev_state) + EventMesh.publish(constants.EVENT.START_LOCATION,[constants.PROTOCOL.AL_SEND,dev_state]) #开始AL定位 + + if power >= 50: + self.low_power_AL = 0 """未联网提示关机""" ble=EventMesh.publish(constants.EVENT.GET_CONNECT) @@ -4611,14 +4627,14 @@ if EventMesh.model == "D15": else: IP = server_data[0] - PORT = '' + PORT = "" if new_com != None: if len(str(new_com)) != 0: - PORT = new_com + PORT = str(new_com) else: - PORT = server_data[1] + PORT = str(server_data[1]) else: - PORT = server_data[1] + PORT = str(server_data[1]) UPLOAD = EventMesh.publish("get_upload_data") diff --git a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/protocol.py b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/protocol.py index 83306642..b6907131 100644 --- a/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/protocol.py +++ b/2.sdk/project/D10/sdk/services/microPython/ports/quectel/core/protocol.py @@ -21,7 +21,10 @@ import urandom import _thread import usys import request - +import umqtt +import modem +SHA256 = uhashlib.sha256 +import SecureData def server_init(server_type = None): #服务器选择1,防走丢,2大锤,3三基同创,4童信,5云米,6荣为 8:ds未知 dey.hinwatch. com:9968 9:183.62.239.121:31869 10:183.62.239.121:33461 if server_type == None: @@ -127,18 +130,148 @@ def UnicodeHexStr_To_Utf8Str(str): odata = odata << 4 odata += tmp - ord('A') + 10 if(i%4==3): #每2字节获取一个int,拿到转换后的unicode int - #EventMesh.debug_log(odata.to_bytes(2, 'big')) + #print(odata.to_bytes(2, 'big')) #result.append(odata) if odata > 255: tmp = unicode_to_utf8(odata)#拿到转换后的utf8 int tmp2 = tmp.to_bytes(3, 'big') #转bytes else : tmp2 = odata.to_bytes(1, 'big') - #EventMesh.debug_log("tmp2:{}".format(tmp2)) + #print("tmp2:{}".format(tmp2)) result = result + tmp2 odata = 0 i+=1 return result.decode('utf-8') #返回utf8的str + +def gewu_init(): + productKey = "cu1shld45y4hjr1L" + return productKey +mqtt_state = 0 +def mqttsub_cb(topic, msg): + global mqtt_state + print("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) + jsload_data = ujson.loads(msg.decode()) + print("jsload_data-{} type:{}".format(jsload_data,type(msg.decode()))) + # jsload_data = {'data':'111','protocolType':'', 'host':'device.miwitracker.com', 'secretKey': 'bZld0ALsZTt15tKEZhOlLPgbsO75BLTP', 'port':8505, 'bid': '3G', 'extJsonStr': ''} + # ujson.loads(c) + # $sys/cu1shld45y4hjr1L/866610001011658/ext/regist + #data = {"messageId":"25","params":{"deviceSecret":"C1D75A63C0338978438E9197372FC698""}} + if "params" in jsload_data: + params_str = jsload_data["params"] + if "deviceSecret" in params_str: + str_tmp = params_str["deviceSecret"] + print(str_tmp) + EventMesh.publish("set_deviceSecret",str_tmp) + mqtt_state = 1 +def mqtterr_cb(error): + ''' + 接收umqtt线程内异常的回调函数 + ''' + print("error!!!!!!!!!!!".format(error)) + +def HMAC(k, m): + SHA1_BLOCK_SIZE = 64 + KEY_BLOCK = k + (b'\0' * (SHA1_BLOCK_SIZE - len(k))) + KEY_INNER = bytes((x ^ 0x36) for x in KEY_BLOCK) + KEY_OUTER = bytes((x ^ 0x5C) for x in KEY_BLOCK) + inner_message = KEY_INNER + m + outer_message = KEY_OUTER + SHA256(inner_message).digest() + return SHA256(outer_message) + + +def get_hmac_sha256(k, m): + data = HMAC(k, m).digest() + # print("HMAC(k, m).digest():", data) + # print("HMAC(k, m).digest():", ubinascii.hexlify(data)) + hex_data = ubinascii.hexlify(data) + hex_data = hex_data.decode('ascii') + return hex_data + +def mqtt_client_pro_init():#一型一密 + client = 0 + + # 创建一个mqtt实例 +# + # {"productKey":"cu1r1rjjrjdhz0lx","deviceKey":"DD86000000001","deviceSecret":"93FEEC6D16D30E2B90FE0DBC2FFCDB14"} 设备基本信息 + # hmac_sha256(deviceIddeviceKeyproductKey,deviceSecret) mqttclientId + deviceId = ""#"bOOSGN5FlXEjt15" + deviceKey = ''#"bOOSGN5FlXEjt15" + imei = EventMesh.publish(constants.EVENT.GET_IMEI) + deviceId = str(imei) + deviceKey = str(imei) + productKey = gewu_init() + + EventMesh.publish("set_product_key",productKey) + data = "{}{}{}".format(deviceId,deviceKey,productKey)#需要用户定义产品是提供数据 + # data = b"The data to encrypt" + # 密钥 + productSecret = b"765fc66242616852209d1c57e51b0744" #765fc66242616852209d1c57e51b0744 ,productSecret + + # {"productKey":"cu1shld45y4hjr1L","deviceKey":"bOOSGN5FlXEjt15","deviceSecret":"9234577490038E0949B800C243BF4321"} + checkpassword = get_hmac_sha256(productSecret,data) + # print(checkpassword) + # {deviceId}|{productKey}|{signMethod}|{authType}|{operator};连接id格式 + + Client_id = "{}|{}|0|1|0".format(deviceId,productKey) # + # print(Client_id) + server = "dmp-mqtt.cuiot.cn" + port = 1883 + # {deviceKey}|{productKey} mqttUsername + userName = "{}|{}".format(deviceKey,productKey) + userpassword = checkpassword + # print(userName) + # print(userpassword) + # client = umqtt.MQTTClient("866610001011658|cu1shld45y4hjr1L|0|1|0","dmp-mqtt.cuiot.cn", 1883, "866610001011658|cu1shld45y4hjr1L","675f6fbfb15a729bbc280273632ce3a96f8b38d4736fbaf888fe8a48fd7aee09") + # client = umqtt.MQTTClient("lxRXQayZ4poQz8G|cujg06l29iav591b|0|0|0","dmp-mqtt.cuiot.cn", 1883, "lxRXQayZ4poQz8G|cujg06l29iav591b","1f8c69d29afca0505d967066b39d84a5eb1e54302b87e337b405f99d029a9242") + client = umqtt.MQTTClient(Client_id,server, port, userName,"{}".format(userpassword),reconn=False) + # client = MqttClient(Client_id, server, port, userName,"{}".format(userpassword)) + # 设置消息回调 + client.set_callback(mqttsub_cb) + # 设置异常回调 + client.error_register_cb(mqtterr_cb) + return client + +def mqtt_client_dev_init():#一机一密 + client = 0 + + # 创建一个mqtt实例 +# + # {"productKey":"cu1r1rjjrjdhz0lx","deviceKey":"DD86000000001","deviceSecret":"93FEEC6D16D30E2B90FE0DBC2FFCDB14"} 设备基本信息 + # hmac_sha256(deviceIddeviceKeyproductKey,deviceSecret) mqttclientId + deviceId = '' #"bOOSGN5FlXEjt15" + deviceKey = ''#"bOOSGN5FlXEjt15" + imei = EventMesh.publish(constants.EVENT.GET_IMEI) + deviceId = str(imei) + deviceKey = str(imei) + productKey = gewu_init() + data = "{}{}{}".format(deviceId,deviceKey,productKey)#需要用户定义产品是提供数据 + # data = b"The data to encrypt" + # 密钥 + deviceSecret_tmp = EventMesh.publish("get_deviceSecret") + subscribe_msg = deviceSecret_tmp.encode('ascii') + deviceSecret = subscribe_msg #765fc66242616852209d1c57e51b0744 ,productSecret + print(deviceSecret) + + checkpassword = get_hmac_sha256(deviceSecret,data) + print(checkpassword) + # {deviceId}|{productKey}|{signMethod}|{authType}|{operator};连接id格式 + Client_id = "{}|{}|0|0|0".format(deviceId,productKey) # + server = "dmp-mqtt.cuiot.cn" + port = 1883 + # {deviceKey}|{productKey} mqttUsername + userName = "{}|{}".format(deviceKey,productKey) + userpassword = checkpassword + + client = umqtt.MQTTClient(Client_id,server, port, userName,"{}".format(userpassword),reconn=False) + # client = MqttClient(Client_id, server, port, userName,"{}".format(userpassword)) + # 设置消息回调 + client.set_callback(mqttsub_cb) + # 设置异常回调 + client.error_register_cb(mqtterr_cb) + return client + + + class SockManager(Abstract): def __init__(self): self.sock = None @@ -148,6 +281,7 @@ class SockManager(Abstract): self.monitor_timer = osTimer() self.publish_timer = osTimer() self.reconnect_timer = osTimer() + self.mqtt_recv_timer = osTimer() self.reconnect_time = 1000 self.reconnect_flag = 0 self.connect_tmp = 0 @@ -157,6 +291,14 @@ class SockManager(Abstract): # self.server_port = server_data[1] self.server_addr = "" self.server_port = "" + self.device_id = "" + self.device_key = "" + self.product_key = gewu_init() + self.deviceSecret = "" + self.client = 0 + self.client_dev = 0 + self.client_state = 0 + self.mqtt_client_count = 0 ip_infor = {} ip_infor = EventMesh.publish("get_new_ip_com") EventMesh.debug_log("ip_infor1:{} \n\n\n".format(ip_infor)) @@ -178,8 +320,34 @@ class SockManager(Abstract): _thread.stack_size((9+2)*1024) _thread.start_new_thread(self.socket_send_queue_thread, ()) _thread.stack_size(8*1024) + EventMesh.subscribe("set_device_id",self.set_device_id) + EventMesh.subscribe("set_device_key",self.set_device_key) + EventMesh.subscribe("set_product_key",self.set_product_key) + + EventMesh.subscribe("get_device_id",self.get_device_id) + EventMesh.subscribe("get_device_key",self.get_device_key) + EventMesh.subscribe("get_product_key",self.get_product_key) + + EventMesh.subscribe("set_deviceSecret",self.set_deviceSecret) + + EventMesh.subscribe("get_deviceSecret",self.get_deviceSecret) + if EventMesh.platform == "gewu": + str = "deviceSecret:" + buf = bytearray(32+len(str)) + length = SecureData.Read(2, buf, 32+len(str)) + deviceSecret = buf.decode() + print(type(deviceSecret)) + if deviceSecret != "": + if "deviceSecret" in deviceSecret: + self.deviceSecret = deviceSecret.split(":")[1] + else: + self.deviceSecret = " " + if EventMesh.platform == "gewu": + self.client = mqtt_client_pro_init() def post_processor_after_instantiation(self): + EventMesh.subscribe("get_mqtt_pro_connect_state",self.get_mqtt_pro_connect_state) + EventMesh.subscribe("get_mqtt_dev_connect_state",self.get_mqtt_dev_connect_state) EventMesh.subscribe(constants.EVENT.CHANNEL_SOCKET_SEND, self.send) self.monitor_timer.start(7 * 60 * 1000, 1, self.check) @@ -191,7 +359,35 @@ class SockManager(Abstract): _thread.start_new_thread(self.recv, ()) _thread.stack_size(8*1024) + def set_device_id(self,event,msg): + self.device_id = str(msg) + + def get_device_id(self,event,msg): + + return self.device_id + def set_device_key(self,event,msg): + self.device_key = str(msg) + return + def get_device_key(self,event,msg): + return self.device_key + + def set_product_key(self,event,msg): + self.product_key = str(msg) + + def get_product_key(self,event,msg): + + return self.product_key + + def set_deviceSecret(self,event,msg): + if EventMesh.platform == "gewu": + self.deviceSecret = str(msg) + deviceSecret_tmp = "deviceSecret:{}".format(msg) + SecureData.Store(2, deviceSecret_tmp, len(deviceSecret_tmp)) + + def get_deviceSecret(self,event,msg): + return self.deviceSecret + def connect(self): EventMesh.debug_log("connect1{}:{}".format(self.server_addr, self.server_port)) if EventMesh.publish("get_sim_Status") != 1: #没sim @@ -204,6 +400,9 @@ class SockManager(Abstract): self.sock.connect((self.server_addr, self.server_port)) self.publish_timer.start(2000, 1, self.publish_timer_cb) + if EventMesh.platform == "gewu": + self.mqtt_client_count = 0 + self.mqtt_recv_timer.start(5000, 1, self.mqtt_recv_timer_cb) utime.sleep_ms(500) EventMesh.publish(constants.PROTOCOL.LK_SEND) @@ -218,11 +417,11 @@ class SockManager(Abstract): EventMesh.debug_log("connect2{}:{}".format(self.server_addr, self.server_port)) self.reconnect_flag = 0 def publish_timer_cb(self, *args): - self.authen_set() def authen_set(self): sever_state = EventMesh.publish("get_server_state")#获取修改服务器状态 + # print("sever_state{}".format(sever_state)) if sever_state != None: if sever_state == 0: imei = EventMesh.publish(constants.EVENT.GET_IMEI) @@ -310,15 +509,300 @@ class SockManager(Abstract): self.reconnect()#重连设备 self.publish_timer.stop() EventMesh.publish("set_server_state",1)#获取修改服务器状态 + else: + self.publish_timer.stop() + + + + def mqtt_recv_timer_cb(self, *args): + self.mqtt_clien_cb() - + + + def mqtt_clien_cb(self): + if EventMesh.platform != "gewu": + return + # 需要加密的数据 + get_deviceSecret = EventMesh.publish("get_deviceSecret") + if get_deviceSecret != None: + if self.mqtt_client_count == 0: + self.mqtt_client_count = 1 + self.mqtt_recv_timer.stop() + get_deviceSecret = EventMesh.publish("get_deviceSecret")#获取设备的秘钥 只获取一次 + print("get_deviceSecret{}".format(get_deviceSecret)) + if get_deviceSecret == '':#如果为空就获取一次 + # print("self.client:{}".format(self.client)) + mqtt_connect = -1 + try: + mqtt_connect = self.client.connect() + except Exception as e: + print(e) + mqtt_connect = -1 + print("mqtt_connect:{}".format(mqtt_connect)) + if mqtt_connect == 0 : + # 订阅主题 + get_device_id = EventMesh.publish(constants.EVENT.GET_IMEI) + get_deviceKey = EventMesh.publish(constants.EVENT.GET_IMEI) + get_productKey = gewu_init() + #$sys/{productKey}/{deviceKey}/ext/regist + client_msg = "$sys/{}/{}/ext/regist".format(get_productKey,get_deviceKey) + # client_msg = "$sys/cu1shld45y4hjr1L/866610001011658/ext/regist" + subscribe_msg = client_msg.encode('ascii') + print(subscribe_msg) + + self.client.subscribe(subscribe_msg,0)#订阅消息主题 + + + self.client.wait_msg() # 阻塞函数,监听消息 + utime.sleep(5) + get_deviceSecret = EventMesh.publish("get_deviceSecret") + if get_deviceSecret != '': + self.client.disconnect() + self.client_dev = mqtt_client_dev_init() + print(self.client_dev) + # mqtt_connect = self.client_dev.connect() + try: + mqtt_connect = self.client_dev.connect() + except Exception as e: + print(e) + mqtt_connect = -1 + if mqtt_connect == 0: + # $sys/cu1shld45y4hjr1L/bOOSGN5FlXEjt15/property/batch_reply + msg_reply = "$sys/{}/{}/property/batch_reply".format(get_productKey,get_deviceKey) + sub_msg = msg_reply.encode('ascii') + self.client_dev.subscribe(sub_msg,0)#订阅消息主题 + print("Connected to dmp-mqtt.cuiot.cn, subscribed to /public/TEST/quecpython topic") + # 发布消息 + # UnicodeHexStr_To_Utf8Str(str_data) + date_tmp = utime.localtime() + time_tmp = utime.mktime(date_tmp)#需要转换成毫秒级别 + updataTime = "{}".format(time_tmp*1000) + # imei_tmp= modem.getDevImei() + imei_tmp = EventMesh.publish(constants.EVENT.GET_IMEI) + bat_tmp = EventMesh.publish("screen_get_battery") + imei = "{}".format(imei_tmp) + power = 0 + power = int(bat_tmp[1]) + hr = 0 + hr = EventMesh.publish("get_old_hr_data") + if hr == None: + hr = 0 + deviceTime = "{}".format(time_tmp) + manufactury = "fengda" + DeviceState = "online" + + data_info = { + "messageId":"0", + "params": { + "data": [ + { + "key":"deviceOffOn", + "value": { + "deviceStatus":"Poweron", + "updateTime":updataTime, + "Imei":imei + } + + }, + { + "key":"HeartRate", + "value":{ + "heartRate":hr, + "updateTme":updataTime, + "Imei":imei + } + }, + { + "key":"powerSavingMode", + "value":0 + }, + { + "key":"IMEI", + "value":imei + }, + { + "key":"DEVICE_TIME", + "value":deviceTime + }, + { + "key":"MANUFACTURER", + "value":manufactury + }, + { + "key":"REMAINING_POWER", + "value":power + }, + { + "key":"DeviceState", + "value":DeviceState + } + ] + } + } + + data_json = ujson.dumps(data_info) + # print("data_json:{}",data_json) + # $sys/cu1shld45y4hjr1L/{deviceKey}/property/batch + msg_pub = "$sys/{}/{}/property/batch".format(get_productKey,get_deviceKey) + pub_msg = msg_pub.encode('ascii') + self.client_dev.publish(pub_msg,data_json,0)#publis主题内容 + + print("Publish topic: /public/TEST/quecpython758, msg: my name is Quecpython") + pass + + else: + mqtt_dev_connect = -1 + mqtt_ret_connect = -1 + mqtt_pro_connect = -1 + if self.client_dev == 0: + self.client_dev = mqtt_client_dev_init() + try: + mqtt_dev_connect = self.client_dev.connect() + except Exception as e: + print("erro!{}".format(e)) + mqtt_dev_connect = -2 + # Server Actively FIN Disconnected.Need Check Connection parameters + err_dis = "FIN Disconnected" in str(e) + err_parm1 = "107" in str(e) + err_parm2 = "4" in str(e) + # print("err_parm1!{} {} {} {}".format(err_parm1,err_parm2,err_info,err_dis)) + # Connect Error='4' MQTT Connect error= + if err_dis == True or err_parm1 == True or err_parm2 == True: + mqtt_dev_connect = -1 + + + if mqtt_dev_connect != 0:#连接参数错误可能是deviceScrete出错重新获取 + + try: + mqtt_ret_connect = self.client.connect()#重新获取deviceScrete + except Exception as e: + print(e) + mqtt_ret_connect = -1 + # mqtt_connect = self.client.connect() + print("mqtt_ret_connect:{}".format(mqtt_ret_connect)) + if mqtt_ret_connect == 0: + # 订阅主题 + get_device_id = EventMesh.publish(constants.EVENT.GET_IMEI) + get_deviceKey = EventMesh.publish(constants.EVENT.GET_IMEI) + get_productKey = gewu_init() + #$sys/{productKey}/{deviceKey}/ext/regist + client_msg = "$sys/{}/{}/ext/regist".format(get_productKey,get_deviceKey) + # client_msg = "$sys/cu1shld45y4hjr1L/866610001011658/ext/regist" + subscribe_msg = client_msg.encode('ascii') + print(subscribe_msg) + + self.client.subscribe(subscribe_msg,0)#订阅消息主题 + + self.client.wait_msg() # 阻塞函数,监听消息 + utime.sleep(5) + + self.client.disconnect() + self.client_dev = mqtt_client_dev_init() + # print(self.client_dev) + try: + mqtt_pro_connect = self.client_dev.connect() + except Exception as e: + print(e) + mqtt_pro_connect = -1 + # print("no deviceScret!!!!!!!{}".format(self.client_dev)) + # 设备秘钥不为空 重连获取设备失败不连接 第一次连接失败不连接不发送数据 + if EventMesh.publish("get_deviceSecret") != "" and (mqtt_pro_connect == 0 or mqtt_dev_connect == 0): + get_device_id = EventMesh.publish(constants.EVENT.GET_IMEI) + get_deviceKey = EventMesh.publish(constants.EVENT.GET_IMEI) + get_productKey = gewu_init() + # $sys/cu1shld45y4hjr1L/bOOSGN5FlXEjt15/property/batch_reply + msg_reply = "$sys/{}/{}/property/batch_reply".format(get_productKey,get_deviceKey) + sub_msg = msg_reply.encode('ascii') + # print(" deviceScret!!!!!!!{} msg_reply:{} sub_msg:{}".format(self.client_dev,msg_reply,sub_msg)) + self.client_dev.subscribe(sub_msg,0)#订阅消息主题 + print("Connected to dmp-mqtt.cuiot.cn, subscribed to /public/TEST/quecpython topic") + # 发布消息 + # UnicodeHexStr_To_Utf8Str(str_data) + date_tmp = utime.localtime() + time_tmp = utime.mktime(date_tmp)#需要转换成毫秒级别 + updataTime = "{}".format(time_tmp*1000) + imei_tmp = EventMesh.publish(constants.EVENT.GET_IMEI) + imei = "{}".format(imei_tmp) + bat_tmp = EventMesh.publish("screen_get_battery") + power = 0 + power = int(bat_tmp[1]) + hr = 0 + hr = EventMesh.publish("get_old_hr_data") + if hr == None: + hr = 0 + deviceTime = "{}".format(time_tmp) + manufactury = "fengda" + DeviceState = "online" + + data_info = { + "messageId":"0", + "params": { + "data": [ + { + "key":"deviceOffOn", + "value": { + "deviceStatus":"Poweron", + "updateTime":updataTime, + "Imei":imei + } + + }, + { + "key":"HeartRate", + "value":{ + "heartRate":hr, + "updateTme":updataTime, + "Imei":imei + } + }, + { + "key":"powerSavingMode", + "value":0 + }, + { + "key":"IMEI", + "value":imei + }, + { + "key":"DEVICE_TIME", + "value":deviceTime + }, + { + "key":"MANUFACTURER", + "value":manufactury + }, + { + "key":"REMAINING_POWER", + "value":power + }, + { + "key":"DeviceState", + "value":DeviceState + } + ] + } + } + + data_json = ujson.dumps(data_info) + # print("data_json:{}",data_json) + # $sys/cu1shld45y4hjr1L/{deviceKey}/property/batch + msg_pub = "$sys/{}/{}/property/batch".format(get_productKey,get_deviceKey) + pub_msg = msg_pub.encode('ascii') + self.client_dev.publish(pub_msg,data_json,0)#publis主题内容 + + print("Publish topic: /public/TEST/quecpython758, msg: my name is Quecpython") + + def get_mqtt_pro_connect_state(self,event,msg): + return self.client + def get_mqtt_dev_connect_state(self,event,msg): + return self.client_dev + def check(self, *args): if (not self.run_flag) or (self.connect_tmp == 0) : #7分钟无数据读取,则认为是掉线了 EventMesh.debug_log("tcp reconnect!!!!!!!!!!!!!!!!!!") EventMesh.publish(constants.EVENT.SET_CONNECT,0) #标记断网 self.reconnect() self.connect_tmp = 0 - def reconnect(self): if(self.reconnect_flag == 1): return @@ -733,13 +1217,70 @@ class UD_ProtoCol(ProtoCol): MD5_SIGN = self.pack_MD5_head(MD5_head_data) data = "[%s%s]"%(str(MD5_SIGN),send_data) - #EventMesh.txt_log("{}".format(data)) + # EventMesh.debug_log("{}".format(data)) # wt_data = EventMesh.publish("get_weather_data") # # #如果没有天气数据,则获取天气数据 # if wt_data != None or wt_data[0] == None : # - EventMesh.publish(constants.EVENT.CHANNEL_SOCKET_SEND, data) + if EventMesh.platform == "gewu": + if(msg != ""): + client = EventMesh.publish("get_mqtt_dev_connect_state") + if client != 0: + mqtt_connect = -1 + try: + mqtt_connect = client.connect() + except Exception as e: + print(e) + mqtt_connect = -1 + print("mqtt_connect:{}".format(mqtt_connect)) + if mqtt_connect == 0: + # 订阅主题 + get_device_id = EventMesh.publish(constants.EVENT.GET_IMEI) + get_deviceKey = EventMesh.publish(constants.EVENT.GET_IMEI) + get_productKey = gewu_init() + #$sys/{productKey}/{deviceKey}/ext/regist + event_msg = "$sys/{}/{}/event/pub_reply".format(get_productKey,get_deviceKey) + # client_msg = "$sys/cu1shld45y4hjr1L/866610001011658/ext/regist" + subscribe_msg = event_msg.encode('ascii') + + client.subscribe(subscribe_msg,0)#订阅事件消息消息主题 + print("Connected to dmp-mqtt.cuiot.cn, subscribed to /public/TEST/quecpython topic") + msg_tmp = msg.decode('ascii') + msg_tmp = msg_tmp.split(',') + longitude = float(msg_tmp[3]) + latitude = float(msg_tmp[5]) + date_tmp = utime.localtime() + time_tmp = utime.mktime(date_tmp)#需要转换成毫秒级别 + updataTime = "{}".format(time_tmp*1000) + data_info = { + "messageId":"0", + "params": { + "key":"location", + "info": [ + { + "key":"longitude", + "value":longitude + }, + { + "key":"latitude", + "value":latitude + }, + { + "key":"UpdateTime", + "value":updataTime + } + ] + } + } + data_json = ujson.dumps(data_info) + event_pub_msg = "$sys/{}/{}/event/pub".format(get_productKey,get_deviceKey) + pub_msg = event_pub_msg.encode('ascii') + client.publish(pub_msg,data_json,0)#publis主题内容 + + print("Publish topic: /public/TEST/quecpython758, msg: my name is Quecpython") + + def recv(self, event, msg): pass @@ -789,7 +1330,7 @@ class AL_ProtoCol(ProtoCol): MD5_SIGN = self.pack_MD5_head(MD5_head_data) data = "[%s%s]"%(str(MD5_SIGN),send_data) - #EventMesh.debug_log("AL_ProtoCol:send:%s"%(data)) + # EventMesh.debug_log("AL_ProtoCol:send:{}".format(data)) # 通过socket发送到服务器端 EventMesh.publish(constants.EVENT.CHANNEL_SOCKET_SEND, data) self.repetition_queue.put(data)#发送入队 @@ -803,7 +1344,8 @@ class AL_ProtoCol(ProtoCol): """ #EventMesh.publish(constants.PROTOCOL.CR_SEND) #EventMesh.publish(constants.EVENT.START_LOCATION,constants.PROTOCOL.UD_SEND) #开始ud定位 - EventMesh.debug_log("报警数据上报:recv:%s"%(msg)) + # print("报警数据上报:recv:%s"%(msg)) + EventMesh.debug_log("报警数据上报:recv:{}".format(msg)) # if self.repetition_queue.empty() == False: self.repetition_queue.get()#出队 @@ -948,7 +1490,6 @@ class WT_ProtoCol(ProtoCol): EventMesh.debug_log("WT_ProtoCol:send:%s"%(data)) # 通过socket发送到服务器端 EventMesh.publish(constants.EVENT.CHANNEL_SOCKET_SEND, data) - def recv(self, event, msg): """