def run(): """Main entry point to execute this program.""" sleep_enabled = _sleep_enabled() try: File.logger().info('%s - Awake: %s', clock.timestamp(), machine.wake_reason()) rainfall = False next_wake = config.RTC_ALARM battery_volts = _battery_voltage() if not sleep_enabled: watcher.disable() if wifi.connect(): _resetConnectCount() rain_data = weather.get_rain_data() rainfall = rain_data.rainfall_occurring() thingspeak.send(rain_data, battery_volts) if rainfall: File.logger().info('%s - System OFF', clock.timestamp()) _system_off() else: File.logger().info('%s - System ON', clock.timestamp()) _system_on() else: if _incrementConnectCount() > 5: # Give up trying to connect to WiFi _resetConnectCount() else: File.logger().info('%s - Set one minute sleep, attempts %d', clock.timestamp(), _getConnectCount()) next_wake = config.SLEEP_ONE_MINUTE except Exception as ex: # Catch exceptions so that device goes back to sleep HTTP calls # fail with exceptions. File.logger().exc(ex, '%s - Error', clock.timestamp()) finally: try: wifi.disconnect() except Exception as ex: File.logger().exc(ex, '%s - WIFI disconnect error', clock.timestamp()) if sleep_enabled: File.logger().info('%s - Sleeping...', clock.timestamp()) File.close_log() _sleep_until(next_wake) else: File.close_log()
def run(): """Main entry point to execute this program.""" # Set variable so that system defaults to ON avoiding garden never being # watered if execution repeatedly fails. try: _log_message('Running') rainfall = False sleep_enabled = _sleep_enabled() battery_volts = _battery_voltage() if wifi.connect(): _log_message('WIFI connected') rain_last_hour_mm, rain_today_mm = _read_weather() rain_forecast_today_mm, rain_forecast_tomorrow_mm = _read_forecast_with_retry() rainfall = (rain_today_mm > 3 or rain_last_hour_mm > 1 or rain_forecast_today_mm > 1) _send_to_thingspeak(rain_last_hour_mm, rain_today_mm, rain_forecast_today_mm, battery_volts, rainfall) if rainfall: _log_message('System OFF') _system_off() else: _log_message('System ON') _system_on() except Exception as ex: # Catch exceptions so that device goes back to sleep if WiFi connect or # HTTP calls fail with exceptions # pass _log_exception_to_file(ex) finally: try: wifi.disconnect() _log_message('WIFI disconnected') except Exception as ex: _log_exception_to_file(ex) if sleep_enabled: _log_message('Sleeping...') _sleep_until(config.RTC_ALARM)
def manual_mode(self): """Manually choose which AP to use.""" wifi.disconnect() wifi.scan() time.sleep(5) avail_ap = wifi.scan_results() logging.debug("List of available ap : %s" % avail_ap) logging.debug("List of faulty ap : %s" % self.faulty_ap) for ap in avail_ap: if ap not in self.faulty_ap: wifi.set_pref(ap) logging.info("New candidate found") logging.debug("Preffered bssid is now set to %s" % ap) logging.info("Associating...") wifi.reassociate() time.sleep(30) wifi_info = wifi.status() if wifi_info['wpa_state'] != "COMPLETED": logging.warning("Association failed!") logging.info("Looking for another candidate...") self.faulty_ap.append(ap) continue logging.info("Association successful") logging.info("bssid : %s" % ap) signal = wifi.signal_strength() logging.info("signal : -%s dBm" % signal) return logging.error( "Tested all available hotspots but none of them work :-(") self.faulty_ap = [] wifi.disconnect() self.sleep_mode()
def handleRequest(msg): """return: reply, closeConnect""" import wifi req = msg.get("request") param = msg.get("param") if req == "getEthernetInterface": return wifi.getEthernetInterface(), CLOSE elif req == "getWifiInterface": return wifi.getWifiInterface(), CLOSE elif req == "getScanResult": return wifi.getScanResult(), CLOSE elif req == "getEthernetConnection": return wifi.getEthernetConnection(), CLOSE elif req == "getWifiConnection": return wifi.getWifiConnection(), CLOSE elif req == "getInterfaceDetail": iface = param.get('iface') v = wifi.getInterfaceDetail(iface) return v, CLOSE elif req == "activateConnection": uuid = param.get("uuid") iface = param.get("iface") v = wifi.activateConnection(uuid, iface) return v, CLOSE elif req == "createWifiConnection": ssid = param.get("ssid") passwd = param.get("password") iface = param.get("iface") name = param.get("name") v = wifi.createWifiConnection(ssid, passwd, iface, name) return v, CLOSE elif req == "deleteConnection": uuid = param.get("uuid") v = wifi.deleteConnection(uuid) return v, CLOSE elif req == "disconnect": iface = param.get("iface") v = wifi.disconnect(iface) return v, CLOSE else: return {"error": "unknown request"}, True
def reconnect(pressed): if pressed: wifi.disconnect() display_connecting() wifi.connect() display_connected()
def disconnect_wifi(): if wifi.status(): wifi.disconnect() rgb.pixel((255, 0, 0), (31, 0)) # red for no wifi
tick = 0 try: connect_wifi() print('retrieving result') result = urequests.get(WEATHER_API_SERVER) disconnect_wifi() if result.status_code == 200: rgb.pixel((0, 255, 0), (31, 7)) # green for new data try: print(gc.mem_free()) weather = result.json() except: print('Error during json parse') print(result.text()) rgb.pixel((255, 0, 0), (31, 7)) # red for error else: print('Status: ' + result.status_code) rgb.pixel((255, 0, 0), (31, 7)) # red for error rgb.text('E {}'.format(result.status_code)) except Exception as e: text = str(e) print(text) wifi.disconnect() rgb.pixel((255, 0, 0), (31, 0)) # red for error rgb.setfont(1) rgb.text('No wifi') sleep(10) rgb.text(str(int(weather["main"]["temp"])), (255, 255, 255), (11, 1))
def stop(self, hub): if hasattr(self, 'mqtt'): self.mqtt.discon() wifi.disconnect() status_led.off()