Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to pass user data to protocol's callbacks? #98

Open
zapta opened this issue Apr 30, 2023 · 1 comment
Open

How to pass user data to protocol's callbacks? #98

zapta opened this issue Apr 30, 2023 · 1 comment

Comments

@zapta
Copy link

zapta commented Apr 30, 2023

Below is the OutputProtocol example from the documentation. Is there a way to pass to it user data that is configured at instantiation time? E.g. passing to serial_asyncio.create_serial_connection() a user value that will be propagated to the callback functions of OutputProtocol's ?

The difficulty I have is 1) I don't control the instantiation of this object and 2) I am not familiar with *args and **kwargs in case they hold the answer.

I could try to set the value myself in the protocol returned by serial_asyncio.create_serial_connection() but is there a guarantee that it will be called before the first callback is invoked?

import asyncio
import serial_asyncio

class OutputProtocol(asyncio.Protocol):
    def connection_made(self, transport):
        self.transport = transport
        print('port opened', transport)
 
...
@tfh-cri
Copy link

tfh-cri commented Nov 3, 2024

The docs for pyserial_asyncio.make_serial_connection() include:

Note: protocol_factory can be any kind of callable, not
necessarily a class. For example, if you want to use a pre-created
protocol instance, you can pass lambda: my_protocol.

class SerialOutputProtocol(Protocol);
    def __init__(self, obj, on_conn_lost_future):
        super().__init__()
        self.obj = obj
        self.on_conn_lost = on_conn_lost_future

# ...

on_conn_lost = loop.create_future()
self.transport, self.protocol = (
    await serial_asyncio.create_serial_connection(
        loop,
        lambda: SerialOutputProtocol(
            obj=self, on_conn_lost=on_conn_lost
        ),
        port,
    )
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants