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

MicroPython • Re: pico w - aioble - httpd

$
0
0
Dunno if anyone will see this or care, but I've sorted out a lot in the past few days.

The goal if this is to be able to place a number of picos in strategic locations in my house, and keep track of something that has a BLE beacon attached to it. All the picos need to do is report the BLE mac and RSSI - once I have that data I'll have another system process that to attempt to determine the location using appropriate calculations.

To that end, I've completely revamped the code yet again. The HTTPD is out, and im using MQTT. I'm also only looking for one specific BT MAC that the device learns from an MQTT message.

Anyway, I'll share the code here in case anyone else either finds it useful or wants to offer any feedback. I know there are probably a few legacy lines that serve no purpose. Maybe I'll clean that up later. I want to move on for now.

Code:

from aioble import scan as aioblescanfrom picozero import pico_ledfrom time import time,sleepimport asyncioimport selectimport micropythonimport binasciiimport socketimport networkimport binasciiimport machineimport rp2import sysimport builtinsimport gcfrom umqtt.simple import MQTTClientmqtt_host = "MYSERVERNAME"mqtt_username = "MQTT_USER"  mqtt_password = "MQTT_PW"mqtt_receive_topic = "watchmac"mqtt_publish_topic = "foundmac"ssid = 'MYWIFI'password = 'MYWIFIPW'watchmac = Nonestarted=time()maxage=const(300)def connect():    #Connect to WLAN    wlan = network.WLAN(network.STA_IF)    wmacb=wlan.config('mac')    wmac=binascii.hexlify(wmacb).decode()    #binascii.hexlify(wmacb).decode()    network.hostname(f'BTSCANPICO-{wmac}')    wlan.active(True)    print('Connecting...')    wlan.connect(ssid, password)    counter=0    while wlan.isconnected() == False:        print(f'Waiting for connection...{counter}')        pico_led.on()        sleep(0.2)        pico_led.off()        sleep(0.2)        counter = counter + 1        if (counter > 20):            sleep(3)            if (wlan.isconnected() == False):                machine.reset()    pico_led.on()    ip = wlan.ifconfig()[0]    print(f'Connected on {ip} {wmac}')       #return ip, binascii.hexlify(wmacb).decode()    return ip, wmacasync def scan_task():    global started    global ip    s=0    while True:        print(f's {s}')        await asyncio.sleep(1)        s=s+1        async with aioblescan(duration_ms=1500, interval_us=20000, window_us=20000, active=True) as scanner:            async for result in scanner:                addrmac=binascii.hexlify(result.device.addr, ":").decode()                if (addrmac == watchmac):                    print(f'Found watched mac {addrmac} with rssi {result.rssi} \r\n')                    mqtt_client.publish(mqtt_publish_topic, f'{ip} {mqtt_client_id} {addrmac} {result.rssi}')def mqtt_subscription_callback(topic, message):    global watchmac    print ('...\r\n')    print (f'Topic {topic} received message {message}')  # Debug print out of what was received over MQTT    watchmacd = message.decode()    watchmac = watchmacd.lower()    mqtt_client.publish('status', f'watching {ip} {mqtt_client_id} {watchmac}')async def main():    loopcount=0    asyncio.create_task(scan_task())    await asyncio.sleep(0)          while True:        await asyncio.sleep(1)        if (loopcount == 0):            loopcount = 1            pico_led.on()        else:            loopcount = 0            pico_led.off()        mqtt_client.check_msg()        if ( watchmac != None):            print(f'Watching for {watchmac}')ip,wmac=connect()print(f'{ip} {wmac}')mqtt_client_id = wmacmqtt_client = MQTTClient(        client_id=mqtt_client_id,        server=mqtt_host,        user=mqtt_username,        password=mqtt_password)server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)server_socket.bind(('', 80))server_socket.listen(5)read_list = [server_socket]mqtt_client.set_callback(mqtt_subscription_callback)mqtt_client.connect()mqtt_client.subscribe(mqtt_receive_topic)print("Connected and subscribed")mqtt_client.publish('status', f'ready {ip} {mqtt_client_id}')asyncio.run(main())

Statistics: Posted by megadave — Thu Feb 20, 2025 2:27 am



Viewing all articles
Browse latest Browse all 9297

Trending Articles