[Python] Running WebSocket server and separate while loop simultaneously

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    The following code is for a RC flight controller based around an Raspberry Pi (Zero 2W). The purpose of the code is to receive input controls from my Iphone while also managing a few PID controllers to control the RC planes control surfaces. The script is written in python.

    import smbus
    from time import sleep
    import time
    import math
    import RPi.GPIO as GPIO
    from gpiozero import Servo
    from gpiozero.pins.pigpio import PiGPIOFactory
    import asyncio
    import websockets
    import json

    #Initialize sensors

    async def handler(websockets):
    async for message in websockets:
    print("Raw message recieved:" + str(message))
    try:
    data = json.loads(message)
    pitch = data.get("pitch", 0)
    roll = data.get("roll", 0)
    yaw = data.get("yaw", 0)
    throttle = data.get("throttle", 0)

    print(f"Pitch: {pitch}, Roll: {roll}, Yaw: {yaw}, Throttle: {throttle}")

    except json.JSONDecodeError as e:
    print("Invalid JSON recieved:" , e)


    async def WebSocketInitialization():
    async with websockets.serve(handler, "0.0.0.0", ####):
    print("Websocket server started on port ####")
    await asyncio.Future()



    async def main():
    #Initialize Servos & Sensors


    #Declearing variables for PID Controllers


    #PID controllers
    while True:
    #Reading Sensors

    #Code for all PID Controllers

    #Code for executing output of PID controllers


    async def AsyncStart():
    asyncio.gather(WebSocketInitialization(), main())

    asyncio.run(AsyncStart())


    If the last line of the code is exchanged for "asyncio.run(WebSocketInitialization())", the WebSocket server and sending information form my iphone works perfectly. If the last line of the code is exchanged for "asyncio.run(main())", the PID controllers works wonderfully. However, I can't get these two to work on the same time.

    If I try to run the code pasted above, the PID controllers initializes and runs but the WebSocket server isn't initialized (I never get the "Websocket server started on port ####") message.

    I have tried TaskGroup() instead of .gather without success. I also tried to move the WebSocket code inside the PID-controllers while True: loop, but without success.

    Continue reading...

Compartilhe esta Página