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

Python • Micropython asyncio help

$
0
0
Hi their

I have been having this issue with some new code i wrote, I managed to strip my code back to bare minimum and its consistent every time on the 6th message sent from client to server it locks up both server and client.

I am the creator of the https://github.com/woodycal/pico-secure-delivery-box so hardware i am using is a pico 2 w with micro python v1.25.0.

The full code can be found here https://github.com/woodycal/pico-secure ... icotkinter

Anyways here is the stripped down code bare minimum not professional programmer by the way, totally the opposite.

server code run on pico 2 w:

Code:

import asyncioimport networkimport timessid = 'yourssid'password = 'yourpassword'def init_wifi(ssid, password):    wlan = network.WLAN(network.STA_IF)    wlan.active(True)    # Connect to your network    wlan.connect(ssid, password)    # Wait for Wi-Fi connection    connection_timeout = 10    while connection_timeout > 0:        print(wlan.status())        if wlan.status() >= 3:            break        connection_timeout -= 1        print('Waiting for Wi-Fi connection...')        time.sleep(1)    # Check if connection is successful    if wlan.status() != 3:        print('Failed to connect to Wi-Fi')        return False    else:        print('Connection successful!')        network_info = wlan.ifconfig()        print('IP address:', network_info[0])        return Trueasync def handle_client(reader, writer):    global state, weather_value, schedule1, schedule2, schedule3, schedule4    while True:        data = await reader.read(1024)        if not data:            break        message = data.decode().strip()        print(f"Received \"{message}\" from {writer.get_extra_info('peername')}")                if message == 'ARMED':            state = 'ARMED'            print(f"Send: {state!r}")            writer.write(state.encode())            await writer.drain()            print("Close the connection")            writer.close()            writer.wait_closed()        elif message == 'DISARMED':            state = 'DISARMED'            dropboxvalue = 0            relay_lock.value(1)            print(f"Send: {state!r}")            writer.write(state.encode())            await writer.drain()            print("Close the connection")            writer.close()            writer.wait_closed()        elif message == 'DROPOFFMODE':            state = 'DROPOFFMODE'            dropboxvalue = 0            relay_lock.value(1)            print(f"Send: {state!r}")            writer.write(state.encode())            await writer.drain()            print("Close the connection")            writer.close()            writer.wait_closed()        elif message == 'getweathervalue':            weather_value = "Example Weather Value"            print(f"Send: {weather_value!r}")            writer.write(weather_value.encode())            await writer.drain()            print("Close the connection")            writer.close()            writer.wait_closed()        elif message.startswith('schedule'):            schedule_data = parse_schedule(message)            if schedule_data:                store_schedule(schedule_data)                print(f"Stored schedule: {schedule_data}")        elif message.startswith('GETSTATE'):            print(f"Send: {state!r}")            writer.write(state.encode())            await writer.drain()            print("Close the connection")            writer.close()            writer.wait_closed()        elif message.startswith('CLEARSCHEDULES'):            schedule1 = {}            schedule2 = {}            schedule3 = {}            schedule1 = {}        else:            print(f"Unknown command: {message}")async def run_server():    if not init_wifi(ssid, password):        return        server = asyncio.start_server(handle_client, '0.0.0.0', 8080)    asyncio.create_task(server)        loop = asyncio.get_event_loop()# Create a task to run the main functionloop.create_task(run_server())try:    # Run the event loop indefinitely    loop.run_forever()except Exception as e:    print('Error occured: ', e)except KeyboardInterrupt:    print('Program Interrupted by the user')
client code:

Code:

import socketHOST = 'ip_address_pico' #server hostPORT = 8080data_payload = 2048style = 'utf-8'def echo_armed():    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    server_address = (HOST, PORT)    try:        sock.connect(server_address)        sock.send("ARMED".encode(style))        datamain = sock.recv(data_payload)        data1main = datamain.decode(style)        if data1main == "ARMED":            print("message sent")    except Exception as e:(        print(f"Error in echo_armed: {e}"))    finally:        sock.close()echo_armed()
Just wondering if the issue after exactly 6 messages sent is to do with my code.

Many thanks

Statistics: Posted by shaun27 — Sun Feb 16, 2025 7:27 pm — Replies 1 — Views 30



Viewing all articles
Browse latest Browse all 4720

Trending Articles