kiss
KISS framing for TNCs over serial and TCP.
KISS is how
software talks to a TNC: each AX.25 frame is wrapped in FEND (0xC0)
bytes after a one-byte command, with FEND and FESC bytes inside escaped.
This package frames and unframes that stream, and sends TNC parameters such
as TX delay and persistence.
Connecting
TCPKISS and SerialKISS block; read() returns AX.25 bytes and
write() returns once the frame has gone out:
from ax253 import Frame
import kiss
tnc = kiss.TCPKISS("localhost", 8001, strip_df_start=True)
tnc.start(TX_DELAY=40)
try:
tnc.write(Frame.from_str("N0CALL>APRS,WIDE1-1:>on the air"))
for raw in tnc.read(min_frames=1):
print(Frame.from_bytes(raw))
finally:
tnc.stop()
create_tcp_connection and create_serial_connection return an asyncio
KISSProtocol whose read() yields decoded ax253.Frame objects:
transport, protocol = await kiss.create_tcp_connection("localhost", 8001)
async for frame in protocol.read():
print(frame)
Decoding a stream
The decoders take bytes as they arrive and return complete frames.
AX25KISSDecode returns ax253.Frame objects and KISSDecode returns
the unescaped bytes. Both skip frames that aren't data, like TNC parameter
echoes:
>>> from ax253 import Frame
>>> import kiss
>>> stream = b"\xc0\x00" + bytes(Frame.from_str("N0CALL>APRS:>hi")) + b"\xc0"
>>> decoder = kiss.AX25KISSDecode()
>>> list(decoder.update(stream[:10])) # half a frame: nothing yet
[]
>>> [str(f) for f in decoder.update(stream[10:] + b"\xc0\x01\x28\xc0")]
['N0CALL>APRS:>hi']
>>> list(kiss.KISSDecode().update(b"\xc0\x00a\xdb\xdcb\xc0"))
[b'a\xc0b']
Pass strip_df_start=False to keep the command byte and every frame.
Based on the original kiss module by Greg Albrecht W2GMD
(https://github.com/ampledata/kiss), Apache License 2.0.
1r"""KISS framing for TNCs over serial and TCP. 2 3`KISS <https://en.wikipedia.org/wiki/KISS_(amateur_radio_protocol)>`_ is how 4software talks to a TNC: each AX.25 frame is wrapped in FEND (``0xC0``) 5bytes after a one-byte command, with FEND and FESC bytes inside escaped. 6This package frames and unframes that stream, and sends TNC parameters such 7as TX delay and persistence. 8 9Connecting 10========== 11 12``TCPKISS`` and ``SerialKISS`` block; ``read()`` returns AX.25 bytes and 13``write()`` returns once the frame has gone out: 14 15.. code-block:: python 16 17 from ax253 import Frame 18 19 import kiss 20 21 tnc = kiss.TCPKISS("localhost", 8001, strip_df_start=True) 22 tnc.start(TX_DELAY=40) 23 try: 24 tnc.write(Frame.from_str("N0CALL>APRS,WIDE1-1:>on the air")) 25 for raw in tnc.read(min_frames=1): 26 print(Frame.from_bytes(raw)) 27 finally: 28 tnc.stop() 29 30``create_tcp_connection`` and ``create_serial_connection`` return an asyncio 31``KISSProtocol`` whose ``read()`` yields decoded ``ax253.Frame`` objects: 32 33.. code-block:: python 34 35 transport, protocol = await kiss.create_tcp_connection("localhost", 8001) 36 async for frame in protocol.read(): 37 print(frame) 38 39Decoding a stream 40================= 41 42The decoders take bytes as they arrive and return complete frames. 43``AX25KISSDecode`` returns ``ax253.Frame`` objects and ``KISSDecode`` returns 44the unescaped bytes. Both skip frames that aren't data, like TNC parameter 45echoes: 46 47>>> from ax253 import Frame 48>>> import kiss 49>>> stream = b"\xc0\x00" + bytes(Frame.from_str("N0CALL>APRS:>hi")) + b"\xc0" 50>>> decoder = kiss.AX25KISSDecode() 51>>> list(decoder.update(stream[:10])) # half a frame: nothing yet 52[] 53>>> [str(f) for f in decoder.update(stream[10:] + b"\xc0\x01\x28\xc0")] 54['N0CALL>APRS:>hi'] 55>>> list(kiss.KISSDecode().update(b"\xc0\x00a\xdb\xdcb\xc0")) 56[b'a\xc0b'] 57 58Pass ``strip_df_start=False`` to keep the command byte and every frame. 59 60Based on the original ``kiss`` module by Greg Albrecht W2GMD 61(https://github.com/ampledata/kiss), Apache License 2.0. 62""" 63 64import logging 65from importlib.metadata import version 66 67from .classes import TCPKISS, SerialKISS 68from .kiss import ( 69 AX25KISSDecode, 70 Command, 71 KISSDecode, 72 KISSProtocol, 73 create_serial_connection, 74 create_tcp_connection, 75) 76 77__author__ = "Greg Albrecht W2GMD <oss@undef.net>" 78__copyright__ = "Copyright 2017 Greg Albrecht and Contributors" 79__license__ = "Apache License, Version 2.0" 80__distribution__ = "kiss3" 81__version__ = version(__distribution__) 82 83# library logging etiquette: never print unless the application configures it 84logging.getLogger(__name__).addHandler(logging.NullHandler()) 85__all__ = [ 86 "AX25KISSDecode", 87 "create_serial_connection", 88 "create_tcp_connection", 89 "Command", 90 "KISSDecode", 91 "KISSProtocol", 92 "SerialKISS", 93 "TCPKISS", 94]
152class AX25KISSDecode(GenericKISSDecode[Frame]): 153 """ 154 Stateful AX25 framing decoder. 155 156 Decoded frames are `ax253.Frame` objects 157 """ 158 159 def decode_frames(self, frame: bytes) -> Iterable[Frame]: 160 for kiss_frame in self._deframe(frame): 161 try: 162 yield Frame.from_bytes(kiss_frame) 163 except Exception: # pylint: disable=broad-except 164 log.debug("Ignore frame AX.25 decode error %r", frame, exc_info=True)
Stateful AX25 framing decoder.
Decoded frames are ax253.Frame objects
159 def decode_frames(self, frame: bytes) -> Iterable[Frame]: 160 for kiss_frame in self._deframe(frame): 161 try: 162 yield Frame.from_bytes(kiss_frame) 163 except Exception: # pylint: disable=broad-except 164 log.debug("Ignore frame AX.25 decode error %r", frame, exc_info=True)
Decode a single deframed byte chunk.
Parameters
- frame: should represent a single higher level frame to decode in some way.
288async def create_serial_connection( # pylint: disable=too-many-arguments 289 port: str, 290 baudrate: int, 291 protocol_kwargs: dict[str, Any] | None = None, 292 loop: asyncio.AbstractEventLoop | None = None, 293 create_connection_kwargs: dict[str, Any] | None = None, 294 kiss_settings: Mapping[Command, bytes | int] | None = None, 295) -> tuple[asyncio.Transport, KISSProtocol]: 296 """ 297 Establish an async Serial KISS connection. 298 299 :param port: the serial port device (platform dependent) 300 :param baudrate: serial port speed 301 :param protocol_kwargs: These kwargs are passed directly to KISSProtocol 302 :param loop: override the asyncio event loop (default: the running loop) 303 :param create_connection_kwargs: These kwargs are passed directly to 304 loop.create_connection 305 :param kiss_settings: dictionary of (Command, bytes) pairs to send after connecting 306 :return: (SerialTransport, KISSProtocol) 307 """ 308 if loop is None: 309 loop = asyncio.get_running_loop() 310 kwargs = _handle_kwargs( 311 protocol_kwargs=protocol_kwargs, 312 create_connection_kwargs=create_connection_kwargs, 313 baudrate=baudrate, 314 ) 315 return await _generic_create_connection( 316 serial_asyncio.create_serial_connection, 317 args=(loop, kwargs.pop("protocol_factory"), port), 318 kwargs=kwargs, 319 kiss_settings=kiss_settings, 320 )
Establish an async Serial KISS connection.
Parameters
- port: the serial port device (platform dependent)
- baudrate: serial port speed
- protocol_kwargs: These kwargs are passed directly to KISSProtocol
- loop: override the asyncio event loop (default: the running loop)
- create_connection_kwargs: These kwargs are passed directly to loop.create_connection
- kiss_settings: dictionary of (Command, bytes) pairs to send after connecting
Returns
(SerialTransport, KISSProtocol)
253async def create_tcp_connection( # pylint: disable=too-many-arguments 254 host, 255 port, 256 protocol_kwargs: dict[str, Any] | None = None, 257 loop: asyncio.AbstractEventLoop | None = None, 258 create_connection_kwargs: dict[str, Any] | None = None, 259 kiss_settings: Mapping[Command, bytes | int] | None = None, 260) -> tuple[asyncio.Transport, KISSProtocol]: 261 """ 262 Establish an async KISS-over-TCP connection. 263 264 :param host: the host to connect to 265 :param port: the TCP port to connect to 266 :param protocol_kwargs: These kwargs are passed directly to KISSProtocol 267 :param loop: override the asyncio event loop (default: the running loop) 268 :param create_connection_kwargs: These kwargs are passed directly to 269 loop.create_connection 270 :param kiss_settings: dictionary of (Command, bytes) pairs to send after connecting 271 :return: (TCPTransport, KISSProtocol) 272 """ 273 if loop is None: 274 loop = asyncio.get_running_loop() 275 return await _generic_create_connection( 276 loop.create_connection, 277 args=tuple(), 278 kwargs=_handle_kwargs( 279 protocol_kwargs=protocol_kwargs, 280 create_connection_kwargs=create_connection_kwargs, 281 host=host, 282 port=port, 283 ), 284 kiss_settings=kiss_settings, 285 )
Establish an async KISS-over-TCP connection.
Parameters
- host: the host to connect to
- port: the TCP port to connect to
- protocol_kwargs: These kwargs are passed directly to KISSProtocol
- loop: override the asyncio event loop (default: the running loop)
- create_connection_kwargs: These kwargs are passed directly to loop.create_connection
- kiss_settings: dictionary of (Command, bytes) pairs to send after connecting
Returns
(TCPTransport, KISSProtocol)
37class Command(enum.Enum): 38 """ 39 KISS Command Codes 40 41 http://en.wikipedia.org/wiki/KISS_(TNC)#Command_Codes 42 """ 43 44 DATA_FRAME = b"\x00" 45 TX_DELAY = b"\x01" 46 PERSISTENCE = b"\x02" 47 SLOT_TIME = b"\x03" 48 TX_TAIL = b"\x04" 49 FULL_DUPLEX = b"\x05" 50 SET_HARDWARE = b"\x06" 51 RETURN = b"\xff"
KISS Command Codes
144class KISSDecode(GenericKISSDecode[bytes]): 145 """ 146 Stateful KISS framing decoder. 147 148 Frames are returned as bytes (with KISS framing removed). 149 """
Stateful KISS framing decoder.
Frames are returned as bytes (with KISS framing removed).
167@define 168class KISSProtocol(FrameDecodeProtocol[Frame]): 169 """A protocol for encoding and decoding KISS frames.""" 170 171 decoder: GenericDecoder[Frame] = field(factory=AX25KISSDecode) 172 173 def _transport(self) -> asyncio.Transport: 174 if self.transport is None: 175 raise ConnectionError("not connected: the transport isn't open yet") 176 return self.transport 177 178 def write( 179 self, frame: SupportsBytes | bytes, command: Command = Command.DATA_FRAME 180 ) -> None: 181 """ 182 Write the framed bytes to the transport. 183 184 :param frame: any bytes-able object that can be sent via KISS 185 :param command: kiss Command to send with the frame, default is 0x00 (DATA) 186 """ 187 frame_escaped = util.escape_special_codes(bytes(frame)) 188 frame_kiss = b"".join([FEND, command.value, frame_escaped, FEND]) 189 self._transport().write(frame_kiss) 190 191 def write_setting(self, name: Command, value: bytes | int) -> None: 192 """ 193 Writes KISS Command Codes to attached device. 194 195 http://en.wikipedia.org/wiki/KISS_(TNC)#Command_Codes 196 197 :param name: KISS Command Code enum 198 :param value: KISS Command Code Value to write. 199 """ 200 # Do the reasonable thing if a user passes an int 201 if isinstance(value, int): 202 value = bytes([value]) 203 204 # write() escapes FEND/FESC; escaping here too would double-escape 205 self.write(value, command=name) 206 207 def write_settings(self, settings: Mapping[Command, bytes | int]) -> None: 208 """Write a dictionary of settings.""" 209 for name, value in settings.items(): 210 self.write_setting(name, value) 211 212 def kiss_on(self) -> None: 213 """Turns KISS ON.""" 214 self._transport().write(KISS_ON) 215 216 def kiss_off(self) -> None: 217 """Turns KISS OFF.""" 218 self._transport().write(KISS_OFF)
A protocol for encoding and decoding KISS frames.
28def __init__(self, transport=attr_dict['transport'].default, decoder=NOTHING, *, max_queued_frames=attr_dict['max_queued_frames'].default): 29 self.transport = transport 30 self.frames = __attr_factory_frames() 31 self.connection_future = __attr_factory_connection_future() 32 self.max_queued_frames = max_queued_frames 33 self.dropped_frames = attr_dict['dropped_frames'].default 34 if decoder is not NOTHING: 35 self.decoder = decoder 36 else: 37 self.decoder = __attr_factory_decoder()
Method generated by attrs for class KISSProtocol.
178 def write( 179 self, frame: SupportsBytes | bytes, command: Command = Command.DATA_FRAME 180 ) -> None: 181 """ 182 Write the framed bytes to the transport. 183 184 :param frame: any bytes-able object that can be sent via KISS 185 :param command: kiss Command to send with the frame, default is 0x00 (DATA) 186 """ 187 frame_escaped = util.escape_special_codes(bytes(frame)) 188 frame_kiss = b"".join([FEND, command.value, frame_escaped, FEND]) 189 self._transport().write(frame_kiss)
Write the framed bytes to the transport.
Parameters
- frame: any bytes-able object that can be sent via KISS
- command: kiss Command to send with the frame, default is 0x00 (DATA)
191 def write_setting(self, name: Command, value: bytes | int) -> None: 192 """ 193 Writes KISS Command Codes to attached device. 194 195 http://en.wikipedia.org/wiki/KISS_(TNC)#Command_Codes 196 197 :param name: KISS Command Code enum 198 :param value: KISS Command Code Value to write. 199 """ 200 # Do the reasonable thing if a user passes an int 201 if isinstance(value, int): 202 value = bytes([value]) 203 204 # write() escapes FEND/FESC; escaping here too would double-escape 205 self.write(value, command=name)
Writes KISS Command Codes to attached device.
http://en.wikipedia.org/wiki/KISS_(TNC)#Command_Codes
Parameters
- name: KISS Command Code enum
- value: KISS Command Code Value to write.
207 def write_settings(self, settings: Mapping[Command, bytes | int]) -> None: 208 """Write a dictionary of settings.""" 209 for name, value in settings.items(): 210 self.write_setting(name, value)
Write a dictionary of settings.
145class SerialKISS(KISS): 146 """KISS Serial Class.""" 147 148 def __init__(self, port: str, speed: str, strip_df_start: bool = False) -> None: 149 self.port = port 150 self.speed = speed 151 super().__init__(strip_df_start) 152 153 def config_xastir(self) -> None: 154 """ 155 Helper method to set default configuration to those that ship with 156 Xastir. 157 """ 158 self._write_defaults(**constants.DEFAULT_KISS_CONFIG_VALUES) 159 160 def kiss_on(self) -> None: 161 """Turns KISS ON.""" 162 self.kiss_protocol.kiss_on() 163 self._drain() 164 165 def kiss_off(self) -> None: 166 """Turns KISS OFF.""" 167 self.kiss_protocol.kiss_off() 168 self._drain() 169 170 def stop(self) -> None: 171 self._close_transport() 172 173 def start_no_config(self) -> None: 174 """ 175 Initializes the KISS device without writing configuration. 176 """ 177 _, self.protocol = self.loop.run_until_complete( 178 kiss.create_serial_connection( 179 port=self.port, 180 baudrate=int(self.speed), 181 protocol_kwargs={"decoder": self.decoder}, 182 ), 183 ) 184 self.loop.run_until_complete(self.protocol.connection_future) 185 186 def start(self, **kwargs: Any) -> None: 187 """ 188 Initializes the KISS device and commits configuration. 189 190 See http://en.wikipedia.org/wiki/KISS_(TNC)#Command_codes 191 for configuration names. 192 193 :param **kwargs: name/value pairs to use as initial config values. 194 """ 195 self._logger.debug("kwargs=%s", kwargs) 196 self.start_no_config() 197 self._write_defaults(**kwargs)
KISS Serial Class.
148 def __init__(self, port: str, speed: str, strip_df_start: bool = False) -> None: 149 self.port = port 150 self.speed = speed 151 super().__init__(strip_df_start)
Method generated by attrs for class SyncFrameDecode.
153 def config_xastir(self) -> None: 154 """ 155 Helper method to set default configuration to those that ship with 156 Xastir. 157 """ 158 self._write_defaults(**constants.DEFAULT_KISS_CONFIG_VALUES)
Helper method to set default configuration to those that ship with Xastir.
160 def kiss_on(self) -> None: 161 """Turns KISS ON.""" 162 self.kiss_protocol.kiss_on() 163 self._drain()
Turns KISS ON.
165 def kiss_off(self) -> None: 166 """Turns KISS OFF.""" 167 self.kiss_protocol.kiss_off() 168 self._drain()
Turns KISS OFF.
173 def start_no_config(self) -> None: 174 """ 175 Initializes the KISS device without writing configuration. 176 """ 177 _, self.protocol = self.loop.run_until_complete( 178 kiss.create_serial_connection( 179 port=self.port, 180 baudrate=int(self.speed), 181 protocol_kwargs={"decoder": self.decoder}, 182 ), 183 ) 184 self.loop.run_until_complete(self.protocol.connection_future)
Initializes the KISS device without writing configuration.
186 def start(self, **kwargs: Any) -> None: 187 """ 188 Initializes the KISS device and commits configuration. 189 190 See http://en.wikipedia.org/wiki/KISS_(TNC)#Command_codes 191 for configuration names. 192 193 :param **kwargs: name/value pairs to use as initial config values. 194 """ 195 self._logger.debug("kwargs=%s", kwargs) 196 self.start_no_config() 197 self._write_defaults(**kwargs)
Initializes the KISS device and commits configuration.
See http://en.wikipedia.org/wiki/KISS_(TNC)#Command_codes for configuration names.
Parameters
- **kwargs: name/value pairs to use as initial config values.
121class TCPKISS(KISS): 122 """KISS TCP Class.""" 123 124 def __init__(self, host: str, port: int, strip_df_start: bool = False): 125 super().__init__(strip_df_start) 126 self.address = (host, int(port)) 127 128 def stop(self) -> None: 129 self._close_transport() 130 131 def start(self, **kwargs: Any) -> None: 132 """ 133 Initializes the KISS device and commits configuration. 134 """ 135 _, self.protocol = self.loop.run_until_complete( 136 kiss.create_tcp_connection( 137 *self.address, 138 protocol_kwargs={"decoder": self.decoder}, 139 ), 140 ) 141 self.loop.run_until_complete(self.protocol.connection_future) 142 self._write_defaults(**kwargs)
KISS TCP Class.
124 def __init__(self, host: str, port: int, strip_df_start: bool = False): 125 super().__init__(strip_df_start) 126 self.address = (host, int(port))
Method generated by attrs for class SyncFrameDecode.
131 def start(self, **kwargs: Any) -> None: 132 """ 133 Initializes the KISS device and commits configuration. 134 """ 135 _, self.protocol = self.loop.run_until_complete( 136 kiss.create_tcp_connection( 137 *self.address, 138 protocol_kwargs={"decoder": self.decoder}, 139 ), 140 ) 141 self.loop.run_until_complete(self.protocol.connection_future) 142 self._write_defaults(**kwargs)
Initializes the KISS device and commits configuration.