### Development Setup: Install and Run Examples Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Set up the development environment by creating a virtual environment, activating it, installing the library in development mode, and running example scripts. Adjust the serial port path as needed. ```bash # Create and activate virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install in development mode pip install -e . # Run examples python examples/pubsub_example.py -p /dev/ttyUSB0 ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/meshcore-dev/meshcore_py/blob/main/tests/README.md Install necessary development dependencies for running tests. This command ensures all required packages, including testing frameworks, are available. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Install MeshCore with pip Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Install the MeshCore Python library using pip. This command should be run in your terminal. ```bash pip install meshcore ``` -------------------------------- ### Initiate Path Discovery Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_path_discovery` to start the path discovery process towards a specific contact. The destination is required. ```python send_path_discovery(dst) ``` -------------------------------- ### Hybrid MeshCore Operations with Asyncio Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md This example demonstrates a hybrid approach using both commands and events within an asyncio application. It connects to a device, sets up event handlers for acknowledgments and battery status, and runs a background task to periodically check battery levels. ```python import asyncio async def main(): # Connect to device meshcore = await MeshCore.create_serial("/dev/ttyUSB0") # Set up event handlers async def handle_ack(event): print("Message acknowledged!") async def handle_battery(event): print(f"Battery level: {event.payload}%") # Subscribe to events meshcore.subscribe(EventType.ACK, handle_ack) meshcore.subscribe(EventType.BATTERY, handle_battery) # Create background task for battery checking async def check_battery_periodically(): while True: # Send command (returns battery level) result = await meshcore.commands.get_bat() if result.type == EventType.ERROR: print(f"Error checking battery: {result.payload}") else: print(f"Battery level: {result.payload.get('level', 'unknown')}%) await asyncio.sleep(60) # Wait 60 seconds between checks # Start the background task battery_task = asyncio.create_task(check_battery_periodically()) # Send manual command and wait for response await meshcore.commands.send_advert(flood=True) try: # Keep the main program running await asyncio.sleep(float('inf')) except asyncio.CancelledError: # Clean up when program ends battery_task.cancel() await meshcore.disconnect() # Run the program asyncio.run(main()) ``` -------------------------------- ### Quick Start: Connect and Send Message Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Connect to a MeshCore device via serial port, retrieve contacts, and send a message to the first contact. Ensure the correct serial port is specified. ```python import asyncio from meshcore import MeshCore, EventType async def main(): # Connect to your device meshcore = await MeshCore.create_serial("/dev/ttyUSB0") # Get your contacts result = await meshcore.commands.get_contacts() if result.type == EventType.ERROR: print(f"Error getting contacts: {result.payload}") return contacts = result.payload print(f"Found {len(contacts)} contacts") # Send a message to the first contact if contacts: # Get the first contact contact = next(iter(contacts.items()))[1] # Pass the contact object directly to send_msg result = await meshcore.commands.send_msg(contact, "Hello from Python!") if result.type == EventType.ERROR: print(f"Error sending message: {result.payload}") else: print("Message sent successfully!") await meshcore.disconnect() asyncio.run(main()) ``` -------------------------------- ### Get Device Information Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Send a query to retrieve information about the connected device, such as its model. ```python result = await meshcore.commands.send_device_query() if result.type == EventType.ERROR: print(f"Error getting device info: {result.payload}") else: print(f"Device model: {result.payload['model']}") ``` -------------------------------- ### Channel Management Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands for managing communication channels on the device, including getting and setting channel configurations. ```APIDOC ## get_channel(channel_idx) ### Description Get the configuration for a specific channel. ### Method `get_channel(channel_idx)` ### Parameters #### Path Parameters - **channel_idx** (int) - Required - The index of the channel to retrieve. ``` ```APIDOC ## set_channel(channel_idx, name, secret) ### Description Configure a specific channel with a name and secret. ### Method `set_channel(channel_idx, name, secret)` ### Parameters #### Path Parameters - **channel_idx** (int) - Required - The index of the channel to configure. - **name** (str) - Required - The name of the channel. - **secret** (bytes) - Required - The channel secret (must be 16 bytes). ``` -------------------------------- ### Get List of Contacts Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Retrieve a list of contacts from the device. The result is a dictionary where keys are contact IDs and values are contact details. ```python result = await meshcore.commands.get_contacts() if result.type == EventType.ERROR: print(f"Error getting contacts: {result.payload}") else: contacts = result.payload for contact_id, contact in contacts.items(): print(f"Contact: {contact['adv_name']} ({contact_id})") ``` -------------------------------- ### Request Status via Binary Protocol Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `req_status` to get detailed status information from a contact using the binary protocol. A timeout can be specified. ```python req_status(contact, timeout=0) ``` -------------------------------- ### Request Historical Telemetry Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `req_mma` to fetch historical telemetry data for a given time range from a contact using the binary protocol. Requires contact details, start and end times, and an optional timeout. ```python req_mma(contact, start, end, timeout=0) ``` -------------------------------- ### Begin Signing Session Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `sign_start` to initiate a signing session. This command returns the maximum buffer size available for the data to be signed. ```python sign_start() ``` -------------------------------- ### Subscribe to Connection Events Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Set up callback functions to handle device connection and disconnection events. These events provide details about the connection status and reasons for disconnection. ```python async def on_connected(event): print(f"Connected: {event.payload}") if event.payload.get('reconnected'): print("Successfully reconnected!") async def on_disconnected(event): print(f"Disconnected: {event.payload['reason']}") if event.payload.get('max_attempts_exceeded'): print("Max reconnection attempts exceeded") meshcore.subscribe(EventType.CONNECTED, on_connected) meshcore.subscribe(EventType.DISCONNECTED, on_disconnected) ``` -------------------------------- ### Connect via Serial Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Establish a connection to a device using a serial port. Debugging can be enabled. ```python meshcore = await MeshCore.create_serial("/dev/ttyUSB0", 115200, debug=True) ``` -------------------------------- ### Available Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md All commands are async methods that return `Event` objects. Commands are organized into functional groups. ```APIDOC ## Available Commands All commands are async methods that return `Event` objects. Commands are organized into functional groups: ``` -------------------------------- ### Advanced Configuration Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands for advanced or experimental device configurations. ```APIDOC ## set_multi_acks(multi_acks) ### Description Set multi-acks mode, which is an experimental feature for ack repeats. ### Method `set_multi_acks(multi_acks)` ### Parameters #### Path Parameters - **multi_acks** (int) - Required - The multi-acks setting. ``` -------------------------------- ### Connect via TCP Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Establish a connection to a device using the TCP protocol with a specified IP address and port. ```python meshcore = await MeshCore.create_tcp("192.168.1.100", 4000) ``` -------------------------------- ### High-Level Data Signing Helper Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md The `sign` method provides a convenient way to sign arbitrary data on-device, automatically handling data chunking. It returns an Event, which can be a SIGNATURE or an ERROR. ```python sign(data, chunk_size=512) ``` -------------------------------- ### Helper Methods Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Utility methods for finding contacts, signing data, checking connection status, and managing event subscriptions. ```APIDOC ## Helper Methods ### `get_contact_by_name(name)` #### Description Find a contact by its advertisement name. #### Parameters - `name` (str) - The name of the contact. #### Returns `dict/None` - The contact object if found, otherwise None. ### `get_contact_by_key_prefix(prefix)` #### Description Find a contact by a partial public key prefix. #### Parameters - `prefix` (str) - The partial public key prefix. #### Returns `dict/None` - The contact object if found, otherwise None. ### `sign(data, chunk_size=512)` #### Description High-level helper to sign arbitrary data on-device, handling chunking automatically. #### Parameters - `data` (any) - The data to sign. - `chunk_size` (int) - Optional - The size of data chunks to use for signing. Defaults to 512. #### Returns `Event` - An Event object containing `SIGNATURE` on success or `ERROR` on failure. ### `is_connected` #### Description Check if the device is currently connected to the network. #### Parameters None #### Returns `bool` - True if connected, False otherwise. ### `subscribe(event_type, callback, filters=None)` #### Description Subscribe to specific events with optional attribute filtering. #### Parameters - `event_type` (EventType) - The type of event to subscribe to. - `callback` (function) - The function to call when the event occurs. - `filters` (dict) - Optional - Filters to apply to the events (e.g., `{"pubkey_prefix": "a1b2c3d4e5f6"}`). #### Returns `Subscription` - An object representing the subscription that can be used to unsubscribe. ### `unsubscribe(subscription)` #### Description Remove an existing event subscription. #### Parameters - `subscription` (Subscription) - The subscription object to remove. #### Returns None ### `wait_for_event(event_type, filters=None, timeout=None)` #### Description Wait for a specific event to occur with optional filtering and timeout. #### Parameters - `event_type` (EventType) - The type of event to wait for. - `filters` (dict) - Optional - Filters to apply to the event. - `timeout` (float) - Optional - The maximum time to wait for the event. #### Returns `Event/None` - The event object if received within the timeout, otherwise None. ``` -------------------------------- ### Device Configuration Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands to configure various aspects of the device, including its name, location, time, and security settings. ```APIDOC ## set_name(name) ### Description Set device name/identifier. ### Method `set_name(name)` ### Parameters #### Path Parameters - **name** (str) - Required - The new name for the device. ``` ```APIDOC ## set_coords(lat, lon) ### Description Set device GPS coordinates. ### Method `set_coords(lat, lon)` ### Parameters #### Path Parameters - **lat** (float) - Required - The latitude value. - **lon** (float) - Required - The longitude value. ``` ```APIDOC ## set_time(val) ### Description Set device time (Unix timestamp). ### Method `set_time(val)` ### Parameters #### Path Parameters - **val** (int) - Required - The Unix timestamp value. ``` ```APIDOC ## set_tx_power(val) ### Description Set radio transmission power level. ### Method `set_tx_power(val)` ### Parameters #### Path Parameters - **val** (int) - Required - The transmission power level. ``` ```APIDOC ## set_devicepin(pin) ### Description Set device PIN for security. ### Method `set_devicepin(pin)` ### Parameters #### Path Parameters - **pin** (int) - Required - The device PIN. ``` ```APIDOC ## set_custom_var(key, value) ### Description Set a custom variable on the device. ### Method `set_custom_var(key, value)` ### Parameters #### Path Parameters - **key** (str) - Required - The key for the custom variable. - **value** (str) - Required - The value for the custom variable. ``` -------------------------------- ### Run Tests from a Specific File Source: https://github.com/meshcore-dev/meshcore_py/blob/main/tests/README.md Execute tests located within a specific file. This is useful for focusing on a particular module or set of tests. ```bash pytest tests/unit/test_commands.py ``` -------------------------------- ### Binary Protocol Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Functions for interacting with the binary protocol, including requesting status, telemetry, historical data, and managing signing sessions. ```APIDOC ## Binary Protocol Commands ### `req_status(contact, timeout=0)` #### Description Get detailed status from a contact via the binary protocol. #### Parameters - `contact` (dict) - The contact object. - `timeout` (float) - Optional - Timeout duration for the request. #### Returns `STATUS_RESPONSE` ### `req_telemetry(contact, timeout=0)` #### Description Get telemetry data from a contact via the binary protocol. #### Parameters - `contact` (dict) - The contact object. - `timeout` (float) - Optional - Timeout duration for the request. #### Returns `TELEMETRY_RESPONSE` ### `req_mma(contact, start, end, timeout=0)` #### Description Get historical telemetry data from a contact via the binary protocol. #### Parameters - `contact` (dict) - The contact object. - `start` (int) - The start timestamp for the data. - `end` (int) - The end timestamp for the data. - `timeout` (float) - Optional - Timeout duration for the request. #### Returns `MMA_RESPONSE` ### `req_acl(contact, timeout=0)` #### Description Get the access control list from a contact via the binary protocol. #### Parameters - `contact` (dict) - The contact object. - `timeout` (float) - Optional - Timeout duration for the request. #### Returns `ACL_RESPONSE` ### `sign_start()` #### Description Begin a signing session. Returns the maximum buffer size for data to sign. #### Parameters None #### Returns `SIGN_START` ### `sign_data(chunk)` #### Description Append a data chunk to the current signing session. Can be called multiple times. #### Parameters - `chunk` (bytes) - The data chunk to sign. #### Returns `OK` ### `sign_finish()` #### Description Finalize the signing process and return the signature for all accumulated data. #### Parameters None #### Returns `SIGNATURE` ``` -------------------------------- ### Run All Tests with Pytest Source: https://github.com/meshcore-dev/meshcore_py/blob/main/tests/README.md Execute all tests in the project using pytest. This is the default command to ensure the entire test suite passes. ```bash pytest ``` -------------------------------- ### Run Tests with Verbose Output Source: https://github.com/meshcore-dev/meshcore_py/blob/main/tests/README.md Run all tests with verbose output enabled. This provides more detailed information about each test case being executed. ```bash pytest -v ``` -------------------------------- ### Subscribe to Contact Message Events Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Set up asynchronous handlers for incoming contact messages. The `handle_message` function is called whenever a message is received, and `handle_specific_contact_messages` allows filtering by a specific contact's public key prefix. ```python # Subscribe to incoming messages async def handle_message(event): data = event.payload print(f"Message from {data['pubkey_prefix']}: {data['text']}") subscription = meshcore.subscribe(EventType.CONTACT_MSG_RECV, handle_message) # Subscribe to advertisements async def handle_advert(event): print("Advertisement detected!") meshcore.subscribe(EventType.ADVERTISEMENT, handle_advert) # When done, unsubscribe meshcore.unsubscribe(subscription) ``` ```python # Subscribe only to messages from a specific contact async def handle_specific_contact_messages(event): print(f"Message from Alice: {event.payload['text']}") contact = meshcore.get_contact_by_name("Alice") if contact: alice_subscription = meshcore.subscribe( EventType.CONTACT_MSG_RECV, handle_specific_contact_messages, attribute_filters={"pubkey_prefix": contact["public_key"][:12]} ) ``` -------------------------------- ### Send Login Request Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_login` to initiate a login request to a contact. Requires the destination and the password. The message will be marked as sent. ```python send_login(dst, pwd) ``` -------------------------------- ### Run a Specific Test Source: https://github.com/meshcore-dev/meshcore_py/blob/main/tests/README.md Execute a single, specific test case. This allows for targeted debugging and verification of individual test functionalities. ```bash pytest tests/unit/test_commands.py::test_send_msg ``` -------------------------------- ### Find Contact by Public Key Prefix Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `get_contact_by_key_prefix` to locate a contact by a partial public key prefix. Returns the contact dictionary or None. ```python get_contact_by_key_prefix(prefix) ``` -------------------------------- ### Device Information Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands to retrieve information about the device itself, its configuration, and status. ```APIDOC ## send_appstart() ### Description Get device self-information and configuration. ### Method `send_appstart()` ### Parameters None ### Returns `SELF_INFO` ``` ```APIDOC ## send_device_query() ### Description Query device capabilities and firmware info. ### Method `send_device_query()` ### Parameters None ### Returns `DEVICE_INFO` ``` ```APIDOC ## get_bat() ### Description Get battery level and storage information. ### Method `get_bat()` ### Parameters None ### Returns `BATTERY` ``` ```APIDOC ## get_time() ### Description Get current device time. ### Method `get_time()` ### Parameters None ### Returns `CURRENT_TIME` ``` ```APIDOC ## get_self_telemetry() ### Description Get device's own telemetry data. ### Method `get_self_telemetry()` ### Parameters None ### Returns `TELEMETRY_RESPONSE` ``` ```APIDOC ## get_custom_vars() ### Description Retrieve all custom variables. ### Method `get_custom_vars()` ### Parameters None ### Returns `CUSTOM_VARS` ``` ```APIDOC ## get_allowed_repeat_freq() ### Description Retrieve allowed repeat frequencies from the device. ### Method `get_allowed_repeat_freq()` ### Parameters None ### Returns `ALLOWED_FREQ` ``` -------------------------------- ### Set Device Name Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Set a new name for the device. Check the result for errors. ```python result = await meshcore.commands.set_name("My Device") if result.type == EventType.ERROR: print(f"Error setting name: {result.payload}") ``` -------------------------------- ### Radio Configuration Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands to configure the device's radio parameters, including frequency, bandwidth, spreading factor, and coding rate. ```APIDOC ## set_radio(freq, bw, sf, cr) ### Description Configure radio parameters including frequency, bandwidth, spreading factor, and coding rate. ### Method `set_radio(freq, bw, sf, cr)` ### Parameters #### Path Parameters - **freq** (float) - Required - The radio frequency in MHz. - **bw** (float) - Required - The bandwidth in kHz. - **sf** (int) - Required - The spreading factor. - **cr** (int) - Required - The coding rate (5-8). ``` ```APIDOC ## set_tuning(rx_dly, af) ### Description Set radio tuning parameters. ### Method `set_tuning(rx_dly, af)` ### Parameters #### Path Parameters - **rx_dly** (int) - Required - The receive delay. - **af** (int) - Required - The auto-frequency value. ``` -------------------------------- ### Configure Device PIN for BLE Pairing Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Set the device's PIN for BLE pairing. This should be done before attempting to connect with PIN pairing. ```python meshcore = await MeshCore.create_ble("12:34:56:78:90:AB") await meshcore.commands.set_devicepin(123456) ``` -------------------------------- ### Device Actions Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands to perform actions on the device, such as sending advertisements or rebooting. ```APIDOC ## send_advert(flood=False) ### Description Send an advertisement to the network. Can optionally flood the network. ### Method `send_advert(flood=False)` ### Parameters #### Path Parameters - **flood** (bool) - Optional - If True, floods the network with the advertisement. Defaults to False. ``` ```APIDOC ## reboot() ### Description Reboot the device. No response is expected. ### Method `reboot()` ### Parameters None ``` -------------------------------- ### Enable Automatic Message Fetching Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Configure the MeshCore library to automatically fetch incoming messages. This simplifies message handling by allowing you to subscribe to message events without manually polling for new messages. Remember to stop fetching when done. ```python # Start auto-fetching messages await meshcore.start_auto_message_fetching() # Just subscribe to message events - the library handles fetching async def on_message(event): print(f"New message: {event.payload['text']}") meshcore.subscribe(EventType.CONTACT_MSG_RECV, on_message) # When done await meshcore.stop_auto_message_fetching() ``` -------------------------------- ### Connect via BLE Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Establish a connection to a device using Bluetooth Low Energy. The function can scan for devices if an address is not provided. ```python meshcore = await MeshCore.create_ble("12:34:56:78:90:AB") ``` -------------------------------- ### Security Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands related to device security, including exporting and importing private keys. ```APIDOC ## export_private_key() ### Description Export the device's private key. Requires PIN authentication and enabled firmware. ### Method `export_private_key()` ### Parameters None ### Returns `PRIVATE_KEY/DISABLED` ``` ```APIDOC ## import_private_key(key) ### Description Import a private key to the device. ### Method `import_private_key(key)` ### Parameters #### Path Parameters - **key** (bytes) - Required - The private key to import. ``` -------------------------------- ### Finalize Signing Session Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `sign_finish` to complete the signing process and retrieve the signature for all accumulated data chunks. ```python sign_finish() ``` -------------------------------- ### Find Contacts by Name or Key Prefix Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use these methods to locate contacts within the MeshCore network. `get_contact_by_name` searches for an exact name match, while `get_contact_by_key_prefix` finds contacts based on a partial public key. ```python # Find a contact by name contact = meshcore.get_contact_by_name("Bob's Radio") if contact: print(f"Found Bob at: {contact['adv_lat']}, {contact['adv_lon']}") # Find by partial key prefix contact = meshcore.get_contact_by_key_prefix("a1b2c3") ``` -------------------------------- ### Connect via BLE with PIN Pairing Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Establish a BLE connection requiring PIN pairing for enhanced security. The PIN must match the device's configured PIN. ```python meshcore = await MeshCore.create_ble("12:34:56:78:90:AB", pin="123456") ``` -------------------------------- ### Subscribe to Events with Filtering Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `subscribe` to register a callback function for specific event types. Optional attribute filters can be applied to narrow down the events received. ```python # Filter by public key prefix meshcore.subscribe( EventType.CONTACT_MSG_RECV, handler, attribute_filters={"pubkey_prefix": "a1b2c3d4e5f6"} ) ``` ```python # Filter by channel index meshcore.subscribe( EventType.CHANNEL_MSG_RECV, handler, attribute_filters={"channel_idx": 0} ) ``` ```python # Filter acknowledgments by code meshcore.subscribe( EventType.ACK, handler, attribute_filters={"code": "12345678"} ) ``` -------------------------------- ### Send Messages to Contacts Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Demonstrates sending messages to contacts using a contact object, a public key string, or bytes. Ensure you have retrieved contacts or a specific contact by name before sending. ```python # Get contacts and send to a specific one result = await meshcore.commands.get_contacts() if result.type == EventType.ERROR: print(f"Error getting contacts: {result.payload}") else: contacts = result.payload for key, contact in contacts.items(): if contact["adv_name"] == "Alice": # Option 1: Pass the contact object directly result = await meshcore.commands.send_msg(contact, "Hello Alice!") if result.type == EventType.ERROR: print(f"Error sending message: {result.payload}") # Option 2: Use the public key string result = await meshcore.commands.send_msg(contact["public_key"], "Hello again Alice!") if result.type == EventType.ERROR: print(f"Error sending message: {result.payload}") # Option 3 (backward compatible): Convert the hex key to bytes dst_key = bytes.fromhex(contact["public_key"]) result = await meshcore.commands.send_msg(dst_key, "Hello once more Alice!") if result.type == EventType.ERROR: print(f"Error sending message: {result.payload}") break # You can also directly use a contact found by name contact = meshcore.get_contact_by_name("Bob") if contact: result = await meshcore.commands.send_msg(contact, "Hello Bob!") if result.type == EventType.ERROR: print(f"Error sending message: {result.payload}") ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Activate debug mode when creating a MeshCore connection to log detailed information about sent commands and received events. This is useful for troubleshooting communication issues. ```python # Enable debug mode when creating the connection meshcore = await MeshCore.create_serial("/dev/ttyUSB0", debug=True) ``` -------------------------------- ### Telemetry Configuration Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands to configure telemetry modes for location, environment, and manual contact addition. ```APIDOC ## set_telemetry_mode_base(mode) ### Description Set the base telemetry mode. ### Method `set_telemetry_mode_base(mode)` ### Parameters #### Path Parameters - **mode** (int) - Required - The base telemetry mode. ``` ```APIDOC ## set_telemetry_mode_loc(mode) ### Description Set the location telemetry mode. ### Method `set_telemetry_mode_loc(mode)` ### Parameters #### Path Parameters - **mode** (int) - Required - The location telemetry mode. ``` ```APIDOC ## set_telemetry_mode_env(mode) ### Description Set the environmental telemetry mode. ### Method `set_telemetry_mode_env(mode)` ### Parameters #### Path Parameters - **mode** (int) - Required - The environmental telemetry mode. ``` ```APIDOC ## set_manual_add_contacts(enabled) ### Description Enable or disable manual contact addition. ### Method `set_manual_add_contacts(enabled)` ### Parameters #### Path Parameters - **enabled** (bool) - Required - Whether to enable manual contact addition. ``` ```APIDOC ## set_advert_loc_policy(policy) ### Description Set the location advertisement policy. ### Method `set_advert_loc_policy(policy)` ### Parameters #### Path Parameters - **policy** (int) - Required - The location advertisement policy. ``` -------------------------------- ### Send Route Trace Packet Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_trace` to send a route trace packet. This requires an authentication code, tag, flags, and an optional path. ```python send_trace(auth_code, tag, flags, path=None) ``` -------------------------------- ### Request Telemetry via Binary Protocol Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `req_telemetry` to retrieve telemetry data from a contact via the binary protocol. A timeout can be specified. ```python req_telemetry(contact, timeout=0) ``` -------------------------------- ### Send a Message Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Send a message to a specified destination key. The destination key should be in bytes. ```python result = await meshcore.commands.send_msg(dst_key, "Hello!") if result.type == EventType.ERROR: print(f"Error sending message: {result.payload}") ``` -------------------------------- ### Enable Auto-Reconnect with Custom Retry Limits Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Configure a TCP connection to automatically attempt reconnection with a specified maximum number of retry attempts. ```python meshcore = await MeshCore.create_tcp( "192.168.1.100", 4000, auto_reconnect=True, max_reconnect_attempts=5 ) ``` -------------------------------- ### Statistics Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands to retrieve various statistics from the device, including core, radio, and packet statistics. ```APIDOC ## get_stats_core() ### Description Get core statistics, including voltage, uptime, errors, and queue length. ### Method `get_stats_core()` ### Parameters None ### Returns `STATS_CORE` ``` ```APIDOC ## get_stats_radio() ### Description Get radio statistics, including noise floor, last RSSI/SNR, and transmit/receive time statistics. ### Method `get_stats_radio()` ### Parameters None ### Returns `STATS_RADIO` ``` ```APIDOC ## get_stats_packets() ### Description Get packet statistics, including transmit/receive totals, flood vs. direct counts, and receive errors. ### Method `get_stats_packets()` ### Parameters None ### Returns `STATS_PACKETS` ``` -------------------------------- ### Append Data Chunk for Signing Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `sign_data` to append a chunk of data to the current signing session. This method can be called multiple times to accumulate data. ```python sign_data(chunk) ``` -------------------------------- ### Check Connection Status Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Query the current connection status of the MeshCore device. ```python if meshcore.is_connected: print("Device is currently connected") ``` -------------------------------- ### Send Binary Data Request Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_binary_req` to send raw binary data to a contact. The destination and the binary data must be provided. ```python send_binary_req(dst, bin_data) ``` -------------------------------- ### Contact Management Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands for managing the contact list on the device, including adding, updating, and removing contacts. ```APIDOC ## get_contacts(lastmod=0) ### Description Get the contact list. Can filter by last modification time. ### Method `get_contacts(lastmod=0)` ### Parameters #### Path Parameters - **lastmod** (int) - Optional - Filter contacts modified after this Unix timestamp. Defaults to 0. ``` ```APIDOC ## add_contact(contact) ### Description Add a new contact to the device. ### Method `add_contact(contact)` ### Parameters #### Path Parameters - **contact** (dict) - Required - A dictionary representing the contact to add. ``` ```APIDOC ## update_contact(contact, path, flags) ### Description Update an existing contact with new details. ### Method `update_contact(contact, path, flags)` ### Parameters #### Path Parameters - **contact** (dict) - Required - A dictionary representing the updated contact. - **path** (bytes) - Required - The new routing path for the contact. - **flags** (int) - Required - The new flags for the contact. ``` ```APIDOC ## remove_contact(key) ### Description Remove a contact from the device using their public key. ### Method `remove_contact(key)` ### Parameters #### Path Parameters - **key** (str/bytes) - Required - The public key of the contact to remove. ``` -------------------------------- ### Request Access Control List Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `req_acl` to retrieve the access control list from a contact via the binary protocol. A timeout can be specified. ```python req_acl(contact, timeout=0) ``` -------------------------------- ### Find Contact by Name Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `get_contact_by_name` to find a contact's details using their advertisement name. Returns the contact dictionary or None if not found. ```python get_contact_by_name(name) ``` -------------------------------- ### Monitor Channel Messages Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Subscribe to incoming channel messages and define a handler function to process them. This is useful for real-time communication monitoring. ```python # Subscribe to channel messages async def channel_handler(event): msg = event.payload print(f"Channel {msg['channel_idx']}: {msg['text']}") meshcore.subscribe(EventType.CHANNEL_MSG_RECV, channel_handler) ``` -------------------------------- ### Event Types Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md MeshCore dispatches various events that can be subscribed to. Each event has a string value and a typical payload associated with it. ```APIDOC ## Event Types All events in MeshCore are represented by the `EventType` enum. These events are dispatched by the library and can be subscribed to: | Event Type | String Value | Description | Typical Payload | |------------|-------------|-------------|-----------------| | **Device & Status Events** ||| | `SELF_INFO` | `"self_info"` | Device's own information after appstart | Device configuration, public key, coordinates | | `DEVICE_INFO` | `"device_info"` | Device capabilities and firmware info | Firmware version, model, max contacts/channels | | `BATTERY` | `"battery_info"` | Battery level and storage info | Battery level, used/total storage | | `CURRENT_TIME` | `"time_update"` | Device time response | Current timestamp | | `STATUS_RESPONSE` | `"status_response"` | Device status statistics | Battery, TX queue, noise floor, packet counts | | `CUSTOM_VARS` | `"custom_vars"` | Custom variable responses | Key-value pairs of custom variables | | **Contact Events** ||| | `CONTACTS` | `"contacts"` | Contact list response | Dictionary of contacts by public key | | `NEW_CONTACT` | `"new_contact"` | New contact discovered | Contact information | | `CONTACT_URI` | `"contact_uri"` | Contact export URI | Shareable contact URI | | **Messaging Events** ||| | `CONTACT_MSG_RECV` | `"contact_message"` | Direct message received | Message text, sender prefix, timestamp | | `CHANNEL_MSG_RECV` | `"channel_message"` | Channel message received | Message text, channel index, timestamp | | `MSG_SENT` | `"message_sent"` | Message send confirmation | Expected ACK code, suggested timeout | | `NO_MORE_MSGS` | `"no_more_messages"` | No pending messages | Empty payload | | `MESSAGES_WAITING` | `"messages_waiting"` | Messages available notification | Empty payload | | **Network Events** ||| | `ADVERTISEMENT` | `"advertisement"` | Node advertisement detected | Public key of advertising node | | `PATH_UPDATE` | `"path_update"` | Routing path update | Public key and path information | | `ACK` | `"acknowledgement"` | Message acknowledgment | ACK code | | `PATH_RESPONSE` | `"path_response"` | Path discovery response | Inbound/outbound path data | | `TRACE_DATA` | `"trace_data"` | Route trace information | Path with SNR data for each hop | | **Telemetry Events** ||| | `TELEMETRY_RESPONSE` | `"telemetry_response"` | Telemetry data response | LPP-formatted sensor data | | `MMA_RESPONSE` | `"mma_response"` | Memory Management Area data | Min/max/avg telemetry over time range | | `ACL_RESPONSE` | `"acl_response"` | Access Control List data | List of keys and permissions | | **Channel Events** ||| | `CHANNEL_INFO` | `"channel_info"` | Channel configuration | Channel name, secret, index | | **Raw Data Events** ||| | `RAW_DATA` | `"raw_data"` | Raw radio data | SNR, RSSI, payload hex | | `RX_LOG_DATA` | `"rx_log_data"` | RF log data | SNR, RSSI, raw payload | | `LOG_DATA` | `"log_data"` | Generic log data | Various log information | | **Binary Protocol Events** ||| | `BINARY_RESPONSE` | `"binary_response"` | Generic binary response | Tag and hex data | | `SIGN_START` | `"sign_start"` | Start of an on-device signing session | Maximum buffer size (bytes) for data to sign | | `SIGNATURE` | `"signature"` | Resulting on-device signature | Raw signature bytes | | **Authentication Events** ||| | `LOGIN_SUCCESS` | `"login_success"` | Successful login | Permissions, admin status, pubkey prefix | | `LOGIN_FAILED` | `"login_failed"` | Failed login attempt | Pubkey prefix | | **Command Response Events** ||| | `OK` | `"command_ok"` | Command successful | Success confirmation, optional value | | `ERROR` | `"command_error"` | Command failed | Error reason or code | | **Connection Events** ||| | `CONNECTED` | `"connected"` | Connection established | Connection details, reconnection status | | `DISCONNECTED` | `"disconnected"` | Connection lost | Disconnection reason | ``` -------------------------------- ### Messaging Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Functions for sending various types of messages, including direct messages, channel messages, login/logout requests, status requests, and binary data. ```APIDOC ## Message Handling ### `get_msg(timeout=None)` #### Description Get the next pending message. #### Parameters - `timeout` (float) - Optional - Timeout duration. #### Returns `CONTACT_MSG_RECV/CHANNEL_MSG_RECV/NO_MORE_MSGS` ### `send_msg(dst, msg, timestamp=None)` #### Description Send a direct message to a contact. #### Parameters - `dst` (contact/str/bytes) - Destination contact or identifier. - `msg` (str) - The message content. - `timestamp` (int) - Optional - Timestamp for the message. #### Returns `MSG_SENT` ### `send_cmd(dst, cmd, timestamp=None)` #### Description Send a command message to a contact. #### Parameters - `dst` (contact/str/bytes) - Destination contact or identifier. - `cmd` (str) - The command to send. - `timestamp` (int) - Optional - Timestamp for the message. #### Returns `MSG_SENT` ### `send_chan_msg(chan, msg, timestamp=None)` #### Description Send a message to a specific channel. #### Parameters - `chan` (int) - The channel index. - `msg` (str) - The message content. - `timestamp` (int) - Optional - Timestamp for the message. #### Returns `MSG_OK` ## Authentication ### `send_login(dst, pwd)` #### Description Send a login request to a contact. #### Parameters - `dst` (contact/str/bytes) - Destination contact or identifier. - `pwd` (str) - The password for login. #### Returns `MSG_SENT` ### `send_logout(dst)` #### Description Send a logout request to a contact. #### Parameters - `dst` (contact/str/bytes) - Destination contact or identifier. #### Returns `MSG_SENT` ## Information Requests ### `send_statusreq(dst)` #### Description Request the status from a contact. #### Parameters - `dst` (contact/str/bytes) - Destination contact or identifier. #### Returns `MSG_SENT` ### `send_telemetry_req(dst)` #### Description Request telemetry data from a contact. #### Parameters - `dst` (contact/str/bytes) - Destination contact or identifier. #### Returns `MSG_SENT` ## Advanced Messaging ### `send_binary_req(dst, bin_data)` #### Description Send binary data to a contact. #### Parameters - `dst` (contact/str/bytes) - Destination contact or identifier. - `bin_data` (bytes) - The binary data to send. #### Returns `MSG_SENT` ### `send_path_discovery(dst)` #### Description Initiate path discovery to a contact. #### Parameters - `dst` (contact/str/bytes) - Destination contact or identifier. #### Returns `MSG_SENT` ### `send_trace(auth_code, tag, flags, path=None)` #### Description Send a route trace packet. #### Parameters - `auth_code` (int) - Authorization code. - `tag` (int) - Tag for the trace. - `flags` (int) - Flags for the trace. - `path` (list) - Optional - The path for the trace. #### Returns `MSG_SENT` ## Message Retry & Scope ### `send_msg_with_retry(dst, msg, ...)` #### Description Send a message with automatic retry and ACK waiting. #### Parameters - `dst` - Destination contact or identifier. - `msg` - The message content. - `timestamp` - Optional - Timestamp for the message. - `max_attempts` - Maximum number of retry attempts. - `max_flood_attempts` - Maximum number of flood retry attempts. - `flood_after` - Delay before flood retries. - `timeout` - Timeout for each attempt. - `min_timeout` - Minimum timeout for retries. #### Returns `MSG_SENT/None` ### `set_flood_scope(scope)` #### Description Set the flood scope for messages. #### Parameters - `scope` (str) - The flood scope (e.g., "#name", "0", "*", or raw key). #### Returns `OK` ``` -------------------------------- ### Handle Command Return Values Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Check the EventType of a command result to determine success or failure. Access the payload for event-specific data. ```python result = await meshcore.commands.some_command() if result.type == EventType.ERROR: print(f"Command failed: {result.payload}") else: print(f"Command succeeded with event type: {result.type}") data = result.payload ``` -------------------------------- ### Common Error Handling Pattern Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md A common pattern for handling errors from MeshCore commands, specifically for sending messages and checking the expected acknowledgment. ```python result = await meshcore.commands.send_msg(contact, "Hello!") if result.type == EventType.ERROR: print(f"Error sending message: {result.payload}") else: print(f"Message sent with expected ack: {result.payload['expected_ack'].hex()}") ``` -------------------------------- ### Request Telemetry from Contact Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_telemetry_req` to request telemetry data from a contact. The destination can be a contact object, string, or bytes. ```python send_telemetry_req(dst) ``` -------------------------------- ### Check Device Connection Status Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `is_connected` to determine if the device is currently connected to the network. Returns a boolean value. ```python is_connected ``` -------------------------------- ### Send Channel Message Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_chan_msg` to send a message to a specific channel. Requires the channel ID and the message content. An optional timestamp can be included. ```python send_chan_msg(chan, msg, timestamp=None) ``` -------------------------------- ### Send Message with Retry Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_msg_with_retry` for robust message sending that includes automatic retries and waiting for acknowledgments. It supports various parameters for controlling the retry behavior. ```python send_msg_with_retry(dst, msg, ...) ``` -------------------------------- ### Wait for Specific Event Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `wait_for_event` to pause execution until a specific event occurs. You can filter events and set a timeout. Returns the Event object or None if the timeout is reached. ```python wait_for_event(event_type, filters=None, timeout=None) ``` -------------------------------- ### Send Message and Wait for Acknowledgment Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md This function sends a message and then waits for a specific acknowledgment event. It extracts the expected acknowledgment code from the send result and uses `wait_for_event` with a timeout to confirm delivery. ```python # Send a message and wait for its specific acknowledgment async def send_and_confirm_message(meshcore, dst_key, message): # Send the message and get information about the sent message sent_result = await meshcore.commands.send_msg(dst_key, message) # Extract the expected acknowledgment code from the message sent event if sent_result.type == EventType.ERROR: print(f"Error sending message: {sent_result.payload}") return False expected_ack = sent_result.payload["expected_ack"].hex() print(f"Message sent, waiting for ack with code: {expected_ack}") # Wait specifically for this acknowledgment result = await meshcore.wait_for_event( EventType.ACK, attribute_filters={"code": expected_ack}, timeout=10.0 ) if result: print("Message confirmed delivered!") return True else: print("Message delivery confirmation timed out") return False ``` -------------------------------- ### Contact Operations Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands for performing operations on contacts, such as resetting routing paths or sharing contact information. ```APIDOC ## reset_path(key) ### Description Reset the routing path for a specific contact. ### Method `reset_path(key)` ### Parameters #### Path Parameters - **key** (str/bytes) - Required - The public key of the contact. ``` ```APIDOC ## share_contact(key) ### Description Share a contact's information with the network. ### Method `share_contact(key)` ### Parameters #### Path Parameters - **key** (str/bytes) - Required - The public key of the contact to share. ``` ```APIDOC ## export_contact(key=None) ### Description Export a contact as a URI. If no key is provided, exports the node's own information. ### Method `export_contact(key=None)` ### Parameters #### Path Parameters - **key** (str/bytes/None) - Optional - The public key of the contact to export. Exports the node if None. ``` ```APIDOC ## import_contact(card_data) ### Description Import a contact from provided card data. ### Method `import_contact(card_data)` ### Parameters #### Path Parameters - **card_data** (bytes) - Required - The card data representing the contact. ``` -------------------------------- ### Request Status from Contact Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_statusreq` to request the current status from a contact. The destination is specified as a contact object, string, or bytes. ```python send_statusreq(dst) ``` -------------------------------- ### Send Direct Message Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_msg` to send a direct message to a contact. The destination can be a contact object, string, or bytes. An optional timestamp can be provided. ```python send_msg(dst, msg, timestamp=None) ``` -------------------------------- ### Send Logout Request Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `send_logout` to send a logout request to a contact. This command requires only the destination. ```python send_logout(dst) ``` -------------------------------- ### Remove Event Subscription Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Use `unsubscribe` to remove a previously active event subscription. Requires the Subscription object returned by the `subscribe` method. ```python unsubscribe(subscription) ``` -------------------------------- ### Contact Modification Commands Source: https://github.com/meshcore-dev/meshcore_py/blob/main/README.md Commands to modify specific attributes of a contact, such as their routing path or flags. ```APIDOC ## change_contact_path(contact, path) ### Description Change the routing path for a specific contact. ### Method `change_contact_path(contact, path)` ### Parameters #### Path Parameters - **contact** (dict) - Required - The contact dictionary. - **path** (bytes) - Required - The new routing path. ``` ```APIDOC ## change_contact_flags(contact, flags) ### Description Change the flags or settings for a specific contact. ### Method `change_contact_flags(contact, flags)` ### Parameters #### Path Parameters - **contact** (dict) - Required - The contact dictionary. - **flags** (int) - Required - The new flags for the contact. ```