Python example: mrpt_comms_example.py
TCP client sockets and serial ports with mrpt.comms (no device needed).
Modules: mrpt.comms
1#!/usr/bin/env python3
2"""
3TCP client sockets and serial ports with mrpt.comms (no device needed).
4
5Demonstrates:
6 - CClientTCPSocket: construction, context manager, connection API
7 - CSerialPort: construction, setConfig, open/close lifecycle
8
9NOTE: This example does NOT open actual network connections or serial ports —
10it demonstrates the API at the Python level without hardware. Real usage
11would call sock.connect() / port.open() against live endpoints.
12"""
13
14from mrpt.comms import CClientTCPSocket, CSerialPort
15
16# ---------------------------------------------------------------------------
17# CClientTCPSocket — TCP client
18# ---------------------------------------------------------------------------
19sock = CClientTCPSocket()
20print(f"CClientTCPSocket created: {sock}")
21print(f" isConnected = {sock.isConnected()}")
22
23# Demonstrate context-manager support (no actual connection made here)
24with CClientTCPSocket() as s:
25 print(f" inside 'with': {s}")
26 # In real usage:
27 # s.connect("192.168.1.10", 9000, timeout_ms=3000)
28 # s.write(b"PING\r\n")
29 # response = s.read(64)
30 # s.close()
31print(" context manager exited cleanly ✓")
32
33# ---------------------------------------------------------------------------
34# CSerialPort — serial port
35# ---------------------------------------------------------------------------
36port = CSerialPort() # no port opened yet
37print(f"\nCSerialPort created: {port}")
38print(f" isOpen = {port.isOpen()}")
39
40# Configure before opening (in real usage you'd open a real device)
41port.setSerialPortName("/dev/ttyUSB0")
42# port.open() ← would raise if /dev/ttyUSB0 doesn't exist
43
44# Context manager (port already closed, just checks API)
45with CSerialPort() as p:
46 print(f" inside 'with' (no port opened): {p}")
47 # In real usage:
48 # p = CSerialPort("/dev/ttyUSB0", openNow=True)
49 # p.setConfig(baudRate=115200, parity=0, bits=8, nStopBits=1)
50 # p.setTimeouts(100, 0, 500, 0, 0)
51 # data = p.read(64)
52 # p.write(b"AT\r")
53print(" serial context manager exited cleanly ✓")
54
55print("""
56Typical real-world usage:
57
58 # TCP
59 from mrpt.comms import CClientTCPSocket
60 with CClientTCPSocket() as s:
61 s.connect("192.168.1.100", 5555, timeout_ms=5000)
62 s.write(b"HELLO")
63 resp = s.read(256)
64
65 # Serial
66 from mrpt.comms import CSerialPort
67 with CSerialPort("/dev/ttyUSB0") as p:
68 p.setConfig(baudRate=115200)
69 p.write(b"AT\\r")
70 reply = p.read(64)
71""")