mirror of
https://github.com/meshtastic/python.git
synced 2025-12-26 17:37:51 -05:00
1851 lines
84 KiB
HTML
1851 lines
84 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
|
||
<meta name="generator" content="pdoc 0.10.0" />
|
||
<title>meshtastic.mesh_interface API documentation</title>
|
||
<meta name="description" content="Mesh Interface class" />
|
||
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
|
||
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
|
||
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
|
||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
|
||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
|
||
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<article id="content">
|
||
<header>
|
||
<h1 class="title">Module <code>meshtastic.mesh_interface</code></h1>
|
||
</header>
|
||
<section id="section-intro">
|
||
<p>Mesh Interface class</p>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">"""Mesh Interface class
|
||
"""
|
||
import sys
|
||
import random
|
||
import time
|
||
import logging
|
||
from typing import AnyStr
|
||
import threading
|
||
from datetime import datetime
|
||
import timeago
|
||
from tabulate import tabulate
|
||
|
||
import google.protobuf.json_format
|
||
|
||
from pubsub import pub
|
||
from google.protobuf.json_format import MessageToJson
|
||
|
||
|
||
import meshtastic.node
|
||
from . import portnums_pb2, mesh_pb2
|
||
from .util import stripnl, Timeout, our_exit
|
||
from .__init__ import LOCAL_ADDR, BROADCAST_NUM, BROADCAST_ADDR, ResponseHandler, publishingThread, OUR_APP_VERSION, protocols
|
||
|
||
class MeshInterface:
|
||
"""Interface class for meshtastic devices
|
||
|
||
Properties:
|
||
|
||
isConnected
|
||
nodes
|
||
debugOut
|
||
"""
|
||
|
||
def __init__(self, debugOut=None, noProto=False):
|
||
"""Constructor
|
||
|
||
Keyword Arguments:
|
||
noProto -- If True, don't try to run our protocol on the
|
||
link - just be a dumb serial client.
|
||
"""
|
||
self.debugOut = debugOut
|
||
self.nodes = None # FIXME
|
||
self.isConnected = threading.Event()
|
||
self.noProto = noProto
|
||
self.localNode = meshtastic.node.Node(self, -1) # We fixup nodenum later
|
||
self.myInfo = None # We don't have device info yet
|
||
self.responseHandlers = {} # A map from request ID to the handler
|
||
self.failure = None # If we've encountered a fatal exception it will be kept here
|
||
self._timeout = Timeout()
|
||
self.heartbeatTimer = None
|
||
random.seed() # FIXME, we should not clobber the random seedval here, instead tell user they must call it
|
||
self.currentPacketId = random.randint(0, 0xffffffff)
|
||
self.nodesByNum = None
|
||
self.configId = None
|
||
self.defaultHopLimit = 3
|
||
self.gotResponse = False # used in gpio read
|
||
self.mask = None # used in gpio read and gpio watch
|
||
|
||
def close(self):
|
||
"""Shutdown this interface"""
|
||
if self.heartbeatTimer:
|
||
self.heartbeatTimer.cancel()
|
||
|
||
self._sendDisconnect()
|
||
|
||
def __enter__(self):
|
||
return self
|
||
|
||
def __exit__(self, exc_type, exc_value, traceback):
|
||
if exc_type is not None and exc_value is not None:
|
||
logging.error(
|
||
f'An exception of type {exc_type} with value {exc_value} has occurred')
|
||
if traceback is not None:
|
||
logging.error(f'Traceback: {traceback}')
|
||
self.close()
|
||
|
||
def showInfo(self, file=sys.stdout):
|
||
"""Show human readable summary about this object"""
|
||
owner = f"Owner: {self.getLongName()} ({self.getShortName()})"
|
||
myinfo = ''
|
||
if self.myInfo:
|
||
myinfo = f"\nMy info: {stripnl(MessageToJson(self.myInfo))}"
|
||
mesh = "\nNodes in mesh:"
|
||
nodes = ""
|
||
if self.nodes:
|
||
for n in self.nodes.values():
|
||
nodes = nodes + f" {stripnl(n)}"
|
||
infos = owner + myinfo + mesh + nodes
|
||
print(infos)
|
||
return infos
|
||
|
||
def showNodes(self, includeSelf=True, file=sys.stdout):
|
||
"""Show table summary of nodes in mesh"""
|
||
def formatFloat(value, precision=2, unit=''):
|
||
"""Format a float value with precsion."""
|
||
return f'{value:.{precision}f}{unit}' if value else None
|
||
|
||
def getLH(ts):
|
||
"""Format last heard"""
|
||
return datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') if ts else None
|
||
|
||
def getTimeAgo(ts):
|
||
"""Format how long ago have we heard from this node (aka timeago)."""
|
||
return timeago.format(datetime.fromtimestamp(ts), datetime.now()) if ts else None
|
||
|
||
rows = []
|
||
if self.nodes:
|
||
logging.debug(f'self.nodes:{self.nodes}')
|
||
for node in self.nodes.values():
|
||
if not includeSelf and node['num'] == self.localNode.nodeNum:
|
||
continue
|
||
|
||
row = {"N": 0}
|
||
|
||
user = node.get('user')
|
||
if user:
|
||
row.update({
|
||
"User": user['longName'],
|
||
"AKA": user['shortName'],
|
||
"ID": user['id'],
|
||
})
|
||
|
||
pos = node.get('position')
|
||
if pos:
|
||
row.update({
|
||
"Latitude": formatFloat(pos.get("latitude"), 4, "°"),
|
||
"Longitude": formatFloat(pos.get("longitude"), 4, "°"),
|
||
"Altitude": formatFloat(pos.get("altitude"), 0, " m"),
|
||
"Battery": formatFloat(pos.get("batteryLevel"), 2, "%"),
|
||
})
|
||
|
||
row.update({
|
||
"SNR": formatFloat(node.get("snr"), 2, " dB"),
|
||
"LastHeard": getLH(node.get("lastHeard")),
|
||
"Since": getTimeAgo(node.get("lastHeard")),
|
||
})
|
||
|
||
rows.append(row)
|
||
|
||
rows.sort(key=lambda r: r.get('LastHeard') or '0000', reverse=True)
|
||
for i, row in enumerate(rows):
|
||
row['N'] = i+1
|
||
|
||
table = tabulate(rows, headers='keys', missingval='N/A', tablefmt='fancy_grid')
|
||
print(table)
|
||
return table
|
||
|
||
|
||
def getNode(self, nodeId):
|
||
"""Return a node object which contains device settings and channel info"""
|
||
if nodeId == LOCAL_ADDR:
|
||
return self.localNode
|
||
else:
|
||
n = meshtastic.node.Node(self, nodeId)
|
||
logging.debug("About to requestConfig")
|
||
n.requestConfig()
|
||
if not n.waitForConfig():
|
||
our_exit("Error: Timed out waiting for node config")
|
||
return n
|
||
|
||
def sendText(self, text: AnyStr,
|
||
destinationId=BROADCAST_ADDR,
|
||
wantAck=False,
|
||
wantResponse=False,
|
||
hopLimit=None,
|
||
onResponse=None,
|
||
channelIndex=0):
|
||
"""Send a utf8 string to some other node, if the node has a display it
|
||
will also be shown on the device.
|
||
|
||
Arguments:
|
||
text {string} -- The text to send
|
||
|
||
Keyword Arguments:
|
||
destinationId {nodeId or nodeNum} -- where to send this
|
||
message (default: {BROADCAST_ADDR})
|
||
portNum -- the application portnum (similar to IP port numbers)
|
||
of the destination, see portnums.proto for a list
|
||
wantAck -- True if you want the message sent in a reliable manner
|
||
(with retries and ack/nak provided for delivery)
|
||
wantResponse -- True if you want the service on the other side to
|
||
send an application layer response
|
||
|
||
Returns the sent packet. The id field will be populated in this packet
|
||
and can be used to track future message acks/naks.
|
||
"""
|
||
if hopLimit is None:
|
||
hopLimit = self.defaultHopLimit
|
||
|
||
return self.sendData(text.encode("utf-8"), destinationId,
|
||
portNum=portnums_pb2.PortNum.TEXT_MESSAGE_APP,
|
||
wantAck=wantAck,
|
||
wantResponse=wantResponse,
|
||
hopLimit=hopLimit,
|
||
onResponse=onResponse,
|
||
channelIndex=channelIndex)
|
||
|
||
def sendData(self, data, destinationId=BROADCAST_ADDR,
|
||
portNum=portnums_pb2.PortNum.PRIVATE_APP, wantAck=False,
|
||
wantResponse=False,
|
||
hopLimit=None,
|
||
onResponse=None,
|
||
channelIndex=0):
|
||
"""Send a data packet to some other node
|
||
|
||
Keyword Arguments:
|
||
data -- the data to send, either as an array of bytes or
|
||
as a protobuf (which will be automatically
|
||
serialized to bytes)
|
||
destinationId {nodeId or nodeNum} -- where to send this
|
||
message (default: {BROADCAST_ADDR})
|
||
portNum -- the application portnum (similar to IP port numbers)
|
||
of the destination, see portnums.proto for a list
|
||
wantAck -- True if you want the message sent in a reliable
|
||
manner (with retries and ack/nak provided for delivery)
|
||
wantResponse -- True if you want the service on the other
|
||
side to send an application layer response
|
||
onResponse -- A closure of the form funct(packet), that will be
|
||
called when a response packet arrives (or the transaction
|
||
is NAKed due to non receipt)
|
||
channelIndex - channel number to use
|
||
|
||
Returns the sent packet. The id field will be populated in this packet
|
||
and can be used to track future message acks/naks.
|
||
"""
|
||
if hopLimit is None:
|
||
hopLimit = self.defaultHopLimit
|
||
|
||
if getattr(data, "SerializeToString", None):
|
||
logging.debug(f"Serializing protobuf as data: {stripnl(data)}")
|
||
data = data.SerializeToString()
|
||
|
||
logging.debug(f"len(data): {len(data)}")
|
||
logging.debug(f"mesh_pb2.Constants.DATA_PAYLOAD_LEN: {mesh_pb2.Constants.DATA_PAYLOAD_LEN}")
|
||
if len(data) > mesh_pb2.Constants.DATA_PAYLOAD_LEN:
|
||
raise Exception("Data payload too big")
|
||
|
||
if portNum == portnums_pb2.PortNum.UNKNOWN_APP: # we are now more strict wrt port numbers
|
||
our_exit("Warning: A non-zero port number must be specified")
|
||
|
||
meshPacket = mesh_pb2.MeshPacket()
|
||
meshPacket.channel = channelIndex
|
||
meshPacket.decoded.payload = data
|
||
meshPacket.decoded.portnum = portNum
|
||
meshPacket.decoded.want_response = wantResponse
|
||
|
||
p = self._sendPacket(meshPacket, destinationId,
|
||
wantAck=wantAck, hopLimit=hopLimit)
|
||
if onResponse is not None:
|
||
self._addResponseHandler(p.id, onResponse)
|
||
return p
|
||
|
||
def sendPosition(self, latitude=0.0, longitude=0.0, altitude=0, timeSec=0,
|
||
destinationId=BROADCAST_ADDR, wantAck=False, wantResponse=False):
|
||
"""
|
||
Send a position packet to some other node (normally a broadcast)
|
||
|
||
Also, the device software will notice this packet and use it to automatically
|
||
set its notion of the local position.
|
||
|
||
If timeSec is not specified (recommended), we will use the local machine time.
|
||
|
||
Returns the sent packet. The id field will be populated in this packet and
|
||
can be used to track future message acks/naks.
|
||
"""
|
||
p = mesh_pb2.Position()
|
||
if latitude != 0.0:
|
||
p.latitude_i = int(latitude / 1e-7)
|
||
logging.debug(f'p.latitude_i:{p.latitude_i}')
|
||
|
||
if longitude != 0.0:
|
||
p.longitude_i = int(longitude / 1e-7)
|
||
logging.debug(f'p.longitude_i:{p.longitude_i}')
|
||
|
||
if altitude != 0:
|
||
p.altitude = int(altitude)
|
||
logging.debug(f'p.altitude:{p.altitude}')
|
||
|
||
if timeSec == 0:
|
||
timeSec = time.time() # returns unix timestamp in seconds
|
||
p.time = int(timeSec)
|
||
logging.debug(f'p.time:{p.time}')
|
||
|
||
return self.sendData(p, destinationId,
|
||
portNum=portnums_pb2.PortNum.POSITION_APP,
|
||
wantAck=wantAck,
|
||
wantResponse=wantResponse)
|
||
|
||
def _addResponseHandler(self, requestId, callback):
|
||
self.responseHandlers[requestId] = ResponseHandler(callback)
|
||
|
||
def _sendPacket(self, meshPacket,
|
||
destinationId=BROADCAST_ADDR,
|
||
wantAck=False, hopLimit=None):
|
||
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||
You probably don't want this - use sendData instead.
|
||
|
||
Returns the sent packet. The id field will be populated in this packet and
|
||
can be used to track future message acks/naks.
|
||
"""
|
||
if hopLimit is None:
|
||
hopLimit = self.defaultHopLimit
|
||
|
||
# We allow users to talk to the local node before we've completed the full connection flow...
|
||
if(self.myInfo is not None and destinationId != self.myInfo.my_node_num):
|
||
self._waitConnected()
|
||
|
||
toRadio = mesh_pb2.ToRadio()
|
||
|
||
nodeNum = 0
|
||
if destinationId is None:
|
||
our_exit("Warning: destinationId must not be None")
|
||
elif isinstance(destinationId, int):
|
||
nodeNum = destinationId
|
||
elif destinationId == BROADCAST_ADDR:
|
||
nodeNum = BROADCAST_NUM
|
||
elif destinationId == LOCAL_ADDR:
|
||
if self.myInfo:
|
||
nodeNum = self.myInfo.my_node_num
|
||
else:
|
||
our_exit("Warning: No myInfo found.")
|
||
# A simple hex style nodeid - we can parse this without needing the DB
|
||
elif destinationId.startswith("!"):
|
||
nodeNum = int(destinationId[1:], 16)
|
||
else:
|
||
if self.nodes:
|
||
node = self.nodes.get(destinationId)
|
||
if not node:
|
||
our_exit(f"Warning: NodeId {destinationId} not found in DB")
|
||
nodeNum = node['num']
|
||
else:
|
||
logging.warning("Warning: There were no self.nodes.")
|
||
|
||
meshPacket.to = nodeNum
|
||
meshPacket.want_ack = wantAck
|
||
meshPacket.hop_limit = hopLimit
|
||
|
||
# if the user hasn't set an ID for this packet (likely and recommended),
|
||
# we should pick a new unique ID so the message can be tracked.
|
||
if meshPacket.id == 0:
|
||
meshPacket.id = self._generatePacketId()
|
||
|
||
toRadio.packet.CopyFrom(meshPacket)
|
||
if self.noProto:
|
||
logging.warning(f"Not sending packet because protocol use is disabled by noProto")
|
||
else:
|
||
logging.debug(f"Sending packet: {stripnl(meshPacket)}")
|
||
self._sendToRadio(toRadio)
|
||
return meshPacket
|
||
|
||
def waitForConfig(self):
|
||
"""Block until radio config is received. Returns True if config has been received."""
|
||
success = self._timeout.waitForSet(self, attrs=('myInfo', 'nodes')) and self.localNode.waitForConfig()
|
||
if not success:
|
||
raise Exception("Timed out waiting for interface config")
|
||
|
||
def getMyNodeInfo(self):
|
||
"""Get info about my node."""
|
||
if self.myInfo is None:
|
||
return None
|
||
logging.debug(f'self.nodesByNum:{self.nodesByNum}')
|
||
return self.nodesByNum.get(self.myInfo.my_node_num)
|
||
|
||
def getMyUser(self):
|
||
"""Get user"""
|
||
nodeInfo = self.getMyNodeInfo()
|
||
if nodeInfo is not None:
|
||
return nodeInfo.get('user')
|
||
return None
|
||
|
||
def getLongName(self):
|
||
"""Get long name"""
|
||
user = self.getMyUser()
|
||
if user is not None:
|
||
return user.get('longName', None)
|
||
return None
|
||
|
||
def getShortName(self):
|
||
"""Get short name"""
|
||
user = self.getMyUser()
|
||
if user is not None:
|
||
return user.get('shortName', None)
|
||
return None
|
||
|
||
def _waitConnected(self):
|
||
"""Block until the initial node db download is complete, or timeout
|
||
and raise an exception"""
|
||
if not self.noProto:
|
||
if not self.isConnected.wait(15.0): # timeout after x seconds
|
||
raise Exception("Timed out waiting for connection completion")
|
||
|
||
# If we failed while connecting, raise the connection to the client
|
||
if self.failure:
|
||
raise self.failure
|
||
|
||
def _generatePacketId(self):
|
||
"""Get a new unique packet ID"""
|
||
if self.currentPacketId is None:
|
||
raise Exception("Not connected yet, can not generate packet")
|
||
else:
|
||
self.currentPacketId = (self.currentPacketId + 1) & 0xffffffff
|
||
return self.currentPacketId
|
||
|
||
def _disconnected(self):
|
||
"""Called by subclasses to tell clients this interface has disconnected"""
|
||
self.isConnected.clear()
|
||
publishingThread.queueWork(lambda: pub.sendMessage(
|
||
"meshtastic.connection.lost", interface=self))
|
||
|
||
def _startHeartbeat(self):
|
||
"""We need to send a heartbeat message to the device every X seconds"""
|
||
def callback():
|
||
self.heartbeatTimer = None
|
||
prefs = self.localNode.radioConfig.preferences
|
||
i = prefs.phone_timeout_secs / 2
|
||
logging.debug(f"Sending heartbeat, interval {i}")
|
||
if i != 0:
|
||
self.heartbeatTimer = threading.Timer(i, callback)
|
||
self.heartbeatTimer.start()
|
||
p = mesh_pb2.ToRadio()
|
||
self._sendToRadio(p)
|
||
|
||
callback() # run our periodic callback now, it will make another timer if necessary
|
||
|
||
def _connected(self):
|
||
"""Called by this class to tell clients we are now fully connected to a node
|
||
"""
|
||
# (because I'm lazy) _connected might be called when remote Node
|
||
# objects complete their config reads, don't generate redundant isConnected
|
||
# for the local interface
|
||
if not self.isConnected.is_set():
|
||
self.isConnected.set()
|
||
self._startHeartbeat()
|
||
publishingThread.queueWork(lambda: pub.sendMessage(
|
||
"meshtastic.connection.established", interface=self))
|
||
|
||
def _startConfig(self):
|
||
"""Start device packets flowing"""
|
||
self.myInfo = None
|
||
self.nodes = {} # nodes keyed by ID
|
||
self.nodesByNum = {} # nodes keyed by nodenum
|
||
|
||
startConfig = mesh_pb2.ToRadio()
|
||
self.configId = random.randint(0, 0xffffffff)
|
||
startConfig.want_config_id = self.configId
|
||
self._sendToRadio(startConfig)
|
||
|
||
def _sendDisconnect(self):
|
||
"""Tell device we are done using it"""
|
||
m = mesh_pb2.ToRadio()
|
||
m.disconnect = True
|
||
self._sendToRadio(m)
|
||
|
||
def _sendToRadio(self, toRadio):
|
||
"""Send a ToRadio protobuf to the device"""
|
||
if self.noProto:
|
||
logging.warning(f"Not sending packet because protocol use is disabled by noProto")
|
||
else:
|
||
#logging.debug(f"Sending toRadio: {stripnl(toRadio)}")
|
||
self._sendToRadioImpl(toRadio)
|
||
|
||
def _sendToRadioImpl(self, toRadio):
|
||
"""Send a ToRadio protobuf to the device"""
|
||
logging.error(f"Subclass must provide toradio: {toRadio}")
|
||
|
||
def _handleConfigComplete(self):
|
||
"""
|
||
Done with initial config messages, now send regular MeshPackets
|
||
to ask for settings and channels
|
||
"""
|
||
self.localNode.requestConfig()
|
||
|
||
def _handleFromRadio(self, fromRadioBytes):
|
||
"""
|
||
Handle a packet that arrived from the radio(update model and publish events)
|
||
|
||
Called by subclasses."""
|
||
fromRadio = mesh_pb2.FromRadio()
|
||
fromRadio.ParseFromString(fromRadioBytes)
|
||
logging.debug(f"in mesh_interface.py _handleFromRadio() fromRadioBytes: {fromRadioBytes}")
|
||
asDict = google.protobuf.json_format.MessageToDict(fromRadio)
|
||
logging.debug(f"Received from radio: {fromRadio}")
|
||
if fromRadio.HasField("my_info"):
|
||
self.myInfo = fromRadio.my_info
|
||
self.localNode.nodeNum = self.myInfo.my_node_num
|
||
logging.debug(f"Received myinfo: {stripnl(fromRadio.my_info)}")
|
||
|
||
failmsg = None
|
||
# Check for app too old
|
||
if self.myInfo.min_app_version > OUR_APP_VERSION:
|
||
failmsg = "This device needs a newer python client, run 'pip install --upgrade meshtastic'."\
|
||
"For more information see https://tinyurl.com/5bjsxu32"
|
||
|
||
# check for firmware too old
|
||
if self.myInfo.max_channels == 0:
|
||
failmsg = "This version of meshtastic-python requires device firmware version 1.2 or later. "\
|
||
"For more information see https://tinyurl.com/5bjsxu32"
|
||
|
||
if failmsg:
|
||
self.failure = Exception(failmsg)
|
||
self.isConnected.set() # let waitConnected return this exception
|
||
self.close()
|
||
|
||
elif fromRadio.HasField("node_info"):
|
||
node = asDict["nodeInfo"]
|
||
try:
|
||
self._fixupPosition(node["position"])
|
||
except:
|
||
logging.debug("Node without position")
|
||
|
||
logging.debug(f"Received nodeinfo: {node}")
|
||
|
||
self.nodesByNum[node["num"]] = node
|
||
if "user" in node: # Some nodes might not have user/ids assigned yet
|
||
if "id" in node["user"]:
|
||
self.nodes[node["user"]["id"]] = node
|
||
publishingThread.queueWork(lambda: pub.sendMessage("meshtastic.node.updated",
|
||
node=node, interface=self))
|
||
elif fromRadio.config_complete_id == self.configId:
|
||
# we ignore the config_complete_id, it is unneeded for our
|
||
# stream API fromRadio.config_complete_id
|
||
logging.debug(f"Config complete ID {self.configId}")
|
||
self._handleConfigComplete()
|
||
elif fromRadio.HasField("packet"):
|
||
self._handlePacketFromRadio(fromRadio.packet)
|
||
elif fromRadio.rebooted:
|
||
# Tell clients the device went away. Careful not to call the overridden
|
||
# subclass version that closes the serial port
|
||
MeshInterface._disconnected(self)
|
||
|
||
self._startConfig() # redownload the node db etc...
|
||
else:
|
||
logging.debug("Unexpected FromRadio payload")
|
||
|
||
def _fixupPosition(self, position):
|
||
"""Convert integer lat/lon into floats
|
||
|
||
Arguments:
|
||
position {Position dictionary} -- object ot fix up
|
||
"""
|
||
if "latitudeI" in position:
|
||
position["latitude"] = position["latitudeI"] * 1e-7
|
||
if "longitudeI" in position:
|
||
position["longitude"] = position["longitudeI"] * 1e-7
|
||
|
||
def _nodeNumToId(self, num):
|
||
"""Map a node node number to a node ID
|
||
|
||
Arguments:
|
||
num {int} -- Node number
|
||
|
||
Returns:
|
||
string -- Node ID
|
||
"""
|
||
if num == BROADCAST_NUM:
|
||
return BROADCAST_ADDR
|
||
|
||
try:
|
||
return self.nodesByNum[num]["user"]["id"]
|
||
except:
|
||
logging.debug(f"Node {num} not found for fromId")
|
||
return None
|
||
|
||
def _getOrCreateByNum(self, nodeNum):
|
||
"""Given a nodenum find the NodeInfo in the DB (or create if necessary)"""
|
||
if nodeNum == BROADCAST_NUM:
|
||
raise Exception("Can not create/find nodenum by the broadcast num")
|
||
|
||
if nodeNum in self.nodesByNum:
|
||
return self.nodesByNum[nodeNum]
|
||
else:
|
||
n = {"num": nodeNum} # Create a minimial node db entry
|
||
self.nodesByNum[nodeNum] = n
|
||
return n
|
||
|
||
def _handlePacketFromRadio(self, meshPacket, hack=False):
|
||
"""Handle a MeshPacket that just arrived from the radio
|
||
|
||
hack - well, since we used 'from', which is a python keyword,
|
||
as an attribute to MeshPacket in protobufs,
|
||
there really is no way to do something like this:
|
||
meshPacket = mesh_pb2.MeshPacket()
|
||
meshPacket.from = 123
|
||
If hack is True, we can unit test this code.
|
||
|
||
Will publish one of the following events:
|
||
- meshtastic.receive.text(packet = MeshPacket dictionary)
|
||
- meshtastic.receive.position(packet = MeshPacket dictionary)
|
||
- meshtastic.receive.user(packet = MeshPacket dictionary)
|
||
- meshtastic.receive.data(packet = MeshPacket dictionary)
|
||
"""
|
||
asDict = google.protobuf.json_format.MessageToDict(meshPacket)
|
||
|
||
# We normally decompose the payload into a dictionary so that the client
|
||
# doesn't need to understand protobufs. But advanced clients might
|
||
# want the raw protobuf, so we provide it in "raw"
|
||
asDict["raw"] = meshPacket
|
||
|
||
# from might be missing if the nodenum was zero.
|
||
if not hack and "from" not in asDict:
|
||
asDict["from"] = 0
|
||
logging.error(f"Device returned a packet we sent, ignoring: {stripnl(asDict)}")
|
||
print(f"Error: Device returned a packet we sent, ignoring: {stripnl(asDict)}")
|
||
return
|
||
if "to" not in asDict:
|
||
asDict["to"] = 0
|
||
|
||
# /add fromId and toId fields based on the node ID
|
||
try:
|
||
asDict["fromId"] = self._nodeNumToId(asDict["from"])
|
||
except Exception as ex:
|
||
logging.warning(f"Not populating fromId {ex}")
|
||
try:
|
||
asDict["toId"] = self._nodeNumToId(asDict["to"])
|
||
except Exception as ex:
|
||
logging.warning(f"Not populating toId {ex}")
|
||
|
||
# We could provide our objects as DotMaps - which work with . notation or as dictionaries
|
||
# asObj = DotMap(asDict)
|
||
topic = "meshtastic.receive" # Generic unknown packet type
|
||
|
||
decoded = asDict["decoded"]
|
||
# The default MessageToDict converts byte arrays into base64 strings.
|
||
# We don't want that - it messes up data payload. So slam in the correct
|
||
# byte array.
|
||
decoded["payload"] = meshPacket.decoded.payload
|
||
|
||
# UNKNOWN_APP is the default protobuf portnum value, and therefore if not
|
||
# set it will not be populated at all to make API usage easier, set
|
||
# it to prevent confusion
|
||
if "portnum" not in decoded:
|
||
new_portnum = portnums_pb2.PortNum.Name(portnums_pb2.PortNum.UNKNOWN_APP)
|
||
decoded["portnum"] = new_portnum
|
||
logging.warning(f"portnum was not in decoded. Setting to:{new_portnum}")
|
||
|
||
portnum = decoded["portnum"]
|
||
|
||
topic = f"meshtastic.receive.data.{portnum}"
|
||
|
||
# decode position protobufs and update nodedb, provide decoded version
|
||
# as "position" in the published msg move the following into a 'decoders'
|
||
# API that clients could register?
|
||
portNumInt = meshPacket.decoded.portnum # we want portnum as an int
|
||
handler = protocols.get(portNumInt)
|
||
# The decoded protobuf as a dictionary (if we understand this message)
|
||
p = None
|
||
if handler is not None:
|
||
topic = f"meshtastic.receive.{handler.name}"
|
||
|
||
# Convert to protobuf if possible
|
||
if handler.protobufFactory is not None:
|
||
pb = handler.protobufFactory()
|
||
pb.ParseFromString(meshPacket.decoded.payload)
|
||
p = google.protobuf.json_format.MessageToDict(pb)
|
||
asDict["decoded"][handler.name] = p
|
||
# Also provide the protobuf raw
|
||
asDict["decoded"][handler.name]["raw"] = pb
|
||
|
||
# Call specialized onReceive if necessary
|
||
if handler.onReceive is not None:
|
||
handler.onReceive(self, asDict)
|
||
|
||
# Is this message in response to a request, if so, look for a handler
|
||
requestId = decoded.get("requestId")
|
||
if requestId is not None:
|
||
# We ignore ACK packets, but send NAKs and data responses to the handlers
|
||
routing = decoded.get("routing")
|
||
isAck = routing is not None and ("errorReason" not in routing)
|
||
if not isAck:
|
||
# we keep the responseHandler in dict until we get a non ack
|
||
handler = self.responseHandlers.pop(requestId, None)
|
||
if handler is not None:
|
||
handler.callback(asDict)
|
||
|
||
logging.debug(f"Publishing {topic}: packet={stripnl(asDict)} ")
|
||
publishingThread.queueWork(lambda: pub.sendMessage(
|
||
topic, packet=asDict, interface=self))</code></pre>
|
||
</details>
|
||
</section>
|
||
<section>
|
||
</section>
|
||
<section>
|
||
</section>
|
||
<section>
|
||
</section>
|
||
<section>
|
||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||
<dl>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface"><code class="flex name class">
|
||
<span>class <span class="ident">MeshInterface</span></span>
|
||
<span>(</span><span>debugOut=None, noProto=False)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Interface class for meshtastic devices</p>
|
||
<p>Properties:</p>
|
||
<p>isConnected
|
||
nodes
|
||
debugOut</p>
|
||
<p>Constructor</p>
|
||
<p>Keyword Arguments:
|
||
noProto – If True, don't try to run our protocol on the
|
||
link - just be a dumb serial client.</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">class MeshInterface:
|
||
"""Interface class for meshtastic devices
|
||
|
||
Properties:
|
||
|
||
isConnected
|
||
nodes
|
||
debugOut
|
||
"""
|
||
|
||
def __init__(self, debugOut=None, noProto=False):
|
||
"""Constructor
|
||
|
||
Keyword Arguments:
|
||
noProto -- If True, don't try to run our protocol on the
|
||
link - just be a dumb serial client.
|
||
"""
|
||
self.debugOut = debugOut
|
||
self.nodes = None # FIXME
|
||
self.isConnected = threading.Event()
|
||
self.noProto = noProto
|
||
self.localNode = meshtastic.node.Node(self, -1) # We fixup nodenum later
|
||
self.myInfo = None # We don't have device info yet
|
||
self.responseHandlers = {} # A map from request ID to the handler
|
||
self.failure = None # If we've encountered a fatal exception it will be kept here
|
||
self._timeout = Timeout()
|
||
self.heartbeatTimer = None
|
||
random.seed() # FIXME, we should not clobber the random seedval here, instead tell user they must call it
|
||
self.currentPacketId = random.randint(0, 0xffffffff)
|
||
self.nodesByNum = None
|
||
self.configId = None
|
||
self.defaultHopLimit = 3
|
||
self.gotResponse = False # used in gpio read
|
||
self.mask = None # used in gpio read and gpio watch
|
||
|
||
def close(self):
|
||
"""Shutdown this interface"""
|
||
if self.heartbeatTimer:
|
||
self.heartbeatTimer.cancel()
|
||
|
||
self._sendDisconnect()
|
||
|
||
def __enter__(self):
|
||
return self
|
||
|
||
def __exit__(self, exc_type, exc_value, traceback):
|
||
if exc_type is not None and exc_value is not None:
|
||
logging.error(
|
||
f'An exception of type {exc_type} with value {exc_value} has occurred')
|
||
if traceback is not None:
|
||
logging.error(f'Traceback: {traceback}')
|
||
self.close()
|
||
|
||
def showInfo(self, file=sys.stdout):
|
||
"""Show human readable summary about this object"""
|
||
owner = f"Owner: {self.getLongName()} ({self.getShortName()})"
|
||
myinfo = ''
|
||
if self.myInfo:
|
||
myinfo = f"\nMy info: {stripnl(MessageToJson(self.myInfo))}"
|
||
mesh = "\nNodes in mesh:"
|
||
nodes = ""
|
||
if self.nodes:
|
||
for n in self.nodes.values():
|
||
nodes = nodes + f" {stripnl(n)}"
|
||
infos = owner + myinfo + mesh + nodes
|
||
print(infos)
|
||
return infos
|
||
|
||
def showNodes(self, includeSelf=True, file=sys.stdout):
|
||
"""Show table summary of nodes in mesh"""
|
||
def formatFloat(value, precision=2, unit=''):
|
||
"""Format a float value with precsion."""
|
||
return f'{value:.{precision}f}{unit}' if value else None
|
||
|
||
def getLH(ts):
|
||
"""Format last heard"""
|
||
return datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') if ts else None
|
||
|
||
def getTimeAgo(ts):
|
||
"""Format how long ago have we heard from this node (aka timeago)."""
|
||
return timeago.format(datetime.fromtimestamp(ts), datetime.now()) if ts else None
|
||
|
||
rows = []
|
||
if self.nodes:
|
||
logging.debug(f'self.nodes:{self.nodes}')
|
||
for node in self.nodes.values():
|
||
if not includeSelf and node['num'] == self.localNode.nodeNum:
|
||
continue
|
||
|
||
row = {"N": 0}
|
||
|
||
user = node.get('user')
|
||
if user:
|
||
row.update({
|
||
"User": user['longName'],
|
||
"AKA": user['shortName'],
|
||
"ID": user['id'],
|
||
})
|
||
|
||
pos = node.get('position')
|
||
if pos:
|
||
row.update({
|
||
"Latitude": formatFloat(pos.get("latitude"), 4, "°"),
|
||
"Longitude": formatFloat(pos.get("longitude"), 4, "°"),
|
||
"Altitude": formatFloat(pos.get("altitude"), 0, " m"),
|
||
"Battery": formatFloat(pos.get("batteryLevel"), 2, "%"),
|
||
})
|
||
|
||
row.update({
|
||
"SNR": formatFloat(node.get("snr"), 2, " dB"),
|
||
"LastHeard": getLH(node.get("lastHeard")),
|
||
"Since": getTimeAgo(node.get("lastHeard")),
|
||
})
|
||
|
||
rows.append(row)
|
||
|
||
rows.sort(key=lambda r: r.get('LastHeard') or '0000', reverse=True)
|
||
for i, row in enumerate(rows):
|
||
row['N'] = i+1
|
||
|
||
table = tabulate(rows, headers='keys', missingval='N/A', tablefmt='fancy_grid')
|
||
print(table)
|
||
return table
|
||
|
||
|
||
def getNode(self, nodeId):
|
||
"""Return a node object which contains device settings and channel info"""
|
||
if nodeId == LOCAL_ADDR:
|
||
return self.localNode
|
||
else:
|
||
n = meshtastic.node.Node(self, nodeId)
|
||
logging.debug("About to requestConfig")
|
||
n.requestConfig()
|
||
if not n.waitForConfig():
|
||
our_exit("Error: Timed out waiting for node config")
|
||
return n
|
||
|
||
def sendText(self, text: AnyStr,
|
||
destinationId=BROADCAST_ADDR,
|
||
wantAck=False,
|
||
wantResponse=False,
|
||
hopLimit=None,
|
||
onResponse=None,
|
||
channelIndex=0):
|
||
"""Send a utf8 string to some other node, if the node has a display it
|
||
will also be shown on the device.
|
||
|
||
Arguments:
|
||
text {string} -- The text to send
|
||
|
||
Keyword Arguments:
|
||
destinationId {nodeId or nodeNum} -- where to send this
|
||
message (default: {BROADCAST_ADDR})
|
||
portNum -- the application portnum (similar to IP port numbers)
|
||
of the destination, see portnums.proto for a list
|
||
wantAck -- True if you want the message sent in a reliable manner
|
||
(with retries and ack/nak provided for delivery)
|
||
wantResponse -- True if you want the service on the other side to
|
||
send an application layer response
|
||
|
||
Returns the sent packet. The id field will be populated in this packet
|
||
and can be used to track future message acks/naks.
|
||
"""
|
||
if hopLimit is None:
|
||
hopLimit = self.defaultHopLimit
|
||
|
||
return self.sendData(text.encode("utf-8"), destinationId,
|
||
portNum=portnums_pb2.PortNum.TEXT_MESSAGE_APP,
|
||
wantAck=wantAck,
|
||
wantResponse=wantResponse,
|
||
hopLimit=hopLimit,
|
||
onResponse=onResponse,
|
||
channelIndex=channelIndex)
|
||
|
||
def sendData(self, data, destinationId=BROADCAST_ADDR,
|
||
portNum=portnums_pb2.PortNum.PRIVATE_APP, wantAck=False,
|
||
wantResponse=False,
|
||
hopLimit=None,
|
||
onResponse=None,
|
||
channelIndex=0):
|
||
"""Send a data packet to some other node
|
||
|
||
Keyword Arguments:
|
||
data -- the data to send, either as an array of bytes or
|
||
as a protobuf (which will be automatically
|
||
serialized to bytes)
|
||
destinationId {nodeId or nodeNum} -- where to send this
|
||
message (default: {BROADCAST_ADDR})
|
||
portNum -- the application portnum (similar to IP port numbers)
|
||
of the destination, see portnums.proto for a list
|
||
wantAck -- True if you want the message sent in a reliable
|
||
manner (with retries and ack/nak provided for delivery)
|
||
wantResponse -- True if you want the service on the other
|
||
side to send an application layer response
|
||
onResponse -- A closure of the form funct(packet), that will be
|
||
called when a response packet arrives (or the transaction
|
||
is NAKed due to non receipt)
|
||
channelIndex - channel number to use
|
||
|
||
Returns the sent packet. The id field will be populated in this packet
|
||
and can be used to track future message acks/naks.
|
||
"""
|
||
if hopLimit is None:
|
||
hopLimit = self.defaultHopLimit
|
||
|
||
if getattr(data, "SerializeToString", None):
|
||
logging.debug(f"Serializing protobuf as data: {stripnl(data)}")
|
||
data = data.SerializeToString()
|
||
|
||
logging.debug(f"len(data): {len(data)}")
|
||
logging.debug(f"mesh_pb2.Constants.DATA_PAYLOAD_LEN: {mesh_pb2.Constants.DATA_PAYLOAD_LEN}")
|
||
if len(data) > mesh_pb2.Constants.DATA_PAYLOAD_LEN:
|
||
raise Exception("Data payload too big")
|
||
|
||
if portNum == portnums_pb2.PortNum.UNKNOWN_APP: # we are now more strict wrt port numbers
|
||
our_exit("Warning: A non-zero port number must be specified")
|
||
|
||
meshPacket = mesh_pb2.MeshPacket()
|
||
meshPacket.channel = channelIndex
|
||
meshPacket.decoded.payload = data
|
||
meshPacket.decoded.portnum = portNum
|
||
meshPacket.decoded.want_response = wantResponse
|
||
|
||
p = self._sendPacket(meshPacket, destinationId,
|
||
wantAck=wantAck, hopLimit=hopLimit)
|
||
if onResponse is not None:
|
||
self._addResponseHandler(p.id, onResponse)
|
||
return p
|
||
|
||
def sendPosition(self, latitude=0.0, longitude=0.0, altitude=0, timeSec=0,
|
||
destinationId=BROADCAST_ADDR, wantAck=False, wantResponse=False):
|
||
"""
|
||
Send a position packet to some other node (normally a broadcast)
|
||
|
||
Also, the device software will notice this packet and use it to automatically
|
||
set its notion of the local position.
|
||
|
||
If timeSec is not specified (recommended), we will use the local machine time.
|
||
|
||
Returns the sent packet. The id field will be populated in this packet and
|
||
can be used to track future message acks/naks.
|
||
"""
|
||
p = mesh_pb2.Position()
|
||
if latitude != 0.0:
|
||
p.latitude_i = int(latitude / 1e-7)
|
||
logging.debug(f'p.latitude_i:{p.latitude_i}')
|
||
|
||
if longitude != 0.0:
|
||
p.longitude_i = int(longitude / 1e-7)
|
||
logging.debug(f'p.longitude_i:{p.longitude_i}')
|
||
|
||
if altitude != 0:
|
||
p.altitude = int(altitude)
|
||
logging.debug(f'p.altitude:{p.altitude}')
|
||
|
||
if timeSec == 0:
|
||
timeSec = time.time() # returns unix timestamp in seconds
|
||
p.time = int(timeSec)
|
||
logging.debug(f'p.time:{p.time}')
|
||
|
||
return self.sendData(p, destinationId,
|
||
portNum=portnums_pb2.PortNum.POSITION_APP,
|
||
wantAck=wantAck,
|
||
wantResponse=wantResponse)
|
||
|
||
def _addResponseHandler(self, requestId, callback):
|
||
self.responseHandlers[requestId] = ResponseHandler(callback)
|
||
|
||
def _sendPacket(self, meshPacket,
|
||
destinationId=BROADCAST_ADDR,
|
||
wantAck=False, hopLimit=None):
|
||
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||
You probably don't want this - use sendData instead.
|
||
|
||
Returns the sent packet. The id field will be populated in this packet and
|
||
can be used to track future message acks/naks.
|
||
"""
|
||
if hopLimit is None:
|
||
hopLimit = self.defaultHopLimit
|
||
|
||
# We allow users to talk to the local node before we've completed the full connection flow...
|
||
if(self.myInfo is not None and destinationId != self.myInfo.my_node_num):
|
||
self._waitConnected()
|
||
|
||
toRadio = mesh_pb2.ToRadio()
|
||
|
||
nodeNum = 0
|
||
if destinationId is None:
|
||
our_exit("Warning: destinationId must not be None")
|
||
elif isinstance(destinationId, int):
|
||
nodeNum = destinationId
|
||
elif destinationId == BROADCAST_ADDR:
|
||
nodeNum = BROADCAST_NUM
|
||
elif destinationId == LOCAL_ADDR:
|
||
if self.myInfo:
|
||
nodeNum = self.myInfo.my_node_num
|
||
else:
|
||
our_exit("Warning: No myInfo found.")
|
||
# A simple hex style nodeid - we can parse this without needing the DB
|
||
elif destinationId.startswith("!"):
|
||
nodeNum = int(destinationId[1:], 16)
|
||
else:
|
||
if self.nodes:
|
||
node = self.nodes.get(destinationId)
|
||
if not node:
|
||
our_exit(f"Warning: NodeId {destinationId} not found in DB")
|
||
nodeNum = node['num']
|
||
else:
|
||
logging.warning("Warning: There were no self.nodes.")
|
||
|
||
meshPacket.to = nodeNum
|
||
meshPacket.want_ack = wantAck
|
||
meshPacket.hop_limit = hopLimit
|
||
|
||
# if the user hasn't set an ID for this packet (likely and recommended),
|
||
# we should pick a new unique ID so the message can be tracked.
|
||
if meshPacket.id == 0:
|
||
meshPacket.id = self._generatePacketId()
|
||
|
||
toRadio.packet.CopyFrom(meshPacket)
|
||
if self.noProto:
|
||
logging.warning(f"Not sending packet because protocol use is disabled by noProto")
|
||
else:
|
||
logging.debug(f"Sending packet: {stripnl(meshPacket)}")
|
||
self._sendToRadio(toRadio)
|
||
return meshPacket
|
||
|
||
def waitForConfig(self):
|
||
"""Block until radio config is received. Returns True if config has been received."""
|
||
success = self._timeout.waitForSet(self, attrs=('myInfo', 'nodes')) and self.localNode.waitForConfig()
|
||
if not success:
|
||
raise Exception("Timed out waiting for interface config")
|
||
|
||
def getMyNodeInfo(self):
|
||
"""Get info about my node."""
|
||
if self.myInfo is None:
|
||
return None
|
||
logging.debug(f'self.nodesByNum:{self.nodesByNum}')
|
||
return self.nodesByNum.get(self.myInfo.my_node_num)
|
||
|
||
def getMyUser(self):
|
||
"""Get user"""
|
||
nodeInfo = self.getMyNodeInfo()
|
||
if nodeInfo is not None:
|
||
return nodeInfo.get('user')
|
||
return None
|
||
|
||
def getLongName(self):
|
||
"""Get long name"""
|
||
user = self.getMyUser()
|
||
if user is not None:
|
||
return user.get('longName', None)
|
||
return None
|
||
|
||
def getShortName(self):
|
||
"""Get short name"""
|
||
user = self.getMyUser()
|
||
if user is not None:
|
||
return user.get('shortName', None)
|
||
return None
|
||
|
||
def _waitConnected(self):
|
||
"""Block until the initial node db download is complete, or timeout
|
||
and raise an exception"""
|
||
if not self.noProto:
|
||
if not self.isConnected.wait(15.0): # timeout after x seconds
|
||
raise Exception("Timed out waiting for connection completion")
|
||
|
||
# If we failed while connecting, raise the connection to the client
|
||
if self.failure:
|
||
raise self.failure
|
||
|
||
def _generatePacketId(self):
|
||
"""Get a new unique packet ID"""
|
||
if self.currentPacketId is None:
|
||
raise Exception("Not connected yet, can not generate packet")
|
||
else:
|
||
self.currentPacketId = (self.currentPacketId + 1) & 0xffffffff
|
||
return self.currentPacketId
|
||
|
||
def _disconnected(self):
|
||
"""Called by subclasses to tell clients this interface has disconnected"""
|
||
self.isConnected.clear()
|
||
publishingThread.queueWork(lambda: pub.sendMessage(
|
||
"meshtastic.connection.lost", interface=self))
|
||
|
||
def _startHeartbeat(self):
|
||
"""We need to send a heartbeat message to the device every X seconds"""
|
||
def callback():
|
||
self.heartbeatTimer = None
|
||
prefs = self.localNode.radioConfig.preferences
|
||
i = prefs.phone_timeout_secs / 2
|
||
logging.debug(f"Sending heartbeat, interval {i}")
|
||
if i != 0:
|
||
self.heartbeatTimer = threading.Timer(i, callback)
|
||
self.heartbeatTimer.start()
|
||
p = mesh_pb2.ToRadio()
|
||
self._sendToRadio(p)
|
||
|
||
callback() # run our periodic callback now, it will make another timer if necessary
|
||
|
||
def _connected(self):
|
||
"""Called by this class to tell clients we are now fully connected to a node
|
||
"""
|
||
# (because I'm lazy) _connected might be called when remote Node
|
||
# objects complete their config reads, don't generate redundant isConnected
|
||
# for the local interface
|
||
if not self.isConnected.is_set():
|
||
self.isConnected.set()
|
||
self._startHeartbeat()
|
||
publishingThread.queueWork(lambda: pub.sendMessage(
|
||
"meshtastic.connection.established", interface=self))
|
||
|
||
def _startConfig(self):
|
||
"""Start device packets flowing"""
|
||
self.myInfo = None
|
||
self.nodes = {} # nodes keyed by ID
|
||
self.nodesByNum = {} # nodes keyed by nodenum
|
||
|
||
startConfig = mesh_pb2.ToRadio()
|
||
self.configId = random.randint(0, 0xffffffff)
|
||
startConfig.want_config_id = self.configId
|
||
self._sendToRadio(startConfig)
|
||
|
||
def _sendDisconnect(self):
|
||
"""Tell device we are done using it"""
|
||
m = mesh_pb2.ToRadio()
|
||
m.disconnect = True
|
||
self._sendToRadio(m)
|
||
|
||
def _sendToRadio(self, toRadio):
|
||
"""Send a ToRadio protobuf to the device"""
|
||
if self.noProto:
|
||
logging.warning(f"Not sending packet because protocol use is disabled by noProto")
|
||
else:
|
||
#logging.debug(f"Sending toRadio: {stripnl(toRadio)}")
|
||
self._sendToRadioImpl(toRadio)
|
||
|
||
def _sendToRadioImpl(self, toRadio):
|
||
"""Send a ToRadio protobuf to the device"""
|
||
logging.error(f"Subclass must provide toradio: {toRadio}")
|
||
|
||
def _handleConfigComplete(self):
|
||
"""
|
||
Done with initial config messages, now send regular MeshPackets
|
||
to ask for settings and channels
|
||
"""
|
||
self.localNode.requestConfig()
|
||
|
||
def _handleFromRadio(self, fromRadioBytes):
|
||
"""
|
||
Handle a packet that arrived from the radio(update model and publish events)
|
||
|
||
Called by subclasses."""
|
||
fromRadio = mesh_pb2.FromRadio()
|
||
fromRadio.ParseFromString(fromRadioBytes)
|
||
logging.debug(f"in mesh_interface.py _handleFromRadio() fromRadioBytes: {fromRadioBytes}")
|
||
asDict = google.protobuf.json_format.MessageToDict(fromRadio)
|
||
logging.debug(f"Received from radio: {fromRadio}")
|
||
if fromRadio.HasField("my_info"):
|
||
self.myInfo = fromRadio.my_info
|
||
self.localNode.nodeNum = self.myInfo.my_node_num
|
||
logging.debug(f"Received myinfo: {stripnl(fromRadio.my_info)}")
|
||
|
||
failmsg = None
|
||
# Check for app too old
|
||
if self.myInfo.min_app_version > OUR_APP_VERSION:
|
||
failmsg = "This device needs a newer python client, run 'pip install --upgrade meshtastic'."\
|
||
"For more information see https://tinyurl.com/5bjsxu32"
|
||
|
||
# check for firmware too old
|
||
if self.myInfo.max_channels == 0:
|
||
failmsg = "This version of meshtastic-python requires device firmware version 1.2 or later. "\
|
||
"For more information see https://tinyurl.com/5bjsxu32"
|
||
|
||
if failmsg:
|
||
self.failure = Exception(failmsg)
|
||
self.isConnected.set() # let waitConnected return this exception
|
||
self.close()
|
||
|
||
elif fromRadio.HasField("node_info"):
|
||
node = asDict["nodeInfo"]
|
||
try:
|
||
self._fixupPosition(node["position"])
|
||
except:
|
||
logging.debug("Node without position")
|
||
|
||
logging.debug(f"Received nodeinfo: {node}")
|
||
|
||
self.nodesByNum[node["num"]] = node
|
||
if "user" in node: # Some nodes might not have user/ids assigned yet
|
||
if "id" in node["user"]:
|
||
self.nodes[node["user"]["id"]] = node
|
||
publishingThread.queueWork(lambda: pub.sendMessage("meshtastic.node.updated",
|
||
node=node, interface=self))
|
||
elif fromRadio.config_complete_id == self.configId:
|
||
# we ignore the config_complete_id, it is unneeded for our
|
||
# stream API fromRadio.config_complete_id
|
||
logging.debug(f"Config complete ID {self.configId}")
|
||
self._handleConfigComplete()
|
||
elif fromRadio.HasField("packet"):
|
||
self._handlePacketFromRadio(fromRadio.packet)
|
||
elif fromRadio.rebooted:
|
||
# Tell clients the device went away. Careful not to call the overridden
|
||
# subclass version that closes the serial port
|
||
MeshInterface._disconnected(self)
|
||
|
||
self._startConfig() # redownload the node db etc...
|
||
else:
|
||
logging.debug("Unexpected FromRadio payload")
|
||
|
||
def _fixupPosition(self, position):
|
||
"""Convert integer lat/lon into floats
|
||
|
||
Arguments:
|
||
position {Position dictionary} -- object ot fix up
|
||
"""
|
||
if "latitudeI" in position:
|
||
position["latitude"] = position["latitudeI"] * 1e-7
|
||
if "longitudeI" in position:
|
||
position["longitude"] = position["longitudeI"] * 1e-7
|
||
|
||
def _nodeNumToId(self, num):
|
||
"""Map a node node number to a node ID
|
||
|
||
Arguments:
|
||
num {int} -- Node number
|
||
|
||
Returns:
|
||
string -- Node ID
|
||
"""
|
||
if num == BROADCAST_NUM:
|
||
return BROADCAST_ADDR
|
||
|
||
try:
|
||
return self.nodesByNum[num]["user"]["id"]
|
||
except:
|
||
logging.debug(f"Node {num} not found for fromId")
|
||
return None
|
||
|
||
def _getOrCreateByNum(self, nodeNum):
|
||
"""Given a nodenum find the NodeInfo in the DB (or create if necessary)"""
|
||
if nodeNum == BROADCAST_NUM:
|
||
raise Exception("Can not create/find nodenum by the broadcast num")
|
||
|
||
if nodeNum in self.nodesByNum:
|
||
return self.nodesByNum[nodeNum]
|
||
else:
|
||
n = {"num": nodeNum} # Create a minimial node db entry
|
||
self.nodesByNum[nodeNum] = n
|
||
return n
|
||
|
||
def _handlePacketFromRadio(self, meshPacket, hack=False):
|
||
"""Handle a MeshPacket that just arrived from the radio
|
||
|
||
hack - well, since we used 'from', which is a python keyword,
|
||
as an attribute to MeshPacket in protobufs,
|
||
there really is no way to do something like this:
|
||
meshPacket = mesh_pb2.MeshPacket()
|
||
meshPacket.from = 123
|
||
If hack is True, we can unit test this code.
|
||
|
||
Will publish one of the following events:
|
||
- meshtastic.receive.text(packet = MeshPacket dictionary)
|
||
- meshtastic.receive.position(packet = MeshPacket dictionary)
|
||
- meshtastic.receive.user(packet = MeshPacket dictionary)
|
||
- meshtastic.receive.data(packet = MeshPacket dictionary)
|
||
"""
|
||
asDict = google.protobuf.json_format.MessageToDict(meshPacket)
|
||
|
||
# We normally decompose the payload into a dictionary so that the client
|
||
# doesn't need to understand protobufs. But advanced clients might
|
||
# want the raw protobuf, so we provide it in "raw"
|
||
asDict["raw"] = meshPacket
|
||
|
||
# from might be missing if the nodenum was zero.
|
||
if not hack and "from" not in asDict:
|
||
asDict["from"] = 0
|
||
logging.error(f"Device returned a packet we sent, ignoring: {stripnl(asDict)}")
|
||
print(f"Error: Device returned a packet we sent, ignoring: {stripnl(asDict)}")
|
||
return
|
||
if "to" not in asDict:
|
||
asDict["to"] = 0
|
||
|
||
# /add fromId and toId fields based on the node ID
|
||
try:
|
||
asDict["fromId"] = self._nodeNumToId(asDict["from"])
|
||
except Exception as ex:
|
||
logging.warning(f"Not populating fromId {ex}")
|
||
try:
|
||
asDict["toId"] = self._nodeNumToId(asDict["to"])
|
||
except Exception as ex:
|
||
logging.warning(f"Not populating toId {ex}")
|
||
|
||
# We could provide our objects as DotMaps - which work with . notation or as dictionaries
|
||
# asObj = DotMap(asDict)
|
||
topic = "meshtastic.receive" # Generic unknown packet type
|
||
|
||
decoded = asDict["decoded"]
|
||
# The default MessageToDict converts byte arrays into base64 strings.
|
||
# We don't want that - it messes up data payload. So slam in the correct
|
||
# byte array.
|
||
decoded["payload"] = meshPacket.decoded.payload
|
||
|
||
# UNKNOWN_APP is the default protobuf portnum value, and therefore if not
|
||
# set it will not be populated at all to make API usage easier, set
|
||
# it to prevent confusion
|
||
if "portnum" not in decoded:
|
||
new_portnum = portnums_pb2.PortNum.Name(portnums_pb2.PortNum.UNKNOWN_APP)
|
||
decoded["portnum"] = new_portnum
|
||
logging.warning(f"portnum was not in decoded. Setting to:{new_portnum}")
|
||
|
||
portnum = decoded["portnum"]
|
||
|
||
topic = f"meshtastic.receive.data.{portnum}"
|
||
|
||
# decode position protobufs and update nodedb, provide decoded version
|
||
# as "position" in the published msg move the following into a 'decoders'
|
||
# API that clients could register?
|
||
portNumInt = meshPacket.decoded.portnum # we want portnum as an int
|
||
handler = protocols.get(portNumInt)
|
||
# The decoded protobuf as a dictionary (if we understand this message)
|
||
p = None
|
||
if handler is not None:
|
||
topic = f"meshtastic.receive.{handler.name}"
|
||
|
||
# Convert to protobuf if possible
|
||
if handler.protobufFactory is not None:
|
||
pb = handler.protobufFactory()
|
||
pb.ParseFromString(meshPacket.decoded.payload)
|
||
p = google.protobuf.json_format.MessageToDict(pb)
|
||
asDict["decoded"][handler.name] = p
|
||
# Also provide the protobuf raw
|
||
asDict["decoded"][handler.name]["raw"] = pb
|
||
|
||
# Call specialized onReceive if necessary
|
||
if handler.onReceive is not None:
|
||
handler.onReceive(self, asDict)
|
||
|
||
# Is this message in response to a request, if so, look for a handler
|
||
requestId = decoded.get("requestId")
|
||
if requestId is not None:
|
||
# We ignore ACK packets, but send NAKs and data responses to the handlers
|
||
routing = decoded.get("routing")
|
||
isAck = routing is not None and ("errorReason" not in routing)
|
||
if not isAck:
|
||
# we keep the responseHandler in dict until we get a non ack
|
||
handler = self.responseHandlers.pop(requestId, None)
|
||
if handler is not None:
|
||
handler.callback(asDict)
|
||
|
||
logging.debug(f"Publishing {topic}: packet={stripnl(asDict)} ")
|
||
publishingThread.queueWork(lambda: pub.sendMessage(
|
||
topic, packet=asDict, interface=self))</code></pre>
|
||
</details>
|
||
<h3>Subclasses</h3>
|
||
<ul class="hlist">
|
||
<li><a title="meshtastic.ble_interface.BLEInterface" href="ble_interface.html#meshtastic.ble_interface.BLEInterface">BLEInterface</a></li>
|
||
<li><a title="meshtastic.stream_interface.StreamInterface" href="stream_interface.html#meshtastic.stream_interface.StreamInterface">StreamInterface</a></li>
|
||
</ul>
|
||
<h3>Methods</h3>
|
||
<dl>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.close"><code class="name flex">
|
||
<span>def <span class="ident">close</span></span>(<span>self)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Shutdown this interface</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def close(self):
|
||
"""Shutdown this interface"""
|
||
if self.heartbeatTimer:
|
||
self.heartbeatTimer.cancel()
|
||
|
||
self._sendDisconnect()</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.getLongName"><code class="name flex">
|
||
<span>def <span class="ident">getLongName</span></span>(<span>self)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Get long name</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def getLongName(self):
|
||
"""Get long name"""
|
||
user = self.getMyUser()
|
||
if user is not None:
|
||
return user.get('longName', None)
|
||
return None</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.getMyNodeInfo"><code class="name flex">
|
||
<span>def <span class="ident">getMyNodeInfo</span></span>(<span>self)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Get info about my node.</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def getMyNodeInfo(self):
|
||
"""Get info about my node."""
|
||
if self.myInfo is None:
|
||
return None
|
||
logging.debug(f'self.nodesByNum:{self.nodesByNum}')
|
||
return self.nodesByNum.get(self.myInfo.my_node_num)</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.getMyUser"><code class="name flex">
|
||
<span>def <span class="ident">getMyUser</span></span>(<span>self)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Get user</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def getMyUser(self):
|
||
"""Get user"""
|
||
nodeInfo = self.getMyNodeInfo()
|
||
if nodeInfo is not None:
|
||
return nodeInfo.get('user')
|
||
return None</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.getNode"><code class="name flex">
|
||
<span>def <span class="ident">getNode</span></span>(<span>self, nodeId)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Return a node object which contains device settings and channel info</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def getNode(self, nodeId):
|
||
"""Return a node object which contains device settings and channel info"""
|
||
if nodeId == LOCAL_ADDR:
|
||
return self.localNode
|
||
else:
|
||
n = meshtastic.node.Node(self, nodeId)
|
||
logging.debug("About to requestConfig")
|
||
n.requestConfig()
|
||
if not n.waitForConfig():
|
||
our_exit("Error: Timed out waiting for node config")
|
||
return n</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.getShortName"><code class="name flex">
|
||
<span>def <span class="ident">getShortName</span></span>(<span>self)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Get short name</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def getShortName(self):
|
||
"""Get short name"""
|
||
user = self.getMyUser()
|
||
if user is not None:
|
||
return user.get('shortName', None)
|
||
return None</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.sendData"><code class="name flex">
|
||
<span>def <span class="ident">sendData</span></span>(<span>self, data, destinationId='^all', portNum=256, wantAck=False, wantResponse=False, hopLimit=None, onResponse=None, channelIndex=0)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Send a data packet to some other node</p>
|
||
<p>Keyword Arguments:
|
||
data – the data to send, either as an array of bytes or
|
||
as a protobuf (which will be automatically
|
||
serialized to bytes)
|
||
destinationId {nodeId or nodeNum} – where to send this
|
||
message (default: {BROADCAST_ADDR})
|
||
portNum – the application portnum (similar to IP port numbers)
|
||
of the destination, see portnums.proto for a list
|
||
wantAck – True if you want the message sent in a reliable
|
||
manner (with retries and ack/nak provided for delivery)
|
||
wantResponse – True if you want the service on the other
|
||
side to send an application layer response
|
||
onResponse – A closure of the form funct(packet), that will be
|
||
called when a response packet arrives (or the transaction
|
||
is NAKed due to non receipt)
|
||
channelIndex - channel number to use</p>
|
||
<p>Returns the sent packet. The id field will be populated in this packet
|
||
and can be used to track future message acks/naks.</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def sendData(self, data, destinationId=BROADCAST_ADDR,
|
||
portNum=portnums_pb2.PortNum.PRIVATE_APP, wantAck=False,
|
||
wantResponse=False,
|
||
hopLimit=None,
|
||
onResponse=None,
|
||
channelIndex=0):
|
||
"""Send a data packet to some other node
|
||
|
||
Keyword Arguments:
|
||
data -- the data to send, either as an array of bytes or
|
||
as a protobuf (which will be automatically
|
||
serialized to bytes)
|
||
destinationId {nodeId or nodeNum} -- where to send this
|
||
message (default: {BROADCAST_ADDR})
|
||
portNum -- the application portnum (similar to IP port numbers)
|
||
of the destination, see portnums.proto for a list
|
||
wantAck -- True if you want the message sent in a reliable
|
||
manner (with retries and ack/nak provided for delivery)
|
||
wantResponse -- True if you want the service on the other
|
||
side to send an application layer response
|
||
onResponse -- A closure of the form funct(packet), that will be
|
||
called when a response packet arrives (or the transaction
|
||
is NAKed due to non receipt)
|
||
channelIndex - channel number to use
|
||
|
||
Returns the sent packet. The id field will be populated in this packet
|
||
and can be used to track future message acks/naks.
|
||
"""
|
||
if hopLimit is None:
|
||
hopLimit = self.defaultHopLimit
|
||
|
||
if getattr(data, "SerializeToString", None):
|
||
logging.debug(f"Serializing protobuf as data: {stripnl(data)}")
|
||
data = data.SerializeToString()
|
||
|
||
logging.debug(f"len(data): {len(data)}")
|
||
logging.debug(f"mesh_pb2.Constants.DATA_PAYLOAD_LEN: {mesh_pb2.Constants.DATA_PAYLOAD_LEN}")
|
||
if len(data) > mesh_pb2.Constants.DATA_PAYLOAD_LEN:
|
||
raise Exception("Data payload too big")
|
||
|
||
if portNum == portnums_pb2.PortNum.UNKNOWN_APP: # we are now more strict wrt port numbers
|
||
our_exit("Warning: A non-zero port number must be specified")
|
||
|
||
meshPacket = mesh_pb2.MeshPacket()
|
||
meshPacket.channel = channelIndex
|
||
meshPacket.decoded.payload = data
|
||
meshPacket.decoded.portnum = portNum
|
||
meshPacket.decoded.want_response = wantResponse
|
||
|
||
p = self._sendPacket(meshPacket, destinationId,
|
||
wantAck=wantAck, hopLimit=hopLimit)
|
||
if onResponse is not None:
|
||
self._addResponseHandler(p.id, onResponse)
|
||
return p</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.sendPosition"><code class="name flex">
|
||
<span>def <span class="ident">sendPosition</span></span>(<span>self, latitude=0.0, longitude=0.0, altitude=0, timeSec=0, destinationId='^all', wantAck=False, wantResponse=False)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Send a position packet to some other node (normally a broadcast)</p>
|
||
<p>Also, the device software will notice this packet and use it to automatically
|
||
set its notion of the local position.</p>
|
||
<p>If timeSec is not specified (recommended), we will use the local machine time.</p>
|
||
<p>Returns the sent packet. The id field will be populated in this packet and
|
||
can be used to track future message acks/naks.</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def sendPosition(self, latitude=0.0, longitude=0.0, altitude=0, timeSec=0,
|
||
destinationId=BROADCAST_ADDR, wantAck=False, wantResponse=False):
|
||
"""
|
||
Send a position packet to some other node (normally a broadcast)
|
||
|
||
Also, the device software will notice this packet and use it to automatically
|
||
set its notion of the local position.
|
||
|
||
If timeSec is not specified (recommended), we will use the local machine time.
|
||
|
||
Returns the sent packet. The id field will be populated in this packet and
|
||
can be used to track future message acks/naks.
|
||
"""
|
||
p = mesh_pb2.Position()
|
||
if latitude != 0.0:
|
||
p.latitude_i = int(latitude / 1e-7)
|
||
logging.debug(f'p.latitude_i:{p.latitude_i}')
|
||
|
||
if longitude != 0.0:
|
||
p.longitude_i = int(longitude / 1e-7)
|
||
logging.debug(f'p.longitude_i:{p.longitude_i}')
|
||
|
||
if altitude != 0:
|
||
p.altitude = int(altitude)
|
||
logging.debug(f'p.altitude:{p.altitude}')
|
||
|
||
if timeSec == 0:
|
||
timeSec = time.time() # returns unix timestamp in seconds
|
||
p.time = int(timeSec)
|
||
logging.debug(f'p.time:{p.time}')
|
||
|
||
return self.sendData(p, destinationId,
|
||
portNum=portnums_pb2.PortNum.POSITION_APP,
|
||
wantAck=wantAck,
|
||
wantResponse=wantResponse)</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.sendText"><code class="name flex">
|
||
<span>def <span class="ident">sendText</span></span>(<span>self, text: ~AnyStr, destinationId='^all', wantAck=False, wantResponse=False, hopLimit=None, onResponse=None, channelIndex=0)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Send a utf8 string to some other node, if the node has a display it
|
||
will also be shown on the device.</p>
|
||
<h2 id="arguments">Arguments</h2>
|
||
<p>text {string} – The text to send</p>
|
||
<p>Keyword Arguments:
|
||
destinationId {nodeId or nodeNum} – where to send this
|
||
message (default: {BROADCAST_ADDR})
|
||
portNum – the application portnum (similar to IP port numbers)
|
||
of the destination, see portnums.proto for a list
|
||
wantAck – True if you want the message sent in a reliable manner
|
||
(with retries and ack/nak provided for delivery)
|
||
wantResponse – True if you want the service on the other side to
|
||
send an application layer response</p>
|
||
<p>Returns the sent packet. The id field will be populated in this packet
|
||
and can be used to track future message acks/naks.</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def sendText(self, text: AnyStr,
|
||
destinationId=BROADCAST_ADDR,
|
||
wantAck=False,
|
||
wantResponse=False,
|
||
hopLimit=None,
|
||
onResponse=None,
|
||
channelIndex=0):
|
||
"""Send a utf8 string to some other node, if the node has a display it
|
||
will also be shown on the device.
|
||
|
||
Arguments:
|
||
text {string} -- The text to send
|
||
|
||
Keyword Arguments:
|
||
destinationId {nodeId or nodeNum} -- where to send this
|
||
message (default: {BROADCAST_ADDR})
|
||
portNum -- the application portnum (similar to IP port numbers)
|
||
of the destination, see portnums.proto for a list
|
||
wantAck -- True if you want the message sent in a reliable manner
|
||
(with retries and ack/nak provided for delivery)
|
||
wantResponse -- True if you want the service on the other side to
|
||
send an application layer response
|
||
|
||
Returns the sent packet. The id field will be populated in this packet
|
||
and can be used to track future message acks/naks.
|
||
"""
|
||
if hopLimit is None:
|
||
hopLimit = self.defaultHopLimit
|
||
|
||
return self.sendData(text.encode("utf-8"), destinationId,
|
||
portNum=portnums_pb2.PortNum.TEXT_MESSAGE_APP,
|
||
wantAck=wantAck,
|
||
wantResponse=wantResponse,
|
||
hopLimit=hopLimit,
|
||
onResponse=onResponse,
|
||
channelIndex=channelIndex)</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.showInfo"><code class="name flex">
|
||
<span>def <span class="ident">showInfo</span></span>(<span>self, file=sys.stdout)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Show human readable summary about this object</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def showInfo(self, file=sys.stdout):
|
||
"""Show human readable summary about this object"""
|
||
owner = f"Owner: {self.getLongName()} ({self.getShortName()})"
|
||
myinfo = ''
|
||
if self.myInfo:
|
||
myinfo = f"\nMy info: {stripnl(MessageToJson(self.myInfo))}"
|
||
mesh = "\nNodes in mesh:"
|
||
nodes = ""
|
||
if self.nodes:
|
||
for n in self.nodes.values():
|
||
nodes = nodes + f" {stripnl(n)}"
|
||
infos = owner + myinfo + mesh + nodes
|
||
print(infos)
|
||
return infos</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.showNodes"><code class="name flex">
|
||
<span>def <span class="ident">showNodes</span></span>(<span>self, includeSelf=True, file=sys.stdout)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Show table summary of nodes in mesh</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def showNodes(self, includeSelf=True, file=sys.stdout):
|
||
"""Show table summary of nodes in mesh"""
|
||
def formatFloat(value, precision=2, unit=''):
|
||
"""Format a float value with precsion."""
|
||
return f'{value:.{precision}f}{unit}' if value else None
|
||
|
||
def getLH(ts):
|
||
"""Format last heard"""
|
||
return datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') if ts else None
|
||
|
||
def getTimeAgo(ts):
|
||
"""Format how long ago have we heard from this node (aka timeago)."""
|
||
return timeago.format(datetime.fromtimestamp(ts), datetime.now()) if ts else None
|
||
|
||
rows = []
|
||
if self.nodes:
|
||
logging.debug(f'self.nodes:{self.nodes}')
|
||
for node in self.nodes.values():
|
||
if not includeSelf and node['num'] == self.localNode.nodeNum:
|
||
continue
|
||
|
||
row = {"N": 0}
|
||
|
||
user = node.get('user')
|
||
if user:
|
||
row.update({
|
||
"User": user['longName'],
|
||
"AKA": user['shortName'],
|
||
"ID": user['id'],
|
||
})
|
||
|
||
pos = node.get('position')
|
||
if pos:
|
||
row.update({
|
||
"Latitude": formatFloat(pos.get("latitude"), 4, "°"),
|
||
"Longitude": formatFloat(pos.get("longitude"), 4, "°"),
|
||
"Altitude": formatFloat(pos.get("altitude"), 0, " m"),
|
||
"Battery": formatFloat(pos.get("batteryLevel"), 2, "%"),
|
||
})
|
||
|
||
row.update({
|
||
"SNR": formatFloat(node.get("snr"), 2, " dB"),
|
||
"LastHeard": getLH(node.get("lastHeard")),
|
||
"Since": getTimeAgo(node.get("lastHeard")),
|
||
})
|
||
|
||
rows.append(row)
|
||
|
||
rows.sort(key=lambda r: r.get('LastHeard') or '0000', reverse=True)
|
||
for i, row in enumerate(rows):
|
||
row['N'] = i+1
|
||
|
||
table = tabulate(rows, headers='keys', missingval='N/A', tablefmt='fancy_grid')
|
||
print(table)
|
||
return table</code></pre>
|
||
</details>
|
||
</dd>
|
||
<dt id="meshtastic.mesh_interface.MeshInterface.waitForConfig"><code class="name flex">
|
||
<span>def <span class="ident">waitForConfig</span></span>(<span>self)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<div class="desc"><p>Block until radio config is received. Returns True if config has been received.</p></div>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def waitForConfig(self):
|
||
"""Block until radio config is received. Returns True if config has been received."""
|
||
success = self._timeout.waitForSet(self, attrs=('myInfo', 'nodes')) and self.localNode.waitForConfig()
|
||
if not success:
|
||
raise Exception("Timed out waiting for interface config")</code></pre>
|
||
</details>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
</dl>
|
||
</section>
|
||
</article>
|
||
<nav id="sidebar">
|
||
<h1>Index</h1>
|
||
<div class="toc">
|
||
<ul></ul>
|
||
</div>
|
||
<ul id="index">
|
||
<li><h3>Super-module</h3>
|
||
<ul>
|
||
<li><code><a title="meshtastic" href="index.html">meshtastic</a></code></li>
|
||
</ul>
|
||
</li>
|
||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||
<ul>
|
||
<li>
|
||
<h4><code><a title="meshtastic.mesh_interface.MeshInterface" href="#meshtastic.mesh_interface.MeshInterface">MeshInterface</a></code></h4>
|
||
<ul class="two-column">
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.close" href="#meshtastic.mesh_interface.MeshInterface.close">close</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.getLongName" href="#meshtastic.mesh_interface.MeshInterface.getLongName">getLongName</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.getMyNodeInfo" href="#meshtastic.mesh_interface.MeshInterface.getMyNodeInfo">getMyNodeInfo</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.getMyUser" href="#meshtastic.mesh_interface.MeshInterface.getMyUser">getMyUser</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.getNode" href="#meshtastic.mesh_interface.MeshInterface.getNode">getNode</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.getShortName" href="#meshtastic.mesh_interface.MeshInterface.getShortName">getShortName</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.sendData" href="#meshtastic.mesh_interface.MeshInterface.sendData">sendData</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.sendPosition" href="#meshtastic.mesh_interface.MeshInterface.sendPosition">sendPosition</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.sendText" href="#meshtastic.mesh_interface.MeshInterface.sendText">sendText</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.showInfo" href="#meshtastic.mesh_interface.MeshInterface.showInfo">showInfo</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.showNodes" href="#meshtastic.mesh_interface.MeshInterface.showNodes">showNodes</a></code></li>
|
||
<li><code><a title="meshtastic.mesh_interface.MeshInterface.waitForConfig" href="#meshtastic.mesh_interface.MeshInterface.waitForConfig">waitForConfig</a></code></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</nav>
|
||
</main>
|
||
<footer id="footer">
|
||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.10.0</a>.</p>
|
||
</footer>
|
||
</body>
|
||
</html> |