pythonpython-asynciopython-socketiouvicorngpiozero

Running gpiozero listener continuously with uvicorn


I am trying to write a python app that will run on raspberry pi, that will have both socket connection (socketio with uvicorn) and physical input listeners. I intend to listen for socket connection and gpio events concurrently, without blocking each other. This is what I have so far:

api.py

import uvicorn
import asyncio
from interaction.volume import VolumeControl
from system.platform_info import PlatformInfo
from connection.api_socket import app


class Api:
    def __init__(self):
        pass

    def initialize_volume_listener(self):
        volume_controller = VolumeControl()
        volume_controller.start_listener()

    def start(self):
        PlatformInfo().print_info()
        self.initialize_volume_listener()
        uvicorn.run(app, host='127.0.0.1', port=5000, loop="asyncio")

volume_control.py

import asyncio
from gpiozero import Button
from connection.api_socket import volume_up


class VolumeControl:
    def __init__(self):
        self.volume_up_button = Button(4)

    def volume_up(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        future = asyncio.ensure_future(volume_up(None, None))
        loop.run_until_complete(future)
        loop.close()

    def start_listener(self):
        self.volume_up_button.when_pressed = self.volume_up

api_socket.py

import socketio
from system.platform_info import PlatformInfo

sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*')
app = socketio.ASGIApp(sio)


@sio.on('connect')
async def test_connect(sid, environ):
    system_info = PlatformInfo().get_info()
    current_volume = 35
    initial_data = {"system_info": system_info,
                    "settings": {"volume": current_volume}
                    }
    await sio.emit('initial_data', initial_data, room=sid)


@sio.on('disconnect request')
async def disconnect_request(sid):
    await sio.disconnect(sid)


@sio.on('disconnect')
async def test_disconnect(sid):
    print('Client disconnected')
    await sio.emit('disconnect', {'data': 'Connected', 'count': 0}, room=sid)


@sio.on('volume_up')
async def volume_up(sid, volume=None):
    increased_volume = 25
    await sio.emit('volume_up', {'volume': increased_volume})


@sio.on('volume_down')
async def volume_down(sid, volume=None):
    decreased_volume = 25
    await sio.emit('volume_down', {'volume': decreased_volume})

I have tried using asyncio, but I am kind of new on async features of python. The problem is that, I wasn't able to run the button listener continuously, so that while socket functions are in progress, I would be able to concurrently listen for button interactions, without blocking one another. The button listener does not work at all. Instead, I need the button listener to be running as long as the uvicorn app is up.

Any help will be appreciated. Thanks.


Solution

  • @Miguel thank you for your answer. As you suggested, I have started the gpio in a while loop and used asyncio.run() command inside the loop to call the related socketio function. It works as intended. Side Note: I have started the gpio thread with param daemon=True. This enables to quit the gpio loop as soon as I quit the main thread, which is the uvicorn server. Final code is as follows:

    api_socket.py

    @sio.on('video_load')
    async def load_video(sid, video_number=3):
        data = open(os.path.join(os.getcwd(), f'sample_videos/dummy_video_{str(video_number)}.mp4'), 'rb').read()
        print('Streaming video...')
        await sio.emit('video_load', {'source': data}, room=sid)
    

    nfc_listener.py

    class NFCListener:
    
        reading = True
    
        def __init__(self):
            GPIO.setmode(GPIO.BOARD)
            self.rdr = RFID()
            util = self.rdr.util()
            util.debug = True
            self.listener_thread = threading.Thread(target=self.start_nfc, daemon=True)
    
        def start_nfc(self):
            selected_video = None
            while self.reading:
                self.rdr.wait_for_tag()
                (error, data) = self.rdr.request()
                if not error:
                    print("\nCard identified!")
                    (error, uid) = self.rdr.anticoll()
                    if not error:
                        # Print UID
                        card_uid = str(uid[0])+" "+str(uid[1])+" " + \
                            str(uid[2])+" "+str(uid[3])+" "+str(uid[4])
                        print(card_uid)
                        if card_uid == "166 107 86 20 143":
                            if selected_video != 2:
                                selected_video = 2
                                asyncio.run(load_video(None, selected_video))
                        else:
                            if selected_video != 3:
                                selected_video = 3
                                asyncio.run(load_video(None, selected_video))
    
        def start_reading(self):
            self.listener_thread.start()