micropython icon indicating copy to clipboard operation
micropython copied to clipboard

Radio: equivalent to uart's `any`

Open tobyspark opened this issue 7 years ago • 0 comments

The radio API is awkward if you want to broadcast state messages. e.g. You cannot check for any new messages to break out of a loop without actually pulling the message out of the module; the uart module has any for this purpose.

Code speaking a thousand words, here's what I needed to get what me and bunch of teenagers built in a workshop actually running reliably, written after-the-fact.

class RadioLatest():
    '''
    A only-care-about-the-latest wrapper for the micro:bit radio class.
    Used in http://tobyz.net/projects/wipeout
    '''
    def __init__(self):
        radio.on()
        self.current_message = None

    def any(self):
        '''
        Checks for new messages and returns true if so.
        Can be used to e.g. break out of animation loops
        '''
        while True:
            message = radio.receive()
            if message:
                self.current_message = message
            else:
                break
        return bool(self.current_message)

    def message_peek(self):
        '''
        Returns the current message while keeping it the current message. Message may be None.
        Can be used to e.g. verify the message qualifies to break out of an animation loop
        '''
        return self.current_message

    def message_get(self):
        '''
        Returns and removes the current message. Message may be None
        '''
        self.any()
        message = self.current_message
        self.current_message = None
        return message

– which allows you to break out of e.g. animation loops if a message is received –

if radio_latest.any():
    return

– and your main loop can then be –

while True:
    if radio_latest.any():
        incoming = radio_latest.message_get()
    else:
        sleep(10)
        continue

    if incoming == ...
        ...

tobyspark avatar Jan 23 '19 17:01 tobyspark