def __heartbeat_cb(self, timer): self.__heartbeat_counter += 1 if self.__heartbeat_counter >= Settings.MQTT_KEEPALIVE: try: self.__client.publish( b'{}/ping'.format(Settings.MQTT_USERNAME), b'ping') self.__heartbeat_counter = 0 except OSError as ose: err_msg = str(ose) print("err time:", time()) print(err_msg) if err_msg in ("[Errno 104] ECONNRESET", "-1"): try: self.__client.disconnect() except OSError: pass finally: self.__client.connect() elif err_msg == "[Errno 113] EHOSTUNREACH": Utilities.hard_reset() gc.collect()
def __data_timer_cb(self, timer): value = self.get_temperature() print("current temperature: {} ℃".format(value)) try: self.__publish_data(value) except OSError as ose: err_msg = str(ose) if err_msg == "-1": pass elif err_msg == "[Errno 113] EHOSTUNREACH": Utilities.hard_reset() else: Utilities.log(self.__data_timer_cb, err_msg, self.__log_callback) except Exception as e: err_msg = str(e) Utilities.log(self.__data_timer_cb, err_msg, self.__log_callback)
def __msg_timer_cb(self): while self.__starting: try: self.__mqtt_client.wait_msg() except OSError as ose: err_msg = str(ose) if err_msg == "-1": pass elif err_msg == "[Errno 113] EHOSTUNREACH": Utilities.hard_reset() else: Utilities.log(self.__msg_timer_cb, err_msg, self.__log_callback) # raise OSError(err_msg) except Exception as e: err_msg = str(e) Utilities.log(self.__msg_timer_cb, err_msg, self.__log_callback) gc.collect()
def _OnWebSocketTextMsg(webSocket, msg): global Utilities, WifiHandler, Config import ujson print('WebSocket text message: %s' % msg) # webSocket.SendTextMessage('Received "%s"' % msg) try: params = ujson.loads(msg) if params["command"] == "identity": from utils.json_const import identity_result identity_result.update( hardware_version=Config.HARDWARE_VERSION, hardware_name=Config.HARDWARE_NAME, mac_address=WifiHandler.get_mac_address(), ip_address=WifiHandler.get_ip_address()) webSocket.SendTextMessage(ujson.dumps(identity_result)) elif params["command"] == "save_settings": from utils.json_const import save_settings_result_success, save_settings_result_failed from utils.settings_template import template settings = template.format(**params) # print(settings) with open("settings.py", "w") as file: length = file.write(settings) if length == len(settings): webSocket.SendTextMessage( ujson.dumps(save_settings_result_success)) else: webSocket.SendTextMessage( ujson.dumps(save_settings_result_failed)) elif params["command"] == "reboot_device": Utilities.hard_reset() elif params["command"] == "check_wifi": from utils.json_const import check_wifi_result result_code = WifiHandler.set_sta_mode(params["wifi_ssid"], params["wifi_password"], timeout_sec=60, for_test=True) check_wifi_result.update(result_code=result_code) webSocket.SendTextMessage(ujson.dumps(check_wifi_result)) if result_code == WifiHandler.STATION_CONNECTED: import urequests from utils.json_const import check_internet_result_success, check_internet_result_failed try: res = urequests.get(Config.INTERNET_TESTING_URL, timeout=10.0) if res: if res.text == "Success": webSocket.SendTextMessage( ujson.dumps(check_internet_result_success)) else: webSocket.SendTextMessage( ujson.dumps(check_internet_result_failed)) else: webSocket.SendTextMessage( ujson.dumps(check_internet_result_failed)) except Exception: webSocket.SendTextMessage( ujson.dumps(check_internet_result_failed)) elif params["command"] == "check_mqtt": from umqtt.simple import MQTTClient from utils.json_const import check_mqtt_result_success, check_mqtt_result_failed def sub_cb(topic, msg): pass mqtt_client = MQTTClient(params["client_id"], params["host"], int(params["port"]), params["username"], params["password"], int(params["keepalive"])) try: username = params["bigiot_username"] if bool( params["is_bigiot"]) else params["client_id"] mqtt_client.set_callback(sub_cb) print("check_mqtt_result:", mqtt_client.connect(True)) print( "test subscribe:", mqtt_client.subscribe( "{}/data".format(username).encode())) print( "test publish:", mqtt_client.publish( "{}/data".format(username).encode(), "world")) mqtt_client.disconnect() webSocket.SendTextMessage( ujson.dumps(check_mqtt_result_success)) except Exception as e: print(str(e)) # e == 5, authorized failed, means device number or device authorize wrong if str(e) == "5": check_mqtt_result_failed.update( error_code="5", error_msg= "Authorized failed, check Username and Password") # e == 128, sub failed, means client_id or topic auth(username/data) wrong elif str(e) == "128": check_mqtt_result_failed.update( error_code="128", error_msg= "Subscribe failed, check Bigiot Username and Client ID" ) else: check_mqtt_result_failed.update( error_code=str(e), error_msg="Unknown error: {}".format(str(e))) webSocket.SendTextMessage( ujson.dumps(check_mqtt_result_failed)) except ValueError: webSocket.SendTextMessage("Params Format Error") gc.collect()
def __sub_cb(self, topic, msg): if topic != self._topic: return print("msg: {}".format(msg)) try: json_obj = json.loads(str(msg, "utf-8")) command = json_obj['command'] general_result = { 'command': command + '_result', 'mac_address': json_obj['mac_address'], 'result': 'success' } if command == "wake_up_pc": for count in range(3): wake_on_lan(json_obj['mac_address']) general_result['title'] = json_obj['title'] general_result['mac_address'] = WifiHandler.get_mac_address() self._client.publish(topic, json.dumps(general_result)) elif command == 'device_remove': if json_obj['mac_address'] != WifiHandler.get_mac_address(): return general_result['title'] = json_obj['title'] self._client.publish(topic, json.dumps(general_result)) Utilities.del_settings_file() Utilities.hard_reset() elif command == 'sync_datetime': if json_obj['mac_address'] != WifiHandler.get_mac_address(): return datetime = json_obj['datetime'] RTC().datetime(( datetime['year'], datetime['month'], datetime['day'], datetime['weekday'], # 0~6 datetime['hour'], datetime['minute'], datetime['second'], datetime['millisecond'])) self._client.publish(topic, json.dumps(general_result)) print("datetime: %02d-%02d-%02d %02d:%02d:%02d" % ((localtime()[:-2]))) elif command == 'device_reboot': if json_obj['mac_address'] != WifiHandler.get_mac_address(): return Utilities.hard_reset() elif command == 'report_error_log': if json_obj['mac_address'] != WifiHandler.get_mac_address(): return general_result['logs'] = Utilities.read_logs() self._client.publish(topic, json.dumps(general_result)) except ValueError: pass except KeyError as ke: print("KeyError:", ke) gc.collect()
def __log_callback(self): Utilities.hard_reset()
def __wifi_timer_cb(self, timer): if not Utilities.is_wifi_connected(): Utilities.hard_reset()
def __button_press_cb(duration): print("button pressed over {} ms".format(duration)) Utilities.del_settings_file() Utilities.hard_reset()
click_cb=__button_click_cb, press_cb=__button_press_cb, timeout=Config.BUTTON_PRESS_TIMEOUT) WifiHandler.set_ap_status(False) sleep(1) if WifiHandler.STATION_CONNECTED == Utilities.connect_to_internet( ): led.stop_all() device = Selector.select(Config.HARDWARE_VERSION) device.setup() device.start() led.customize(1000, 0, 0) while forever_loop: sleep(0.5) else: # 600 秒后无法连接指定的 wifi 则重启 Utilities.hard_reset() except KeyboardInterrupt: forever_loop = False print("\nPRESS CTRL+D TO RESET DEVICE") if ap_server is not None: ap_server.stop() if led is not None: led.deinit() if button is not None: button.deinit()