Meshtastic Home Assistant Integration

repository·main·Indexed 19 days ago

https://github.com/meshtastic/home-assistant

A Home Assistant integration for Meshtastic that enables interaction with mesh networks, monitoring of node metrics, and device position tracking. It supports sending and receiving messages via the notify platform or the meshtastic_api_text_message event, provides device triggers and actions for automations, and includes a TCP proxy to allow the Meshtastic Web Client to connect through Home Assistant.

Tokens
2.7K
Snippets
5
Records
10
Agent score
14%

What's inside meshtastic-home-assistant

  1. View Meshtastic messages in the Home Assistant Logbook

    main

    Direct messages and channel messages are recorded in the Home Assistant Logbook.

    • Each gateway has specific entities for its direct messages and channels.
    • You can view logs by navigating to the device and selecting the entity, or by filtering the global Logbook for those entities.
    • Note: Messages are only recorded if the Logbook integration is enabled.
  2. Automate Meshtastic with Triggers and Actions

    main

    For nodes selected during configuration, you can use device triggers and device actions in Home Assistant automations.

    Triggers

    Triggers are available when messages are sent or received. Gateway nodes provide more granular triggers, allowing you to filter by specific channels or direct messages.

    Actions

    • Send Direct Message
    • Request Telemetry
    • Request Position

    Important: Always include a delay before performing an action if the automation was triggered by a Meshtastic device trigger. This prevents the action from being dropped if the device is still busy processing the incoming message.

    - id: '1800000042000'
      alias: Ping Sample
      description: 'Reply back after message from device'
      triggers:
      - device_id: e3376b45b4912c27cffb46c58e4998e4
        domain: meshtastic
        type: message.sent
        trigger: device
      actions:
      - delay:
          seconds: 10
      - device_id: e3376b45b4912c27cffb46c58e4998e4
        domain: meshtastic
        type: send_message
        message: PONG {{ trigger.event.data.message }}
  3. Track Meshtastic node positions with Device Tracker

    main

    For nodes selected during configuration, their position is exposed as a Home Assistant device_tracker entity. This allows you to:

    • View nodes on the Home Assistant map.
    • Use 'Home/Away' presence detection based on node position.
  4. Handle incoming text messages via the `meshtastic_api_text_message` event

    main

    If you prefer not to use the notify platform (to avoid cluttering Home Assistant with many entities), you can listen for the meshtastic_api_text_message event. This allows you to handle all incoming channel and direct messages in a single automation.

    Event Data Structure

    When a message is received, the event contains the following data:

    trigger:
      event:
        event_type: meshtastic_api_text_message
        event_data:
          data:
            from: 1127918844
            to:
              node: null
              channel: 0
            gateway: 862525748
            message: Sample Message
    • from: The node ID of the sender.
    • to.node: The node ID of the gateway (for direct messages).
    • to.channel: The gateway channel ID (for channel messages).
    • gateway: The gateway node ID.

    Filtering and Replying

    • Filter by Gateway Node: Use {{ trigger.event.data.data.to.node == <NODE_ID> }}.
    • Filter by Channel: Use {{ trigger.event.data.data.to.channel == 0 }} (where 0 is typically LONGFAST).
    • Replying: Use the meshtastic.send_text action. Always include a delay (at least 2 seconds) before replying to ensure the device is idle.
    action: meshtastic.send_text
    metadata: {}
    data:
      ack: false
      from: "{{ trigger.event.data.data.gateway }}"
      to: "{{ trigger.event.data.data.from }}"
      text: "ECHO: {{ trigger.event.data.data.message }}"
  5. Send Meshtastic messages using the Notification platform

    main

    The recommended way to send messages to the mesh without managing low-level details (like specific gateways or acknowledgements) is to use the notify platform. The integration generates notify.mesh_* entities.

    All nodes from the gateway's node database and all available channels can be used as notification targets. This implementation uses the Home Assistant entity notification platform.

  6. Use the Meshtastic Web Client via Home Assistant proxy

    main

    Because Meshtastic firmware typically allows only one connection at a time, this integration provides a workaround by exposing an HTTP API for each configured gateway. This allows the Meshtastic Web Client to connect to Home Assistant, which then acts as a proxy to your nodes.

    This method enables interaction with nodes that do not support TCP or are connected via serial/Bluetooth.

    Security Warning: Enabling this feature provides unauthenticated access to your gateway nodes to anyone who can reach your Home Assistant instance, as the Meshtastic HTTP API does not support authentication. Only use this in trusted environments.

    ### To access the web client:
    
    **In Home Assistant:**
    1. Enable the feature in the integration configuration.
    2. Navigate to the "Meshtastic" menu item (reload the Home Assistant interface if it is not visible).
    3. Press the "Open" button of the desired gateway to launch the web client.
    
    **Inside the Meshtastic Web Client:**
    4. Press "New Connection" (the correct hostname should be pre-populated).
    5. Press "Connect".
  7. Install the Meshtastic Home Assistant Integration via HACS

    main

    The recommended way to install the integration is using HACS (Home Assistant Community Store):

    1. Add this repository as a custom repository to HACS.
    2. Use HACS to install the integration.
    3. Restart Home Assistant.
    4. Set up the integration using the Home Assistant UI (Configuration -> Integrations -> Add Integration -> search for 'Meshtastic').
  8. Install the Meshtastic Home Assistant Integration manually

    main

    If you are not using HACS, follow these steps to install manually:

    1. Open your Home Assistant configuration directory (where configuration.yaml is located).
    2. Create a custom_components directory if it does not exist.
    3. Inside custom_components, create a folder named homeassistant-meshtastic.
    4. Download all files from the custom_components/meshtastic/ directory of this repository.
    5. Place the downloaded files into your new homeassistant-meshtastic folder.
    6. Restart Home Assistant.
    7. In the Home Assistant UI, go to Configuration -> Integrations, click + Add Integration, and search for Meshtastic.
  9. Use ClientProxyTransport to handle TCP stream packets

    main

    The ClientProxyTransport class extends StreamingClientTransport to wrap standard asyncio StreamReader and StreamWriter objects. It provides specialized methods for reading and writing Meshtastic protobuf packets over a TCP connection.

    Key methods:

    • read_to_radio_packet(): Asynchronously reads bytes from the stream, parses them as a mesh_pb2.ToRadio protobuf message, and returns a tuple of (packet_bytes, to_radio_message). Returns None if no packet is available or an error occurs.
    • write_from_radio_packet(from_radio): Takes a mesh_pb2.FromRadio object, serializes it to bytes, wraps it in a frame using StreamingClientTransport.build_frame, and writes it to the stream.
    • is_connected: A property that returns True for this transport implementation.
    # Example conceptual usage of ClientProxyTransport
    from asyncio import StreamReader, StreamWriter
    
    # Assuming reader and writer are provided by an asyncio server
    transport = ClientProxyTransport(reader, writer)
    
    # Reading a packet
    result = await transport.read_to_radio_packet()
    if result:
        packet_bytes, to_radio = result
        # Process packet...
    
    # Writing a packet
    # from_radio is a mesh_pb2.FromRadio instance
    await transport.write_from_radio_packet(from_radio)
  10. Use MeshtasticTcpProxy to proxy Meshtastic traffic over TCP

    main

    The MeshtasticTcpProxy class acts as a bridge between a MeshInterface (the gateway/radio connection) and multiple TCP clients. It starts a TCP server that listens for incoming connections and forwards packets between the TCP clients and the Meshtastic radio.

    Initialization:

    • interface: A MeshInterface instance representing the connection to the Meshtastic hardware.
    • host: The IP address to bind the server to (defaults to None, meaning all interfaces).
    • port: The TCP port to listen on (defaults to 4403).

    Lifecycle Management:

    • start(): Starts the TCP server and begins a background task to forward packets from the radio to all connected TCP clients.
    • stop(): Cancels the forwarding task and closes the TCP server.
    • The class supports the asynchronous context manager pattern (async with).

    Behavior:

    • When a TCP client connects, the proxy creates a dedicated pair of tasks: one to forward packets from the client to the radio (forward_to_radio) and one to forward packets from the radio to the client (forward_from_radio).
    • If a client sends a ToRadio packet with the disconnect field set to True, the proxy will disconnect that specific client.
    from custom_components.meshtastic.aiomeshtastic import MeshInterface
    from custom_components.meshtastic.meshtastic_tcp.server import MeshtasticTcpProxy
    
    async def run_proxy(mesh_interface: MeshInterface):
        # Initialize proxy on port 4403
        proxy = MeshtasticTcpProxy(interface=mesh_interface, host='0.0.0.0', port=4403)
        
        # Use as an async context manager to ensure start() and stop() are called
        async with proxy:
            # The proxy is now running and listening for TCP clients
            # Keep the loop alive
            await asyncio.Event().wait()