def main(): wlan = wm.get_connection() if wlan is None: print("Could not initialize the network connection.") while True: pass # you shall not pass :D try: client.connect() except Exception as e: print('could not connect to MQTT server {}{}'.format( type(e).__name__, e)) sys.exit() #do_connect() last_mesurement_time = 0 client.set_callback(call_back_routine) client.subscribe(mqtt_feedname2) client.subscribe(mqtt_feedname3) client.subscribe(mqtt_feedname4) last_notification = time.time() - 3610 switch_0ff("off") while True: if (not wlan.isconnected()): wlan = wm.get_connection() client.connect() client.set_callback(call_back_routine) client.subscribe(mqtt_feedname2) client.subscribe(mqtt_feedname3) client.subscribe(mqtt_feedname4) if wlan is None: print("Could not initialize the network connection.") while True: pass # you shall not pass :D client.check_msg() i = len(threshold_notify) if i == 0: i = 1 j = len(threshold_notify) if j == 0: j = 1 current_time = time.time() if current_time - last_mesurement_time > MESUREMENT_INTERVAL: adc = machine.ADC(0) print('Moisture:', adc.read()) Send_Data(adc.read()) if adc.read() > threshold_notify[ i - 1] and last_notification + notification_interval < current_time: print(threshold_notify[i - 1]) notify("The soil is dry its time to turn on water.") last_notification = current_time if pin2.value() == 0 and adc.read() < threshold_water[j - 1]: pin2.value(1) switch_0ff("off") last_mesurement_time = current_time
def main(): LED_PIN = config.CONFIG.get('led_pin', 13) pin = Pin(LED_PIN, Pin.OUT) pin.value(0) # Attempt to connect to Wifi network. wlan = wifimgr.get_connection() # Bind to UART 2 to handle RPC requests. uart = UART(2, baudrate=115200) uart_awriter = asyncio.StreamWriter(uart, {}) uart_areader = asyncio.StreamReader(uart) # Bind I2C connection for controlling motor drivers i2c_config = config.CONFIG.get('i2c', {}) i2c = I2C(scl=Pin(i2c_config.get('scl', 22)), sda=Pin(i2c_config.get('sda', 23)), freq=i2c_config.get('freq', 10000)) motor_ctrl = motor.GroveMotorControl(i2c) # Expose globals to RPC context context = globals().copy() # Expose locals to RPC context ([note MicroPython `locals()` caveat][1]) # # [1]: https://github.com/micropython/micropython/wiki/Differences#differences-by-design context.update(locals()) # Explicitly add local variables to context, since (see [here][1]): # # > MicroPython optimizes local variable handling and does not record or # > provide any introspection info for them, e.g. **locals() doesn't have # > entries for locals.** # # [1]: https://github.com/micropython/micropython/wiki/Differences#differences-by-design context['i2c'] = i2c context['motor_ctrl'] = motor_ctrl context['uart'] = uart context['wlan'] = wlan # Remove `rpc` module from context to avoid recursive reference in # `rpc.rpc()` function. rpc = context.pop('rpc', None) # Reclaim memory associated with any temporary allocations. gc.collect() loop = asyncio.get_event_loop() pin = Pin(LED_PIN, Pin.OUT) pin.value(1) # Start RPC task. loop.run_until_complete( rpc.rpc(uart_areader, uart_awriter, context=context)) pin.value(0) # Reclaim memory associated with any temporary allocations. gc.collect()
def fetch_update(API_TOKEN, tag=None, output_dir='/ota-next', cache=False, verbose=True): # Try to connect to wifi wlan = get_connection() if wlan is None: raise RuntimeError('No network connection.') if not util.exists(output_dir): os.mkdir(output_dir) repo = Repo(REPO_URL, api_token=API_TOKEN, username=USERNAME) if tag is None: tag = repo.latest_version() downloaded = [] for path in ('/app', '/lib'): contents = repo.tag_contents(tag, path=path) try: downloaded += repo.download(contents, root=output_dir + path, cache=cache, verbose=verbose) except Exception as exception: print('error fetching update: `%s`' % contents) raise with open(output_dir + '/VERSION', 'w') as output: output.write(tag + '\n') gc.collect() return downloaded
def main(): wlan = get_connection() gc.collect() for package in ('urequests', 'shutil', 'uasyncio', 'functools'): upip.install(package) gc.collect()
def wifiConnect(): # Manage Wifi connection wlan = wifimgr.get_connection() if wlan is None: print("Could not initialize the network connection.") oledPrint(l1="No Wifi connection") while True: pass # you shall not pass :D else: print("Connected to wifi") oledPrint('Connected', wlan.ifconfig()[0])
def connect_wifi(): wlan = wifimgr.get_connection() if wlan is None: print('Could not initialize the network connection') if is_debug_mode(): # Start web server for connection manager wifimgr.start() else: print('Reconnecting in 1 second...') time.sleep(1) connect_wifi()
def get_connection(): import wifimgr import sys import gc wlan = None while not wlan: wlan = wifimgr.get_connection() del wifimgr del sys.modules['wifimgr'] gc.collect() return wlan
def verifyWifiStatus(): global wlan if not wlan or (not wlan.isconnected()): lcd.clear() pictoSmall.print("0", 2, 0) font.print(" WStation ") pictoSmall.print("0") font.print("Connecting to", 0, 2) font.print("wifi...", 0, 3) pictoSmall.print("w", 37, 5) wlan = wifimgr.get_connection(cb_error=displayInstructions, cb_success=displaySuccess) print("Waiting...") utime.sleep(2) print("Done.")
try: response = urequests.post("http://192.168.0.11:8060/keypress/play") print("API Response %s" % response.status_code) return response.status_code == 200 except: print("Error !!!") log("Error !!!", 0, 40) return False # Get OLED display & Distance sensor oled, sensor = init() # Connect to WIfi log("Connecting...", 0, 0) wlan = wifimgr.get_connection() if wlan is None: log("No wifi !!!", 0, 20) print("Unable to connect to Wifi") else: log("Connected :-)", 0, 20) wifimgr.deactivate_ap() print("Deactivated AP mode.") time.sleep_ms(1000) prevDistance = -1 isPaused = False while True: currDistance = int(sensor.distance_cm())
import wifimgr from time import sleep import machine import _thread import mqtt_controle import tempo import data import controle try: import usocket as socket except: import socket led = machine.Pin(2, machine.Pin.OUT) wlan = wifimgr.get_connection() # criar o wifi-manager if wlan is None: print("Não foi possível inicializar a conexão.") while True: pass # codigo do do controle apartir daqui. t1 =_thread.start_new_thread(mqtt_controle.inicializar,()) t2 =_thread.start_new_thread(tempo.prev_temp,()) sleep(2) t3 =_thread.start_new_thread(data.atualizador,())
import zabbixsender import time import machine led = LED.LED() led.pin.on() # check if the device woke from a deep sleep if machine.reset_cause() == machine.DEEPSLEEP_RESET: print('woke from a deep sleep') # configure RTC.ALARM0 to be able to wake the device rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) wlan = wifimgr.get_connection(failover=False) for count in range(60): led.Blink(10, 0.1) if wlan and wlan.isconnected() == True: led.pin.off() break if wlan and wlan.isconnected() == True: pass else: #reboot: retry initialize the network connection machine.reset() # Main Code goes here, wlan is a working network.WLAN(STA_IF) instance. print("ESP OK") led.Blink(2, 0.2)
def task1(): u = UART(1, 9600) #only tx can be used = Pin(2) c = config('data.ini') # u.read() #UART(1) can't read ret = c.readAll() # rtc = machine.RTC() # rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) # mywifi.WIFI() wlan = wifimgr.get_connection() ##### #upload url = "http://api.heclouds.com/devices/643534dxx/datapoints" headers = {'api-key': 'gjxxxxxxxxxxx'} data_name = ["lock"] data_value = [0] def upload(): # global data_name,data_value temp_list = [] for ii in range(len(data_name)): # temp_list.append({'id':data_name[ii],'datapoints':[{'value':'%.1f' % data_value[ii]}]} ) temp_list.append({ 'id': data_name[ii], 'datapoints': [{ 'value': data_value[ii] }] }) data = {'datastreams': temp_list} rp = urequests.post(url, headers=headers, data=json.dumps(data)) rp.close() #update # upload() ### def down(): # global data_name,data_value r = urequests.get(url, headers=headers) data_value[0] = r.json( )['data']['datastreams'][0]['datapoints'][0]['value'] data_value[0] = (int)(data_value[0]) r.close() #esp32的urequest,记得关 close !!! ##### while 1: try: print("start") down() if data_value[0] == 1: print("open") u.write(ret['open']) data_value[0] = 0 #update upload() elif data_value[0] == 2: print("close") u.write(ret['close']) data_value[0] = 0 #update upload() except: print("error") time.sleep(5) #60 machine.reset()
def task1(): # rtc = machine.RTC() # rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) # mywifi.WIFI() wlan = wifimgr.get_connection() ########################## out = Pin(2, Pin.OUT, Pin.PULL_UP) out0 = Pin(0, Pin.OUT, Pin.PULL_UP) def open(): # global out out.on() out0.off() def close(): # global out out.off() out0.on() close() ##### #upload url = "http://api.heclouds.com/devices/611890860/datapoints" headers = {'api-key': 'gjU2173SbsvrSi4OpLyK8IXW3tc='} data_name = ["lock"] data_value = [0] def upload(): # global data_name,data_value temp_list = [] for ii in range(len(data_name)): # temp_list.append({'id':data_name[ii],'datapoints':[{'value':'%.1f' % data_value[ii]}]} ) temp_list.append({ 'id': data_name[ii], 'datapoints': [{ 'value': data_value[ii] }] }) data = {'datastreams': temp_list} rp = urequests.post(url, headers=headers, data=json.dumps(data)) rp.close() #update # upload() ### def down(): # global data_name,data_value r = urequests.get(url, headers=headers) data_value[0] = r.json( )['data']['datastreams'][0]['datapoints'][0]['value'] data_value[0] = (int)(data_value[0]) r.close() #esp32的urequest,记得关 close !!! ##### while 1: try: print("start") down() if data_value[0] > 0: print("open") open() time.sleep(data_value[0]) #一般是1s 强制关机5~6s close() data_value[0] = 0 #update upload() except: print("error") time.sleep(60) machine.reset()
import wifimgr as wm wlan = wm.get_connection() if wlan is None: print("Could not initialize the network connection.") while True: pass # you shall not pass :D # Main Code goes here, wlan is a working network.WLAN(STA_IF) instance. print("ESP OK") from machine import Pin import network import time from umqtt.robust import MQTTClient import sys import os import ujson import urequests data2send = { "type": "note", "title": "Msg From NodeMCU", "body": "", } API_KEY = 'api key' pb_headers = { 'Access-Token': API_KEY, 'Content-Type': 'application/json', 'Host': 'api.pushbullet.com' }