def test_streaming(self): queue = ListQueue() kiss = KISSProtocol(0, queue) kiss.handle_bytes(b"\xc0\x00Hello,") assert len(queue) == 0 kiss.handle_bytes(b"") kiss.handle_bytes(b" KISS!\xc0") assert len(queue) == 1 assert queue.pop(0).data == b"Hello, KISS!"
def test_partial(self): queue = ListQueue() kiss = KISSProtocol(0, queue) kiss.handle_bytes( b"\xb4@\x04_\x96h\x88\x84\xb4@\x12CHAT \x96h\x88\x84\xb4@\x04_\xc0" ) assert len(queue) == 0 kiss.handle_bytes(b"\xc0\x00Hello, KISS!\xc0") assert len(queue) == 1 assert queue.pop(0).data == b"Hello, KISS!"
def main(): parser = argparse.ArgumentParser(description='Decode packets from a serial port') parser.add_argument("port", help="Serial port to open") parser.add_argument("baud", type=int, help="Baudrate to use") parser.add_argument("local_call", help="Your callsign (e.g., K4DBZ-10)") parser.add_argument("local_alias", help="Your alias (e.g., ZDBZ10)") parser.add_argument("remote_call", help="Remote callsign") parser.add_argument("-datalink", help="Force L2 mode", action="store_true") parser.add_argument("--check-crc", type=bool, default=False) parser.add_argument("--monitor-port", type=int) parser.add_argument("--debug", action="store_true") args = parser.parse_args() # Configure logging main_logger = logging.getLogger("root") main_logger.setLevel(logging.ERROR) if args.debug: main_logger.setLevel(logging.DEBUG) state_logger = logging.getLogger("ax25.state") state_logger.setLevel(logging.DEBUG) state_logger.addHandler(logging.StreamHandler(sys.stdout)) state_logger = logging.getLogger("netrom.state") state_logger.setLevel(logging.DEBUG) state_logger.addHandler(logging.StreamHandler(sys.stdout)) scheduler = Scheduler() # Configure and initialize I/O device and L2 port_config = PortConfig.from_dict(0, { "port.enabled": True, "port.type": "serial", "serial.device": args.port, "serial.speed": args.baud }) # Initialize I/O device and L2 l3_protocols = L3Protocols() l2_multi = DefaultLinkMultiplexer(L3PriorityQueue, scheduler) l2_queueing = L2FIFOQueue(20, AX25Protocol.maximum_frame_size()) l2 = AX25Protocol(port_config, port_config.port_id(), AX25Call.parse(args.local_call), scheduler, l2_queueing, l2_multi, l3_protocols) kiss = KISSProtocol(port_config.port_id(), l2_queueing, port_config.get_boolean("kiss.checksum", False)) SerialDevice(kiss, port_config.get("serial.device"), port_config.get_int("serial.speed"), port_config.get_float("serial.timeout"), scheduler) scheduler.submit(L2IOLoop(l2_queueing, l2)) # Initialize L3 and L4 network_config = NetworkConfig.from_dict({ "netrom.node.call": args.local_call, "netrom.node.alias": args.local_alias, "netrom.ttl": 7, "netrom.nodes.interval": 60, "netrom.obs.init": 6, "netrom.obs.min": 4, "netrom.nodes.quality.min": 74 }) # Register L3 protocols netrom_l3 = NetRomL3(AX25Call.parse(network_config.node_call()), network_config.node_alias(), scheduler, l2_multi, NetRomRoutingTable(network_config.node_alias())) l3_protocols.register(netrom_l3) # Create the L4 protocol netrom_l4 = NetRomTransportProtocol(network_config, netrom_l3, scheduler) async def wait_for_network(): tty = TTY() loop.add_reader(sys.stdin, tty.handle_stdin) loop.add_signal_handler(signal.SIGTERM, tty.handle_signal, loop, scheduler) loop.add_signal_handler(signal.SIGINT, tty.handle_signal, loop, scheduler) remote_call = AX25Call.parse(args.remote_call) while True: (found, mtu) = netrom_l3.route_packet(NetRomAddress.from_call(remote_call)) if found: break await asyncio.sleep(0.200) main_logger.info(f"Learned route to {remote_call}") await asyncio.sleep(1.200) netrom_l4.open(protocol_factory=lambda: tty, local_call=AX25Call.parse(args.local_call), remote_call=AX25Call.parse(args.remote_call), origin_user=AX25Call(args.local_alias), origin_node=AX25Call(args.local_call)) loop = asyncio.get_event_loop() loop.create_task(wait_for_network()) try: loop.run_forever() finally: loop.close()
def run_node(args): # Load settings from ini file s = Settings(".", args.config) node_settings = s.node_config() # Setup logging logging.config.fileConfig("config/logging.ini", disable_existing_loggers=False) # Create thread pool scheduler = Scheduler() # Initialize I/O devices and L2 protocols l3_protocols = L3Protocols() l2_multi = LinkMultiplexer(L3PriorityQueue, scheduler) for port_config in s.port_configs(): l2_queueing = L2FIFOQueue(20, AX25Protocol.maximum_frame_size()) l2 = AX25Protocol(port_config.port_id(), AX25Call.parse(node_settings.node_call()), scheduler, l2_queueing, l2_multi, l3_protocols) kiss = KISSProtocol(port_config.port_id(), l2_queueing, port_config.get_boolean("kiss.checksum", False)) SerialDevice(kiss, port_config.get("serial.device"), port_config.get_int("serial.speed"), scheduler) scheduler.submit(L2IOLoop(l2_queueing, l2)) # Register L3 protocols routing_table = tarpn.netrom.router.NetRomRoutingTable.load(f"nodes-{s.network_configs().node_call()}.json", s.network_configs().node_alias()) netrom_l3 = NetRomL3(AX25Call.parse(s.network_configs().node_call()), s.network_configs().node_alias(), scheduler, l2_multi, routing_table) l3_protocols.register(netrom_l3) l3_protocols.register(NoLayer3Protocol()) # Create the L4 protocol netrom_l4 = NetRomTransportProtocol(s.network_configs(), netrom_l3, scheduler) # Bind the command processor ncp_factory = partial(NodeCommandProcessor, config=s.network_configs(), l2s=l2_multi, l3=netrom_l3, l4=netrom_l4, scheduler=scheduler) netrom_l4.bind_server(AX25Call.parse(s.network_configs().node_call()), s.network_configs().node_alias(), ncp_factory) # Set up applications for app_config in s.app_configs(): # We have a single unix socket connection multiplexed to many network connections app_multiplexer = TransportMultiplexer() app_protocol = ApplicationProtocol(app_config.app_name(), AX25Call.parse(app_config.app_call()), app_config.app_alias(), netrom_l4, app_multiplexer) scheduler.submit(UnixServerThread(app_config.app_socket(), app_protocol)) multiplexer_protocol = partial(MultiplexingProtocol, app_multiplexer) netrom_l4.bind_server(AX25Call.parse(app_config.app_call()), app_config.app_alias(), multiplexer_protocol) # Start a metrics reporter reporter = ConsoleReporter(reporting_interval=300) reporter.start() scheduler.add_shutdown_hook(reporter.stop) logger.info("Finished Startup") try: # Wait for all threads scheduler.join() except KeyboardInterrupt: scheduler.shutdown()
def run_node(args): # Bootstrap node.ini if not os.path.exists(args.config) and os.path.basename( args.config) == "node.ini": shutil.copyfile("config/node.ini.sample", args.config) # Load settings from ini file s = Settings(".", ["config/defaults.ini", args.config]) node_settings = s.node_config() node_call = AX25Call.parse(node_settings.node_call()) if node_call.callsign == "N0CALL": print("Callsign is missing from config. Please see instructions here " "https://github.com/tarpn/tarpn-node-controller") sys.exit(1) else: print(f"Loaded configuration for {node_call}") # Setup logging logging_config_file = node_settings.get("log.config", "not_set") if logging_config_file != "not_set": log_dir = node_settings.get("log.dir") if not os.path.exists(log_dir): os.makedirs(log_dir) logging.config.fileConfig(logging_config_file, defaults={"log.dir": log_dir}, disable_existing_loggers=False) if args.verbose: logging.getLogger("root").setLevel(logging.DEBUG) # Create thread pool scheduler = Scheduler() # Initialize I/O devices and L2 protocols l3_protocols = L3Protocols() l3_protocols.register(NoLayer3Protocol()) l2_multi = DefaultLinkMultiplexer(L3PriorityQueue, scheduler) # Port UDP mapping # udp.forwarding.enabled = true # udp.address = 192.168.0.160:10093 # udp.destinations = K4DBZ-2,NODES # udp.mapping = KN4ORB-2:1,KA2DEW-2:2 port_queues = {} if node_settings.get_boolean("udp.enabled", False): udp_host, udp_port = node_settings.get("udp.address").split(":") udp_port = int(udp_port) udp_writer = UDPWriter(g8bpq_address=(udp_host, udp_port)) intercept_dests = { AX25Call.parse(c) for c in node_settings.get("udp.destinations", "").split(",") } interceptor = udp_writer.receive_frame udp_mapping = {} for mapping in node_settings.get("udp.mapping", "").split(","): c, i = mapping.split(":") udp_mapping[AX25Call.parse(c)] = int(i) scheduler.submit( UDPThread("0.0.0.0", udp_port, udp_mapping, port_queues, udp_writer)) else: intercept_dests = {} interceptor = lambda frame: None for port_config in s.port_configs(): if port_config.get_boolean("port.enabled") and port_config.get( "port.type") == "serial": l2_queueing = L2FIFOQueue(20, AX25Protocol.maximum_frame_size()) port_queues[port_config.port_id()] = l2_queueing l2 = AX25Protocol(port_config, port_config.port_id(), node_call, scheduler, l2_queueing, l2_multi, l3_protocols, intercept_dests, interceptor) kiss = KISSProtocol( port_config.port_id(), l2_queueing, port_config.get_boolean("kiss.checksum", False)) SerialDevice(kiss, port_config.get("serial.device"), port_config.get_int("serial.speed"), port_config.get_float("serial.timeout"), scheduler) scheduler.submit(L2IOLoop(l2_queueing, l2)) # Register L3 protocols routing_table = tarpn.netrom.router.NetRomRoutingTable.load( f"nodes-{node_settings.node_call()}.json", node_settings.node_alias()) network_configs = s.network_configs() if network_configs.get_boolean("netrom.enabled", False): logger.info("Starting NET/ROM router") netrom_l3 = NetRomL3(node_call, node_settings.node_alias(), scheduler, l2_multi, routing_table) l3_protocols.register(netrom_l3) netrom_l4 = NetRomTransportProtocol(s.network_configs(), netrom_l3, scheduler) l4_handlers = L4Handlers() if network_configs.get_boolean("mesh.enabled", False): mesh_l3 = MeshProtocol(WallTime(), network_configs, l2_multi, l4_handlers, scheduler) l3_protocols.register(mesh_l3) # Create the L4 protocols mesh_l4 = MeshTransportManager(mesh_l3) # Register L4 handlers reliable = ReliableManager(mesh_l3, scheduler) fragment_protocol = FragmentProtocol(mesh_l3, mesh_l4) reliable_protocol = ReliableProtocol(mesh_l3, reliable, l4_handlers) datagram_protocol = DatagramProtocol(mesh_l3, mesh_l4, fragment_protocol, reliable_protocol) broadcast_protocol = BroadcastProtocol(mesh_l3, mesh_l4, reliable) l4_handlers.register_l4(Protocol.FRAGMENT, fragment_protocol) l4_handlers.register_l4(Protocol.RELIABLE, reliable_protocol) l4_handlers.register_l4(Protocol.DATAGRAM, datagram_protocol) l4_handlers.register_l4(Protocol.BROADCAST, broadcast_protocol) # TODO fix circular dependency here mesh_l4.broadcast_protocol = broadcast_protocol mesh_l4.datagram_protocol = datagram_protocol # Bind the command processor ncp_factory = partial(NodeCommandProcessor, config=network_configs, link=l2_multi, network=mesh_l3, transport_manager=mesh_l4, scheduler=scheduler) mesh_l4.bind(ncp_factory, mesh_l3.our_address, 11) # Set up applications for app_config in s.app_configs(): # We have a single unix socket connection multiplexed to many network connections print(app_config) app_multiplexer = TransportMultiplexer() app_address = MeshTransportAddress.parse( app_config.get("app.address")) app_protocol = ApplicationProtocol(app_config.app_name(), app_config.app_alias(), str(app_address.address), mesh_l4, app_multiplexer) scheduler.submit( UnixServerThread(app_config.app_socket(), app_protocol)) multiplexer_protocol = partial(MultiplexingProtocol, app_multiplexer) # TODO bind or connect? mesh_l4.connect(multiplexer_protocol, app_address.address, MeshAddress.parse("00.a2"), app_address.port) sock = node_settings.get("node.sock") print(f"Binding node terminal to {sock}") scheduler.submit( UnixServerThread(sock, TarpnShellProtocol(mesh_l3, mesh_l4))) # Start a metrics reporter #reporter = ConsoleReporter(reporting_interval=300) #scheduler.timer(10_000, reporter.start, True) #scheduler.add_shutdown_hook(reporter.stop) logger.info("Finished Startup") try: # Wait for all threads scheduler.join() except KeyboardInterrupt: scheduler.shutdown()
def main(): parser = argparse.ArgumentParser( description='Broadcast to mesh network over serial device') parser.add_argument("device", help="Serial port to open") parser.add_argument("baud", type=int, help="Baudrate to use") parser.add_argument("callsign", help="Your callsign (e.g., K4DBZ-10)") parser.add_argument("address", help="Local address, e.g., 00.1a") parser.add_argument("port", type=int, help="Port", default=10) parser.add_argument("--debug", action="store_true") args = parser.parse_args() # Configure logging main_logger = logging.getLogger("root") main_logger.setLevel(logging.ERROR) main_logger.addHandler(logging.StreamHandler(sys.stdout)) if args.debug: main_logger.setLevel(logging.DEBUG) state_logger = logging.getLogger("ax25.state") state_logger.setLevel(logging.DEBUG) state_logger.addHandler(logging.StreamHandler(sys.stdout)) scheduler = Scheduler() # Configure and initialize I/O device and L2 port_config = PortConfig.from_dict( 0, { "port.enabled": True, "port.type": "serial", "serial.device": args.device, "serial.speed": args.baud }) # Initialize I/O device and L2 l3_protocols = L3Protocols() l2_multi = DefaultLinkMultiplexer(L3PriorityQueue, scheduler) l2_queueing = L2FIFOQueue(20, AX25Protocol.maximum_frame_size()) l2 = AX25Protocol(port_config, port_config.port_id(), AX25Call.parse(args.callsign), scheduler, l2_queueing, l2_multi, l3_protocols) kiss = KISSProtocol(port_config.port_id(), l2_queueing, port_config.get_boolean("kiss.checksum", False)) SerialDevice(kiss, port_config.get("serial.device"), port_config.get_int("serial.speed"), port_config.get_float("serial.timeout"), scheduler) scheduler.submit(L2IOLoop(l2_queueing, l2)) addr = MeshAddress.parse(args.address) mesh_l3 = MeshProtocol(our_address=addr, link_multiplexer=l2_multi, scheduler=scheduler) l3_protocols.register(mesh_l3) mesh_l4 = MeshTransportManager(mesh_l3) tty = TTY() loop = asyncio.get_event_loop() loop.add_reader(sys.stdin, tty.handle_stdin) loop.add_signal_handler(signal.SIGTERM, tty.handle_signal, loop, scheduler) loop.add_signal_handler(signal.SIGINT, tty.handle_signal, loop, scheduler) mesh_l4.connect(protocol_factory=lambda: tty, port=args.port, local_address=addr, remote_address=MeshProtocol.BroadcastAddress) try: loop.run_forever() finally: loop.close()