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

working on TCPKISSDevice #6

Closed
hemna opened this issue Feb 23, 2021 · 5 comments
Closed

working on TCPKISSDevice #6

hemna opened this issue Feb 23, 2021 · 5 comments

Comments

@hemna
Copy link
Contributor

hemna commented Feb 23, 2021

I'm trying to wrap my head around how this package works.
I'm trying to use this to connect to direwolf's TCP KISS interface to recieve aprs messages.

I haven't quite figured out how the KISSPort maps to a TCP based kissdevice, but my test script looks like this.

kissdev = kiss.TCPKISSDevice("192.168.1.7", 8001, log=LOG)
kissdev.open()

kissport0 = kissdev[0]

ax25int = interface.AX25Interface(
    kissport=kissport0,
    log=LOG
)

aprsint = APRSInterface(
    ax25int=ax25int,
    mycall='WB4BOR',
    log=LOG
)

But it just just and exits. How do I get this to loop forever waiting for packets to come in?

[02/22/2021 07:57:44 PM][MainThread  ][DEBUG] [/home/waboring/devel/aioax25/aioax25/kiss.py.__init__:446] Created
[02/22/2021 07:57:44 PM][MainThread  ][DEBUG] [/home/waboring/devel/aioax25/aioax25/kiss.py.open:386] Opening device
[02/22/2021 07:57:44 PM][MainThread  ][DEBUG] [/home/waboring/devel/aioax25/aioax25/kiss.py._open:449] Call open
[02/22/2021 07:57:44 PM][MainThread  ][DEBUG] [/home/waboring/devel/aioax25/aioax25/kiss.py._open:455] Call open Done
[02/22/2021 07:57:44 PM][MainThread  ][DEBUG] [/home/waboring/devel/aioax25/aioax25/kiss.py.__getitem__:373] OPEN new port 0
[02/22/2021 07:57:44 PM][MainThread  ][DEBUG] [/home/waboring/devel/aioax25/aioax25/kiss.py.__getitem__:375] <aioax25.kiss.KISSPort object at 0x7f82202bbcd0>

My TCPKISSDevice class looks like this:

class TCPKISSDevice(BaseKISSDevice):

    _interface = None
    READ_BYTES = 1000

    def __init__(self, host: str, port: int, *args, **kwargs):
        super(TCPKISSDevice, self).__init__(*args, **kwargs)
        self.address = (host, port)
        self._log.debug('Created')

    def _open(self):
        self._log.debug('Call open')
        self._interface = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._interface.connect(self.address)
        self._state = KISSDeviceState.OPEN
        self._loop.add_reader(self._interface, self._on_recv_ready)
        self._loop.call_soon(self._init_kiss)
        self._log.debug('Call open Done')

    def _on_recv_ready(self):
        self._log.debug('Called')
        try:
            read_data = self._interface.recv(self.READ_BYTES, timeout=30)
            self._receive(read_data)
        except:
            self._log.exception('Failed to read from serial device')

    def _send_raw_data(self, data):
        self._serial.write(data)

    def _close(self):
        self._loop.remove_reader(self._interface)
        socket.close(self._interface)
        self._interface = None
        self._state = KISSDeviceState.CLOSED
       
@sjlongland
Copy link
Owner

Okay, so KISS over TCP… that's not something I've tried, although in truth it's definitely something that should be implemented.

I'll have to look at how to achieve this. I don't think using socket directly is the answer, the aim of aioax25 is to use non-blocking I/O where possible and asyncio has native support for doing this with TCP connections, so it'd make better sense to use that.

That said, it should still be possible to use the synchronous socket library directly as you are doing. On Unix-like platforms, there'll be a method there to get the file handle (much like there is on the serial version), and that is what you'll want to pass to the IOLoop's add_reader method, so that it can notify the loop that something is waiting to be read.

In your test script, I note you don't seem to create any sort of IOLoop instance or try to launch any coroutines. I think for something asyncio based, you need to have an IOLoop running or else it will just fall though, doing nothing, which is indeed what you are seeing. aioax25 is an asynchronous library, and thus requires an IOLoop to run to perform its tasks.

This is what I have in my code:

# main.py

def main(): # pragma: no cover
    # Okay, this is for pulling settings from a command line and config file… adapt for your needs
    ap = argparse.ArgumentParser(description='aioax25 example')
    ap.add_argument('config', help='Path to configuration file')

    args = ap.parse_args()

    config = yaml.load(open(args.config, 'r'))

    # Event loop
    loop = asyncio.get_event_loop()

    # Set up logging
    logging.config.dictConfig(config.pop('logging'))
    log = logging.getLogger('rfidterm')

    log.info('Starting up')

    # Set up TNC interface
    kiss_port = config['kiss'].pop('port', 0)
    kiss = SerialKISSDevice( # in your case, TCPKISSDevice would be used.
            loop=loop, log=log.getChild('kiss'),
            **config['kiss']
    )
    kiss.open() # This starts the "open" process, which will continue when the IOLoop is started.

    # Set up AX.25 interface
    ax25int = AX25Interface(
            kissport=kiss[kiss_port],
            loop=loop, log=log.getChild('ax25'),
            **config.get('ax25', {})
    )

    # Set up APRS message handler
    aprs = APRSInterface(
            ax25int,
            log=log.getChild('aprs'),
            **config['aprs']
    )

    # Set up digipeating handler (optional)
    digi_enable = config.get('digi', {}).pop('enable', False)
    digi = APRSDigipeater(log=log.getChild('digi'),
            **config.get('digi', {}))
    if digi_enable:
        digi.connect(aprs)

    # Set up signal handlers
    def _shutdown():
        log.info('Shut-down signal received')
        # Do whatever you have to here to clean everything up!
        kiss.close()
        log.info('Waiting 5 seconds for final shut-down')
        loop.call_later(5, loop.stop)

    for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGQUIT):
        loop.add_signal_handler(sig, _shutdown)

    # Enter the event loop
    log.info('Entering event loop')
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        # Perform whatever shutdown steps needed here.
        pass

# in __main__.py
from .main import main

if __name__ == '__main__':
    main()

That loop.run_forever() is the key here… that starts an IOLoop instance to run continuously; if we get a KeyboardInterrupt exception; or we receive a suitable signal, we shut everything down (cleanly)… otherwise it just keeps on trucking.

@sjlongland
Copy link
Owner

Ohh, and the above, would use a configuration file that looks like this:

aprs:
        mycall: VK4MSL-1
        #aprs_path: []

kiss: # here, you would put the parameters used by TCPKISSInterface… in this case, it's a serial interface to a port on a PocketBeagle which connects to a KPC3
        device: /dev/ttyS4
        baudrate: 9600

# Logging settings
# See https://docs.python.org/3/library/logging.config.html#logging-config-dictschema
logging:
        version: 1
        formatters:
                detail:
                        format: '%(asctime)s %(name)s[%(filename)s:%(lineno)4d] %(levelname)s %(message)s'
        handlers:
                console:
                        formatter: detail
                        class: logging.StreamHandler
                        level: DEBUG
                        stream: ext://sys.stdout
        root:
                level: DEBUG
                handlers:
                        - console

@hemna
Copy link
Contributor Author

hemna commented May 10, 2021

Any chance you can do a formal release so I can use aioax25 from pypi with the new tcpkiss support?

@sjlongland
Copy link
Owner

I'll have to schedule some time to give it a shot at some point. The last few weeks have been a bit of a battle getting free time to work on these projects.

@sjlongland
Copy link
Owner

Release 0.0.10 includes these changes.

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