def security_mode_c(self,security_mode,password=""): """ :param security_mode_num: 0:"home",1:"out",2:"sleep",3:"disarm" :param password: :return: """ # security_mode={ # 0:"home", # 1:"out", # 2:"sleep", # 3:"disarm" # } cmd={ "security_mode":security_mode, "password":password, "msg_type":"security_mode_change", "command":"modify", "from_role":"phone", "from_account":user.get_info_dict("USERNAME") } if user.get_info_dict("Net_flag")==1: sendmsg=self.__sendmsgformat(cmd) # print(sendmsg) res_msg=self._request("post",msg=sendmsg) # print(res_msg) elif user.get_info_dict("Net_flag")==0: self.send_all(cmd,flag="dynamic")
def __send_msg(self,msg_type,extend_params=None): if user.get_info_dict("Net_flag")==1: cmd={ "msg_type":msg_type, "command":"query", "from_role":"phone", "from_account":user.get_info_dict("USERNAME") } if extend_params: cmd.update(extend_params) sendmsg=self.__sendmsgformat(cmd) # print(sendmsg) res_msg=self._request("post",msg=sendmsg) # print(res_msg) elif user.get_info_dict("Net_flag")==0: cmd={ "msg_type":msg_type, "command":"query", "from_role":"phone", #用"phone"or"shared_company"? OK "from_account":user.get_info_dict("USERNAME") } if extend_params: cmd.update(extend_params) self.send_all(cmd,flag="dynamic")
def login(self): global login_flag global login_lock login_success_flag = 0 dict_msg = { "msg_type": "gateway_manager", "from_role": "shared_company", "command": "login", "from_account": user.get_info_dict("USERNAME"), "app_id": APP_ID } if user.get_info_dict("SERVER_PORT") == 9102: dict_msg = { "msg_type": "gateway_manager", "from_role": "shared_company", "command": "login", "from_account": user.get_info_dict("USERNAME"), "app_id": APP_ID, "password": "" } self.send_all(dict_msg, flag="private") time.sleep(2) if key_lock.acquire(): if dynamic_key and login_flag: # print("login success") login_success_flag = 1 key_lock.release() if login_lock.acquire(): login_flag = True login_lock.release() return login_success_flag
def __send_msg(self,dev_class_type,room_name,dev_name,func_command,func_value={"value":0},extend_params=None): if user.get_info_dict("Net_flag")==1: cmd={ "device_name":dev_name, "room_name":room_name, "func_command":func_command, "dev_class_type":dev_class_type, "func_value":func_value, "msg_type":"device_control", "command":"control", "from_role":"phone", "from_account":user.get_info_dict("USERNAME") } if extend_params: cmd.update(extend_params) sendmsg=self.__sendmsgformat(cmd) # print(sendmsg) res_msg=self._request("post",msg=sendmsg) # print(res_msg) elif user.get_info_dict("Net_flag")==0: cmd={ "device_name":dev_name, "room_name":room_name, "func_command":func_command, "dev_class_type":dev_class_type, "func_value":func_value, "msg_type":"device_control", "command":"control", "from_role":"phone", "from_account":user.get_info_dict("USERNAME") } if extend_params: cmd.update(extend_params) self.send_all(cmd,flag="dynamic")
def get_dev_status(self): sendmsg={ "cmd":"get_dev_status", "offset":"0", "total":"1048576",#1024*1024=1048576 "pid":user.get_info_dict("PID"), "vid":user.get_info_dict("VID"), "to_username":user.get_info_dict("SIPADDR") } # print(sendmsg) res_msg=self._request("post",msg=sendmsg) if res_msg!="": self.OnDataCallback(res_msg)
def monitor_c(self,room_name,dev_name): cmd={ "device_name":dev_name, "room_name":room_name, "msg_type":"camera_monitor_manager", "command":"monitor", "from_role":"phone", "from_account":user.get_info_dict("USERNAME") } if user.get_info_dict("Net_flag")==1: sendmsg=self.__sendmsgformat(cmd) # print(sendmsg) self._request("post",msg=sendmsg) # print(res_msg) elif user.get_info_dict("Net_flag")==0: self.send_all(cmd,flag="dynamic")
def scene_c(self,control_name,password=""): cmd={ "control_name":control_name, "password":password, "msg_type":"combination_control_manager", "command":"start", "from_role":"phone", "from_account":user.get_info_dict("USERNAME") } if user.get_info_dict("Net_flag")==1: sendmsg=self.__sendmsgformat(cmd) # print(sendmsg) res_msg=self._request("post",msg=sendmsg) # print(res_msg) elif user.get_info_dict("Net_flag")==0: self.send_all(cmd,flag="dynamic")
def __sendmsgformat(self,msg=None): sendmsg={ "cmd":"send_msg", "to_username":user.get_info_dict("SIPADDR"), "msg":json.dumps(msg), "subject":"control" } return sendmsg
def logout(self): #退出登录,关闭有关线程 # print("come in logout") """ Net_flag=0 #走内网 Net_flag=1 #走公网 默认 Net_flag=1 """ if self.publicradioButton.isChecked() or self.netradioButton.isChecked(): if user.get_info_dict("Net_flag")==1: #走公网 msg=LoginManage().loginout() # print(msg) if msg!="": dict_msg=dict(eval(msg)) if dict_msg.get("result",None)=="success": # print("come in stop thread") #停止公网有关线程 if self.get_thread_p: # print("stop get_thread_p thread") self.get_thread_p.stop() if self.key_thread_p: # print("stop key_thread_p thread") self.key_thread_p.stop() QtGui.QMessageBox.about(self,"Info",_fromUtf8(str(msg))) self.sipaddrcomboBox.clear() self.combstextBrowser.clear() self.devlisttextBrowser.clear() else: # print("check in the network") msg="check in the network" QtGui.QMessageBox.about(self,"Info",_fromUtf8(str(msg))) elif user.get_info_dict("Net_flag")==0: #走局域网 #停止局域网有关线程 if self.getRecvall_thread_l: # print("stop getRecvall_thread_l thread") self.getRecvall_thread_l.stop() time.sleep(3) #等待线程接受完数据 QtGui.QMessageBox.about(self,"Info",_fromUtf8(str("logout success"))) self.combstextBrowser.clear() self.devlisttextBrowser.clear() else: QtGui.QMessageBox.about(self,"Info",_fromUtf8(str("not login"))) else: QtGui.QMessageBox.about(self,"Info","please choose login mode")
def search(self, PORT=9200, BufferSize=8192): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.settimeout(1) HOST = '<broadcast>' #PORT 9200:网关与其他设备;9100:室内机和魔镜 if user.get_info_dict("PID") == "0002" or user.get_info_dict( "PID") == "0008": PORT = 9100 elif user.get_info_dict("PID") == "0003": PORT = 9200 # print(PORT) ADDR = (HOST, PORT) #向9200端口的设备发送广播消息 sock.bind(('', 0)) msg = { "msg_type": "search", "from_role": "phone", "from_account": user.get_info_dict("USERNAME"), "command": "query", "app_id": "1000000002" } msg = json.dumps(msg, separators=(',', ':')) jiami_msg = self._aes_encrypt(SEARCH_KEY, msg) # print(jiami_msg) sock.sendto(jiami_msg, ADDR) devices_list = [] while True: try: data, addr = sock.recvfrom(BufferSize) rec_data = self._aes_decrypt(SEARCH_KEY, data) # print("got data from",addr) # print(rec_data) rec_data = dict(eval(rec_data)) devices_list.append(rec_data) except Exception as e: # print(e.message) break sock.close() user.set_data_dict("search", devices_list)
def search_devices_by_type(devices_list): """ :param devices_list: [] :return:[] """ try: dev_list = [] if devices_list: for rec_dict in devices_list: if user.get_info_dict("PID") == "0002": if rec_dict.get("device_type", None) == "gateway": dev_list.append(rec_dict) elif user.get_info_dict("PID") == "0003": if rec_dict.get("device_type", None) == "coordin_zigbee": dev_list.append(rec_dict) elif user.get_info_dict("PID") == "0008": if rec_dict.get("device_type", None) == "mirror": dev_list.append(rec_dict) except Exception as e: logfile.logger.exception(e.message) finally: return dev_list
def request_post(self, msg): msg = json.dumps(msg) miwen = self._pub_encrypt(msg) res_msg = "" try: response = requests.post( url=user.get_info_dict("POST_SECUREPORT_URL"), data=miwen, timeout=1) if response.status_code == 200: res_msg = self._pub_decrypt(response.content) except requests.ConnectionError as e: #断开连接了 # print("PubPost connection error") # print("PubPost post===",e.message) # time.sleep(60) logfile.logger.exception(e.message) except Exception as e: # print("PubPost post===",e.message) logfile.logger.exception(e.message) finally: return res_msg
def send_all(self, dict_msg, flag="dynamic"): global dynamic_key global key_lock # python json不编码unicode并且除去无用的空格 # data = json.dumps(data,separators=(‘,’,’:’),ensure_ascii=False) msg = json.dumps(dict_msg, separators=(',', ':')) # print(msg) queue_msg = "send success===" + msg queue.logcat_Q.put(queue_msg) temp_msg = {} if flag == "private": encrypt_msg = self._aes_encrypt(private_key, msg) temp_msg = { "encrypt": "private", "msg": encrypt_msg, "app_id": APP_ID } else: if key_lock.acquire(): # print(dynamic_key) encrypt_msg = self._aes_encrypt(dynamic_key, msg) key_lock.release() if user.get_info_dict("SERVER_PORT") == 9101: temp_msg = { "msg": encrypt_msg, "encrypt": "dynamic", "app_id": APP_ID } elif user.get_info_dict("SERVER_PORT") == 9102: if getHttpToken: temp_msg = { "msg": encrypt_msg, "encrypt": "dynamic", "app_id": APP_ID, "token": getHttpToken } str_temp_msg = json.dumps(temp_msg, separators=(',', ':')) if user.get_info_dict("SERVER_PORT") == 9101: #室内机或魔镜内网 str_len = self.__fourhex(str_temp_msg) if user.get_info_dict("data_length") == 6: str_len = self.__sixhex(str_temp_msg) temp = "smartProtocol" + str_len send_msg = temp + str_temp_msg queue_msg = "send to business===" + send_msg queue.logcat_Q.put(queue_msg) # print(user.TCP_SOCKET) try: # print("tcp send") user.TCP_SOCKET.settimeout(1) #设置超时1s user.TCP_SOCKET.sendall(send_msg) except Exception as e: #超时 # print("send to server,is not connect") # print(e.message) logfile.logger.exception(e.message) elif user.get_info_dict("SERVER_PORT") == 9102: #zigbee内网 try: res = requests.post(url=user.get_info_dict("postHttp"), data=str_temp_msg, timeout=1) # print(res.status_code) # print("post from zigbee result===",res.content) queue_msg = "post from zigbee getReponseCode===" + str( res.status_code) # print(queue_msg) queue.logcat_Q.put(queue_msg) if res.status_code == 200: self.__msg_decrypt(res.content) except requests.ConnectionError as e: #断开连接了 # print("zigbee connection error") # print("zigbee post===",e.message) pass except Exception as e: # print(e.message) logfile.logger.exception(e.message)
def recv_all(self): #data length is packed into 4 or 6 bytes if user.get_info_dict("SERVER_PORT") == 9101: size_data = '' sock_data = '' recv_size = 8192 try: # print(user.TCP_SOCKET) user.TCP_SOCKET.settimeout(90) #设置超时90s sock_data = user.TCP_SOCKET.recv(recv_size) data_size_flag = 17 if user.get_info_dict("data_length") == 6: data_size_flag = 19 if len(sock_data) > data_size_flag: size_data = size_data + sock_data # print(size_data) # print(size_data[13:data_size_flag]) size = int(size_data[13:data_size_flag], 16) # print(size) if size > len(size_data): while True: sock_data = user.TCP_SOCKET.recv(recv_size) size_data = size_data + sock_data if size <= len(size_data): break if size_data != "": queue_msg = "from business===" + size_data queue.logcat_Q.put(queue_msg) self.__do_msg(size_data, data_size_flag) except Exception as e: # print("is not connect ") # print(e.message) # logfile.logger.exception(e.message) # user.TCP_SOCKET.close() # print("waiting 3s") time.sleep(3) while True: # print("reconnect again") # print("ip:",(user.get_info_dict("SERVER_IP"),user.get_info_dict("SERVER_PORT"))) connect_flag = user.create_tcp_socket( user.get_info_dict("SERVER_IP"), user.get_info_dict("SERVER_PORT")) #重新连接 if connect_flag: # print("reconnect success") # print("login again") self.login() break else: # print("reconnect failure") # print("waiting 60s") time.sleep(60) # print("re connect tcp server success") elif user.get_info_dict("SERVER_PORT") == 9102: if getHttpToken: params = {"tok": getHttpToken, "id": APP_ID} try: res = requests.get(url=user.get_info_dict("getHttp"), params=params, timeout=30) queue_msg = "get from zigbee getReponseCode===" + str( res.status_code) queue.logcat_Q.put(queue_msg) # print(queue_msg) if res.status_code == 200: # print("come in msg_decrypt") self.__msg_decrypt(res.content) except requests.ConnectionError as e: #断开连接,每1分钟请求一次 # print("zigbee connection error") # print("zigbee get===",e.message) # print("waiting 60s") time.sleep(60) except requests.ConnectTimeout as e: # print(time.time()) # print("get Timeout error") # print("RecvMsg get===",e.message) # logfile.logger.exception(e.message) pass except Exception as e: # print("RecvMsg get===",e.message) logfile.logger.exception(e.message)
def __init__(self): self.username = user.get_info_dict("USERNAME") self.password = user.get_info_dict("PASSWORD")
def _request(self, method, params=None, msg=None): #只有实例和子类使用 global AES_KEY global LOCK_KEY global TOKEN global LOCK_TOKEN res_msg = "" response = "" try: if method == "get": # print("come in get server") if LOCK_TOKEN.acquire(): param = {"token": TOKEN} LOCK_TOKEN.release() param.update(params) try: response = requests.get( url=user.get_info_dict("GET_URL"), params=param, timeout=65) #大多数请求外部服务器应该有一个超时, # 以防服务器没有响应及时。没有超时,那么您的代码就会挂几分钟或者更多 temp_response = "getReponseCode===" + str( response.status_code) queue.logcat_Q.put(temp_response) except requests.ConnectionError as e: #get服务断开连接,每60秒请求一次 # print(time.time()) # print("get connection error") # print("SendMsg get===",e.message) time.sleep(60) # print("60s sleep over") except requests.ConnectTimeout as e: # print(time.time()) # print("get Timeout error") # print("SendMsg get===",e.message) pass except Exception as e: # print("SendMsg get===",e.message) logfile.logger.exception(e.message) else: if LOCK_TOKEN.acquire(): sendmsg = {"token": TOKEN} LOCK_TOKEN.release() sendmsg.update(msg) # print(sendmsg) jsonmsg = json.dumps(sendmsg) # print(jsonmsg) temp_msg = "json.dumps()===" + jsonmsg queue.logcat_Q.put(temp_msg) if LOCK_KEY.acquire(): miwen = self._aes_encrypt(AES_KEY, jsonmsg) LOCK_KEY.release() try: response = requests.post( url=user.get_info_dict("POST_MSG_URL"), data=miwen, timeout=2) temp_response = "postResponseCode===" + str( response.status_code) queue.logcat_Q.put(temp_response) except Exception as e: # print("SendMsg post===",e.message) logfile.logger.exception(e.message) if response != "": if response.status_code == 200: if LOCK_KEY.acquire(): try: res_msg = self._aes_decrypt( AES_KEY, response.content) queue.result_Q.put(res_msg) temp_result = "postResult===" + res_msg queue.logcat_Q.put(temp_result) LOCK_KEY.release() except Exception as e: # print("aes_decrypt",e.message) temp_exception = "aes_decrypt().Exception===" + e.message queue.logcat_Q.put(temp_exception) LOCK_KEY.release() #避免死锁 exptime = GetAesKey().get_aes() # print("aes_decrypt fail:",exptime) temp_exptime = "AesKeyExpire===" + str(exptime) queue.logcat_Q.put(temp_exptime) except Exception as e: # print(e.message) temp_exception = "_request().Exception===" + e.message queue.logcat_Q.put(temp_exception) finally: return res_msg
def login(self): """ Net_flag=0 #走内网 Net_flag=1 #走公网 默认 Net_flag=1 """ if self.publicradioButton.isChecked() or self.netradioButton.isChecked(): if self.publicradioButton.isChecked(): # print("choose public network") # user.Net_flag=1 user.set_info_dict("Net_flag",1) elif self.netradioButton.isChecked(): # print("choose local network") # user.Net_flag=0 #走内网 user.set_info_dict("Net_flag",0) # print(user.Net_flag) # print(user.get_info_dict("Net_flag")) if user.get_info_dict("Net_flag")==1: #走公网 try: Server_IP=socket.gethostbyname(HostName) except Exception as e: Server_IP="139.159.224.188" # POST_SECUREPORT_URL="http://112.74.28.12/secureport" # POST_MSG_URL="http://112.74.28.12/postmsg" # GET_URL="http://112.74.28.12/getmsg" finally: user.set_info_dict("POST_SECUREPORT_URL","http://{0}/secureport".format(Server_IP)) user.set_info_dict("POST_MSG_URL","http://{0}/postmsg".format(Server_IP)) user.set_info_dict("GET_URL","http://{0}/getmsg".format(Server_IP)) user.set_info_dict("USERNAME",str(self.usernameEdit.text())) password=str(self.passwordEdit.text()) user.set_info_dict("PASSWORD",password) if len(password)>=6 and len(password)<=16: msg=LoginManage().login() if msg=="Login success": #停止内网线程 if self.getRecvall_thread_l: # print("stop getRecvall_thread_l thread") self.getRecvall_thread_l.stop() self.key_thread_p=getAesKeyThread() self.key_thread_p.start() #动态获取密钥线程 time.sleep(0.1) self.get_thread_p=getMsgThread() self.get_thread_p.start() #向服务器get请求线程 QueryMsg().get_all_friends() #向服务器get_friends self.connect(self.pidcomboBox,QtCore.SIGNAL('activated(int)'),self.update_addrs) self.update_addrs(0) #设置默认值 self.okButton.clicked.connect(self.okbutton_updataUI) self.logoutButton.clicked.connect(self.logout) QtGui.QMessageBox.about(self,"Info",_fromUtf8(msg)) else: QtGui.QMessageBox.about(self,"Info",_fromUtf8(str("password length is 6 to 16"))) else: #走内网 connect_flag=1 if user.get_info_dict("SERVER_PORT")==9101: #室内机通讯---tcp socket;网关通讯---http(get,post) connect_flag=user.create_tcp_socket(user.get_info_dict("SERVER_IP"),user.get_info_dict("SERVER_PORT")) # print(connect_flag) if connect_flag: self.getRecvall_thread_l=getRecvallThread() #接受服务器信息线程 self.getRecvall_thread_l.start() login_flag=SendRecvManage().login() if login_flag: QtGui.QMessageBox.about(self,"Info","login success") #停止公网有关线程 if self.get_thread_p: # print("stop get_thread_p thread") self.get_thread_p.stop() if self.key_thread_p: # print("stop key_thread_p thread") self.key_thread_p.stop() query_manage=QueryMsg() query_manage.combination_control_query() query_manage.room_query() query_manage.devices_query() time.sleep(2) self.devlisttextBrowser.clear() self.combstextBrowser.clear() self.display_combs() self.display_devices() else: queue.logout_Q.put("login_failure") self.getRecvall_thread_l.stop() self.getResult_thread.stop() else: QtGui.QMessageBox.about(self,"Info","tcp connect failure") else: QtGui.QMessageBox.about(self,"Info","please choose login mode")