def init(): print('trains/main: Init') ugfx.init() ntp.set_NTP_time() # ensure wifi connection if not wifi.is_connected(): wifi.connect(show_wait_message=True)
def mqtt(self, state): self.oled.write_lines( 'WIFI:', ('%8d' % wifi.rssi()) if wifi.is_connected() else ('%8s' % '--'), 'MQTT:', '%8s' % ('OK' if state.mqtt else '--'), )
def __init__(self, state): led = None if reset_cause() == DEEPSLEEP_RESET else StatusLED(config.LED) wifi.connect(secrets.WIFI_NAME, secrets.WIFI_PASSWORD, led=led) if wifi.is_connected(): print(wifi.mac(), wifi.ip(), wifi.rssi()) mqtt = MQTT(config.NAME, secrets, uid = UID, led=led) opt = dict(exp_aft = config.FREQ * 2.5) mqtt.add('Temp', Temperature, **opt).set_state(state['temp']) mqtt.add('Humid', Humidity, **opt).set_state(state['humid']) mqtt.set_attr("freq", config.FREQ) mqtt.do_pub_cfg = reset_cause() != DEEPSLEEP_RESET or ticks_us() % 10 == 0 mqtt.connect() sleep(1) mqtt.pub_state() sleep(5) mqtt.discon() sleep(5)
def update(self, state, changed): self.oled.rst() self.oled.txt('WIFI:%3d' % (wifi.rssi() if wifi.is_connected() else 0)) self.oled.txt( 'MQTT:%3s' % ('OK' if hasattr(state, 'mqtt') and state.mqtt else '--')) self.oled.txt('SOLR:%3d' % state.solar_temp) self.oled.txt('TANK:%3d' % state.tank_temp) self.oled.txt('TARG:%3d' % state.tank_target_temp) self.oled.txt('%-4s:%3s' % (state.mode.upper(), 'ON' if state.pump else 'OFF'))
def publish(self, tpc, msg, **kwarg): print(' <', 'tx', tpc) print(' <', 'tx', msg) if wifi.is_connected() and self.mqtt: if type(tpc) != type(b''): tpc = tpc.encode(UTF8) if type(msg) != type(b''): msg = msg.encode(UTF8) self.mqtt.publish(tpc, msg, **kwarg) sleep(0.5) print(' <', 'tx', 'ok') return True return False
def sync(sender): wireless = wifi.is_connected() show_wifi_status() if wireless: views[0]['label2'].text = 'Connecting...' drive = Drive() updated = drive.update('journal.jl') sync_status_alert(updated) if updated: views[0]['label2'].text = 'All changes saved to Google Drive' else: views[0]['label2'].text = 'Out of Sync' else: console.alert('WiFi required for sync')
def try_pub_cfg(self): ok = False if wifi.is_connected(): try: if not self.mqtt: self.do_pub_cfg = True self.connect() ok = True else: ok = self.pub_cfg() except Exception as e: print_exception(e) self.discon() self.do_pub_cfg = False return ok
def pub_json(self, tpc, obj, **kwarg): gc_collect() print(tpc) print(obj) if wifi.is_connected() and self.mqtt: if type(tpc) != type(b''): tpc = tpc.encode(UTF8) with BytesIO() as json: json_dump(obj, json) gc_collect() self.mqtt.publish(tpc, json.getvalue(), **kwarg) sleep(0.5) gc_collect() return True return False
def __init__(self, state): print(wifi.uid()) if reset_cause() != DEEPSLEEP_RESET: status_led.slow_blink() wifi.connect(secrets.WIFI_NAME, secrets.WIFI_PASSWORD) status_led.off() mqtt = MQTT(config.NAME, secrets, uid=UID) opt = dict(exp_aft=config.FREQ * 2.5) if 'temp' in state: from home_assistant.sensors.temperature import Temperature mqtt.add('Temp', Temperature, **opt).set_state(state['temp']) if 'humid' in state: from home_assistant.sensors.humidity import Humidity mqtt.add('Humid', Humidity, **opt).set_state(state['humid']) if 'lux' in state: from home_assistant.sensors.illuminance import Illuminance mqtt.add('Lux', Illuminance, **opt).set_state(state['lux']) if 'analog' in state: mqtt.add('Analog', Sensor, unit="%", icon="mdi:gauge", **opt).set_state(state['analog']) if 'battery' in state: from home_assistant.sensors.battery import Battery mqtt.add('Battery', Battery, key='bat', **opt).set_state(state['battery']) mqtt.set_attr('battery', state['battery']) mqtt.set_attr("freq", config.FREQ) if wifi.is_connected(): if reset_cause() != DEEPSLEEP_RESET: status_led.fast_blink() mqtt.connect() sleep(1) mqtt.pub_state() status_led.off() sleep(5) mqtt.discon() sleep(5)
def start(): ugfx_helper.init() loading_screen() if not wifi.is_connected(): try: wifi.connect() except OSError: display_error("Unable to connect to Wifi") return False try: load_account_details() except OSError as e: display_error("Unable to contact the server. Please try again later") return False if len(projects) == 0: display_error("Sorry, no projects are available to display") return False load_camera_dates() load_image_list() return True
def __connect(self, reconnect=False): self.__display.draw_background(ugfx.WHITE) ugfx.set_default_font(ugfx.FONT_SMALL) ugfx.text(10, 120, "Connecting to Wifi...", ugfx.BLACK) print("emf_hub_mon: Connecting to Wifi") if reconnect: self.__disconnect_mqtt() wifi.nic().disconnect() while not wifi.is_connected(): try: wifi.connect(wait=True, timeout=15) except: pyb.delay(200) ugfx.set_default_font(ugfx.FONT_SMALL) ugfx.text(10, 140, "Connecting to MQTT...", ugfx.BLACK) self.__connect_mqtt() pyb.delay(1000)
def pub(_): self._sched = False if config.COMPNT != None: if hub.light_cmd: hub.light_cmd = False try: self.mqtt.publish(light.cmd_tpc(), light.ON if hub.light else light.OFF, retain = True) except: pass light.set_state(hub.light) if config.COMPNT == LIGHT and config.BRIGHTNESS: light.set_bri(hub.brightness) if config.MOTN: motion.set_state(hub.motion) enable.set_state(hub.enable) if config.COMPNT != None: auto.set_state(hub.auto) if config.BATT: battery.set_state(hub.battery) self.mqtt.set_attr(BATT, hub.battery) if wifi.is_connected(): self.mqtt.set_attr('rssi', wifi.rssi()) self.mqtt.pub_state()
def start(self, hub): if hub.internet: status_led.fast_blink() wifi.connect(secrets.WIFI_NAME, secrets.WIFI_PASSWORD) status_led.off() sleep(2) if wifi.is_connected(): status_led.fast_blink() self.mqtt = MQTT(config.NAME, secrets, uid=UID) self.mqtt.add('Water', Moisture, prim=True, key='water', off_dly=config.NORMAL_SLEEP).set_state(hub.water) enable = self.mqtt.add('Enable', Switch, icon="mdi:bell") def enable_rx(msg): hub.set(enable=msg == enable.ON) self.mqtt.sub(enable.cmd_tpc(), enable_rx) self.mqtt.add('Battery', Battery, key='bat').set_state(hub.battery) self.mqtt.set_attr('battery', hub.battery) self.mqtt.set_attr('rssi', wifi.rssi()) self.mqtt.do_pub_cfg = self.do_pub_cfg self.mqtt.connect() sleep(1) self.mqtt.pub_state() sleep(1) status_led.off()
def wait(self, led=None): while self.reconnect: try: if wifi.is_connected(): self.connect() while True: gc_collect() try: self.mqtt.wait_msg() except RxEx: pass else: print('No WiFi') except Exception as e: print('MQTT' + ':') print_exception(e) self.discon() if self.reconnect: if led: led.slow_blink() sleep(random_int(5)) led.off() else: sleep(random_int(8))
def show_wifi_status(): views[0]['label4'].text = str(wifi.is_connected())
def connect(): if not wifi.is_connected(): with dialogs.WaitingMessage(text=wifi.connection_text(), title="TiLDA App Library") as message: wifi.connect()
from http_client import get import ugfx import buttons import wifi from dialogs import notice DIALOG_TITLE = "EMF Number One" def dialog(message): notice(message, title=DIALOG_TITLE) drawui() if not wifi.is_connected(): dialog("It looks like your wifi isn't connected, so you probably won't be able to access the sign. You may want to reset your badge?") def wiggle(): request("Let's give it some wiggle!", "I see you baby, #shakingthadass!!", "/lights") drawui() def disco(): request("Let's get disco, honey!", "Hope you enjoyed some disco action!!", "/disco") drawui() def request(before, after, uri): dialog(before) drawui()
def test_connect(self): wifi.connect(show_wait_message=True) self.assertTrue(wifi.is_connected())
hpos = 1 showevent(venue[vpos], data[venue[vpos]][hpos]) if buttons.is_triggered("JOY_UP"): print(hpos) hpos = 0 showevent(venue[vpos], data[venue[vpos]][hpos]) if buttons.is_triggered("BTN_A"): # Need to Implement fetching description by ID here pass if buttons.is_triggered("BTN_B"): mainscreen() return #Check and Connect to WiFi if wifi.is_connected(): pass else: wifi.connect() #Init GFX and Buttons ugfx.init() buttons.init() #Server Address server = 'badge.emf.camp' #Main Screen mainscreen() while True: if buttons.is_triggered('BTN_A'):
ugfx.text(40,75,"Press [A] to continue",ugfx.YELLOW) return def getdata(): server = 'badge.emf.camp' #url = 'http://'+server+':9002/schedule' #url = 'http://hackspace-leaderboard-scollins.c9users.io/schedule' url = 'http://api.ipify.org/' resp = get(url).text ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000) while True: ugfx.text(30,30,resp,ugfx.WHITE) return json.loads(resp) #Check and Connect to WiFi if wifi.is_connected(): pass else: wifi.connect() #Init GFX and Buttons ugfx.init() buttons.init() #Main Screen mainscreen() while True: if buttons.is_triggered('BTN_A'): getdata() if buttons.is_triggered('BTN_B'): mainscreen()
cloudant_url = settings["cloudant_url"] cloudant_auth = settings["cloudant_auth"] db_name = settings["db_name"] dev_id = settings["dev_id"] led = Pin(2, Pin.OUT) # base_url = 'http://{}:{}'.format(server, port) # headers = {'Authorization': 'Basic {}'.format(base64_auth)} base_url = 'https://{}'.format(cloudant_url) headers = {'Authorization': 'Basic {}'.format(cloudant_auth)} sleep(2) while True: led.value(0) if wifi.is_connected() == False: wifi.connect(ap, ap_pass) try: res = db.add_doc_with_update( base_url, db_name, '_design/utils/_update/add_with_timestamp', { 'dev_id': dev_id, 'temperature': 20 + rnd.getrandbits(4), 'humidity': 80 + rnd.getrandbits(4) }, headers=headers) print(res) except OSError as err: print(err) led.value(1)
___categories___ = ["EMF"] # borrowed from https://github.com/micropython/micropython/blob/master/esp8266/scripts/ntptime.py import ugfx, ntp, wifi, utime, machine, app from tilda import Buttons # initialize screen ugfx.init() ugfx.clear() # set the RTC using time from ntp # print out RTC datetime if not wifi.is_connected(): wifi.connect(show_wait_message=True) ntp.set_NTP_time() rtc = machine.RTC() ugfx.orientation(270) count = 0 last = None while 1: now = rtc.now()[:6] year = now[0] month = now[1] day = now[2] hour = now[3] minute = now[4] second = now[5] if now != last: