Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5172

MicroPython • Re: main.py is not running on reboot/hard reset.

$
0
0
I moved the connection code into a class which loads into main.py using the following code:

lib/connect.py

Code:

import machineimport networkimport utimeclass Connect:    def __init__(self, ssid: str, password: str, hostname: str):        self.ssid = ssid        self.password = password        self.status: bool = False        self.wlan = network.WLAN(network.STA_IF)        self.wlan.active(True)        self.hostname = network.hostname(hostname)    def connect(self):        self.wlan.connect(self.ssid, self.password)        max_wait = 10        while max_wait > 0:            if self.wlan.status() < 0 or self.wlan.status() >= 3:                break            max_wait -= 1            print('waiting for connection...')            utime.sleep(1)        if self.wlan.status() != 3:            machine.reset()        else:            print('connected')            status = self.wlan.ifconfig()            print('ip = ' + status[0])
And then in main.py I instantiate the class just after the imports, and do a check to see if I am connect in the while True:

I also add a try/finally to my run code with the finally disconnecting the connection.

main.py

Code:

import ahtx0import secretsimport uasyncioimport ujsonimport urequestsfrom machine import Pin, I2Cfrom connect import Connectfrom lighting import Lightingfrom stemma_soil_sensor import StemmaSoilSensorwifi = Connect(    ssid=secrets.SSID,    password=secrets.PASSWORD,    hostname=secrets.HOSTNAME,)wifi.connect()lights = Lighting(count=secrets.PIXEL_COUNT, pin=secrets.LIGHT_PIN)air_i2c = I2C(secrets.I2C_ID, sda=Pin(secrets.SDA_PIN), scl=Pin(secrets.SCL_PIN), freq=20000)soil_i2c = I2C(secrets.I2C_ID, sda=Pin(secrets.SDA_PIN), scl=Pin(secrets.SCL_PIN), freq=20000)def get_profile(colors: list) -> list:    return [tuple(color_set) for color_set in colors]def c_to_f(c_temp: float) -> float:    return (c_temp * 9 / 5) + 32def read_sensors() -> dict:    air_sense = ahtx0.AHT20(air_i2c)    soil_sense = StemmaSoilSensor(soil_i2c)    sensor_data: dict = {        "air_temp": c_to_f(air_sense.temperature),        "humidity": air_sense.relative_humidity,        "moisture": soil_sense.get_moisture(),        "soil_temp": c_to_f(soil_sense.get_temp()),    }    return sensor_datadef post_data(data: dict) -> int:    sensor_post: dict = {        "project_id": secrets.PROJECT_ID,        "sensor_data": ujson.dumps(data),    }    try:        response = urequests.post(            url=f"{secrets.API_URL}/data",            headers={"Content-Type": "application/json"},            data=ujson.dumps(sensor_post),        )        return response.status_code    except Exception as e:        print(e)def get_status() -> dict:    try:        response = urequests.get(            url=f"{secrets.API_URL}/projects/{secrets.PROJECT_ID}/status",            headers={"Content-Type": "application/json"}        )        return response.json()    except Exception as e:        print(e)async def run_sensors():    while True:        sensor_data = read_sensors()        post_data(sensor_data)        await uasyncio.sleep(60 * 15)async def run_lights():    while True:        if not wifi.wlan.isconnected():            wifi.connect()        status_data = get_status()        print(status_data)        if status_data:            profile = get_profile(status_data.get("colors", [(255, 0, 0)]))            status = status_data.get("status", False)            if status and not lights.status:                lights.turn_on_all(profile=profile)            elif not status and lights.status:                lights.turn_off()        await uasyncio.sleep(60 * 15)event_loop = uasyncio.get_event_loop()event_loop.create_task(run_sensors())event_loop.create_task(run_lights())try:    event_loop.run_forever()finally:    wifi.wlan.disconnect()
It is working, but I think that I can be a little more defensive in the programming.

Statistics: Posted by TomCamp — Wed Jan 31, 2024 12:24 am



Viewing all articles
Browse latest Browse all 5172

Trending Articles