mirror of
https://github.com/meshtastic/python.git
synced 2026-01-04 05:47:57 -05:00
0.5.3
This commit is contained in:
53
docs/meshtastic/ble.html
Normal file
53
docs/meshtastic/ble.html
Normal file
@@ -0,0 +1,53 @@
|
||||
<!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.8.1" />
|
||||
<title>meshtastic.ble API documentation</title>
|
||||
<meta name="description" content="" />
|
||||
<link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
|
||||
<link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
|
||||
<style>.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%}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}.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%}.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>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<article id="content">
|
||||
<header>
|
||||
<h1 class="title">Module <code>meshtastic.ble</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</section>
|
||||
<section>
|
||||
</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>
|
||||
</ul>
|
||||
</nav>
|
||||
</main>
|
||||
<footer id="footer">
|
||||
<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.8.1</a>.</p>
|
||||
</footer>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
|
||||
<script>hljs.initHighlightingOnLoad()</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -20,7 +20,7 @@
|
||||
<h1 class="title">Package <code>meshtastic</code></h1>
|
||||
</header>
|
||||
<section id="section-intro">
|
||||
<h2 id="an-api-for-meshtastic-devices">an API for Meshtastic devices</h2>
|
||||
<h1 id="an-api-for-meshtastic-devices">an API for Meshtastic devices</h1>
|
||||
<p>Primary class: StreamInterface
|
||||
Install with pip: "<a href="https://pypi.org/project/meshtastic/">pip3 install meshtastic</a>"
|
||||
Source code on <a href="https://github.com/meshtastic/Meshtastic-python">github</a></p>
|
||||
@@ -34,7 +34,7 @@ node in the mesh.
|
||||
This is a read-only datastructure.</li>
|
||||
<li>myNodeInfo - Contains read-only information about the local radio device (software version, hardware version, etc)</li>
|
||||
</ul>
|
||||
<h2 id="published-pubsub-topics">Published PubSub topics</h2>
|
||||
<h1 id="published-pubsub-topics">Published PubSub topics</h1>
|
||||
<p>We use a <a href="https://pypubsub.readthedocs.io/en/v4.0.3/">publish-subscribe</a> model to communicate asynchronous events.
|
||||
Available
|
||||
topics:</p>
|
||||
@@ -48,7 +48,7 @@ If you want to see all packets, simply subscribe to "meshtastic.receive".</li>
|
||||
<li>meshtastic.receive.data(packet)</li>
|
||||
<li>meshtastic.node.updated(node = NodeInfo) - published when a node in the DB changes (appears, location changed, username changed, etc…)</li>
|
||||
</ul>
|
||||
<h2 id="example-usage">Example Usage</h2>
|
||||
<h1 id="example-usage">Example Usage</h1>
|
||||
<pre><code>import meshtastic
|
||||
from pubsub import pub
|
||||
|
||||
@@ -56,11 +56,13 @@ def onReceive(packet): # called when a packet arrives
|
||||
print(f"Received: {packet}")
|
||||
|
||||
def onConnection(): # called when we (re)connect to the radio
|
||||
interface.sendText("hello mesh") # defaults to broadcast, specify a destination ID if you wish
|
||||
# defaults to broadcast, specify a destination ID if you wish
|
||||
interface.sendText("hello mesh")
|
||||
|
||||
pub.subscribe(onReceive, "meshtastic.receive")
|
||||
pub.subscribe(onConnection, "meshtastic.connection.established")
|
||||
interface = meshtastic.StreamInterface() # By default will try to find a meshtastic device, otherwise provide a device path like /dev/ttyUSB0
|
||||
# By default will try to find a meshtastic device, otherwise provide a device path like /dev/ttyUSB0
|
||||
interface = meshtastic.StreamInterface()
|
||||
|
||||
</code></pre>
|
||||
<details class="source">
|
||||
@@ -68,7 +70,7 @@ interface = meshtastic.StreamInterface() # By default will try to find a meshtas
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">"""
|
||||
## an API for Meshtastic devices
|
||||
# an API for Meshtastic devices
|
||||
|
||||
Primary class: StreamInterface
|
||||
Install with pip: "[pip3 install meshtastic](https://pypi.org/project/meshtastic/)"
|
||||
@@ -76,26 +78,26 @@ Source code on [github](https://github.com/meshtastic/Meshtastic-python)
|
||||
|
||||
properties of StreamInterface:
|
||||
|
||||
- radioConfig - Current radio configuration and device settings, if you write to this the new settings will be applied to
|
||||
- radioConfig - Current radio configuration and device settings, if you write to this the new settings will be applied to
|
||||
the device.
|
||||
- nodes - The database of received nodes. Includes always up-to-date location and username information for each
|
||||
- nodes - The database of received nodes. Includes always up-to-date location and username information for each
|
||||
node in the mesh. This is a read-only datastructure.
|
||||
- myNodeInfo - Contains read-only information about the local radio device (software version, hardware version, etc)
|
||||
|
||||
## Published PubSub topics
|
||||
# Published PubSub topics
|
||||
|
||||
We use a [publish-subscribe](https://pypubsub.readthedocs.io/en/v4.0.3/) model to communicate asynchronous events. Available
|
||||
topics:
|
||||
|
||||
- meshtastic.connection.established - published once we've successfully connected to the radio and downloaded the node DB
|
||||
- meshtastic.connection.lost - published once we've lost our link to the radio
|
||||
- meshtastic.receive.position(packet) - delivers a received packet as a dictionary, if you only care about a particular
|
||||
- meshtastic.receive.position(packet) - delivers a received packet as a dictionary, if you only care about a particular
|
||||
type of packet, you should subscribe to the full topic name. If you want to see all packets, simply subscribe to "meshtastic.receive".
|
||||
- meshtastic.receive.user(packet)
|
||||
- meshtastic.receive.data(packet)
|
||||
- meshtastic.node.updated(node = NodeInfo) - published when a node in the DB changes (appears, location changed, username changed, etc...)
|
||||
|
||||
## Example Usage
|
||||
# Example Usage
|
||||
```
|
||||
import meshtastic
|
||||
from pubsub import pub
|
||||
@@ -104,16 +106,19 @@ def onReceive(packet): # called when a packet arrives
|
||||
print(f"Received: {packet}")
|
||||
|
||||
def onConnection(): # called when we (re)connect to the radio
|
||||
interface.sendText("hello mesh") # defaults to broadcast, specify a destination ID if you wish
|
||||
# defaults to broadcast, specify a destination ID if you wish
|
||||
interface.sendText("hello mesh")
|
||||
|
||||
pub.subscribe(onReceive, "meshtastic.receive")
|
||||
pub.subscribe(onConnection, "meshtastic.connection.established")
|
||||
interface = meshtastic.StreamInterface() # By default will try to find a meshtastic device, otherwise provide a device path like /dev/ttyUSB0
|
||||
# By default will try to find a meshtastic device, otherwise provide a device path like /dev/ttyUSB0
|
||||
interface = meshtastic.StreamInterface()
|
||||
|
||||
```
|
||||
|
||||
"""
|
||||
|
||||
import pygatt
|
||||
import google.protobuf.json_format
|
||||
import serial
|
||||
import threading
|
||||
@@ -153,7 +158,7 @@ class MeshInterface:
|
||||
self.isConnected = False
|
||||
self._startConfig()
|
||||
|
||||
def sendText(self, text, destinationId=BROADCAST_ADDR):
|
||||
def sendText(self, text, destinationId=BROADCAST_ADDR, wantAck=False):
|
||||
"""Send a utf8 string to some other node, if the node has a display it will also be shown on the device.
|
||||
|
||||
Arguments:
|
||||
@@ -163,30 +168,30 @@ class MeshInterface:
|
||||
destinationId {nodeId or nodeNum} -- where to send this message (default: {BROADCAST_ADDR})
|
||||
"""
|
||||
self.sendData(text.encode("utf-8"), destinationId,
|
||||
dataType=mesh_pb2.Data.CLEAR_TEXT)
|
||||
dataType=mesh_pb2.Data.CLEAR_TEXT, wantAck=wantAck)
|
||||
|
||||
def sendData(self, byteData, destinationId=BROADCAST_ADDR, dataType=mesh_pb2.Data.OPAQUE):
|
||||
def sendData(self, byteData, destinationId=BROADCAST_ADDR, dataType=mesh_pb2.Data.OPAQUE, wantAck=False):
|
||||
"""Send a data packet to some other node"""
|
||||
meshPacket = mesh_pb2.MeshPacket()
|
||||
meshPacket.payload.data.payload = byteData
|
||||
meshPacket.payload.data.typ = dataType
|
||||
self.sendPacket(meshPacket, destinationId)
|
||||
meshPacket.decoded.data.payload = byteData
|
||||
meshPacket.decoded.data.typ = dataType
|
||||
self.sendPacket(meshPacket, destinationId, wantAck=wantAck)
|
||||
|
||||
def sendPacket(self, meshPacket, destinationId=BROADCAST_ADDR):
|
||||
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||||
def sendPacket(self, meshPacket, destinationId=BROADCAST_ADDR, wantAck=False):
|
||||
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||||
You probably don't want this - use sendData instead."""
|
||||
toRadio = mesh_pb2.ToRadio()
|
||||
# FIXME add support for non broadcast addresses
|
||||
|
||||
if isinstance(destinationId, int):
|
||||
nodeNum = destinationId
|
||||
elif nodeNum == BROADCAST_ADDR:
|
||||
elif destinationId == BROADCAST_ADDR:
|
||||
nodeNum = 255
|
||||
else:
|
||||
raise Exception(
|
||||
"invalid destination addr, we don't yet support nodeid lookup")
|
||||
nodeNum = self.nodes[destinationId].num
|
||||
|
||||
meshPacket.to = nodeNum
|
||||
meshPacket.want_ack = wantAck
|
||||
toRadio.packet.CopyFrom(meshPacket)
|
||||
self._sendToRadio(toRadio)
|
||||
|
||||
@@ -232,16 +237,17 @@ class MeshInterface:
|
||||
Called by subclasses."""
|
||||
fromRadio = mesh_pb2.FromRadio()
|
||||
fromRadio.ParseFromString(fromRadioBytes)
|
||||
json = google.protobuf.json_format.MessageToJson(fromRadio)
|
||||
logging.debug(f"Received: {json}")
|
||||
asDict = google.protobuf.json_format.MessageToDict(fromRadio)
|
||||
logging.debug(f"Received: {asDict}")
|
||||
if fromRadio.HasField("my_info"):
|
||||
self.myInfo = fromRadio.my_info
|
||||
elif fromRadio.HasField("radio"):
|
||||
self.radioConfig = fromRadio.radio
|
||||
elif fromRadio.HasField("node_info"):
|
||||
node = fromRadio.node_info
|
||||
self._nodesByNum[node.num] = node
|
||||
self.nodes[node.user.id] = node
|
||||
node = asDict["nodeInfo"]
|
||||
self._fixupPosition(node["position"])
|
||||
self._nodesByNum[node["num"]] = node
|
||||
self.nodes[node["user"]["id"]] = node
|
||||
elif fromRadio.config_complete_id == MY_CONFIG_ID:
|
||||
# we ignore the config_complete_id, it is unneeded for our stream API fromRadio.config_complete_id
|
||||
self._connected()
|
||||
@@ -253,12 +259,31 @@ class MeshInterface:
|
||||
else:
|
||||
logging.warn("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
|
||||
return self._nodesByNum[num]["user"]["id"]
|
||||
except:
|
||||
logging.error("Node not found for fromId")
|
||||
return None
|
||||
@@ -278,29 +303,80 @@ class MeshInterface:
|
||||
asDict["toId"] = self._nodeNumToId(asDict["to"])
|
||||
|
||||
# We could provide our objects as DotMaps - which work with . notation or as dictionaries
|
||||
#asObj = DotMap(asDict)
|
||||
topic = None
|
||||
if meshPacket.payload.HasField("position"):
|
||||
# asObj = DotMap(asDict)
|
||||
topic = "meshtastic.receive" # Generic unknown packet type
|
||||
if meshPacket.decoded.HasField("position"):
|
||||
topic = "meshtastic.receive.position"
|
||||
# FIXME, update node DB as needed
|
||||
if meshPacket.payload.HasField("user"):
|
||||
p = asDict["decoded"]["position"]
|
||||
self._fixupPosition(p)
|
||||
# update node DB as needed
|
||||
self._nodesByNum[asDict["from"]]["position"] = p
|
||||
|
||||
if meshPacket.decoded.HasField("user"):
|
||||
topic = "meshtastic.receive.user"
|
||||
# FIXME, update node DB as needed
|
||||
if meshPacket.payload.HasField("data"):
|
||||
u = asDict["decoded"]["user"]
|
||||
# update node DB as needed
|
||||
self._nodesByNum[asDict["from"]]["user"] = u
|
||||
|
||||
if meshPacket.decoded.HasField("data"):
|
||||
topic = "meshtastic.receive.data"
|
||||
# For text messages, we go ahead and decode the text to ascii for our users
|
||||
# if asObj.payload.data.typ == "CLEAR_TEXT":
|
||||
# asObj.payload.data.text = asObj.payload.data.payload.decode(
|
||||
# "utf-8")
|
||||
if asDict["decoded"]["data"]["typ"] == "CLEAR_TEXT":
|
||||
asDict["decoded"]["data"]["text"] = meshPacket.decoded.data.payload.decode(
|
||||
"utf-8")
|
||||
|
||||
pub.sendMessage(topic, packet=asDict, interface=self)
|
||||
|
||||
|
||||
# Our standard BLE characteristics
|
||||
TORADIO_UUID = "f75c76d2-129e-4dad-a1dd-7866124401e7"
|
||||
FROMRADIO_UUID = "8ba2bcc2-ee02-4a55-a531-c525c5e454d5"
|
||||
FROMNUM_UUID = "ed9da18c-a800-4f66-a670-aa7547e34453"
|
||||
|
||||
|
||||
class BLEInterface(MeshInterface):
|
||||
"""A not quite ready - FIXME - BLE interface to devices"""
|
||||
|
||||
def __init__(self, address, debugOut=None):
|
||||
self.address = address
|
||||
self.adapter = pygatt.GATTToolBackend() # BGAPIBackend()
|
||||
self.adapter.start()
|
||||
logging.debug(f"Connecting to {self.address}")
|
||||
self.device = self.adapter.connect(address)
|
||||
logging.debug("Connected to device")
|
||||
# fromradio = self.device.char_read(FROMRADIO_UUID)
|
||||
MeshInterface.__init__(self, debugOut=debugOut)
|
||||
|
||||
self._readFromRadio() # read the initial responses
|
||||
|
||||
def handle_data(handle, data):
|
||||
self._handleFromRadio(data)
|
||||
|
||||
self.device.subscribe(FROMNUM_UUID, callback=handle_data)
|
||||
|
||||
def _sendToRadio(self, toRadio):
|
||||
"""Send a ToRadio protobuf to the device"""
|
||||
logging.debug(f"Sending: {toRadio}")
|
||||
b = toRadio.SerializeToString()
|
||||
self.device.char_write(TORADIO_UUID, b)
|
||||
|
||||
def close(self):
|
||||
self.adapter.stop()
|
||||
|
||||
def _readFromRadio(self):
|
||||
wasEmpty = False
|
||||
while not wasEmpty:
|
||||
b = self.device.char_read(FROMRADIO_UUID)
|
||||
wasEmpty = len(b) == 0
|
||||
if not wasEmpty:
|
||||
self._handleFromRadio(b)
|
||||
|
||||
|
||||
class StreamInterface(MeshInterface):
|
||||
"""Interface class for meshtastic devices over a stream link (serial, TCP, etc)"""
|
||||
|
||||
def __init__(self, devPath=None, debugOut=None):
|
||||
"""Constructor, opens a connection to a specified serial port, or if unspecified try to
|
||||
"""Constructor, opens a connection to a specified serial port, or if unspecified try to
|
||||
find one Meshtastic device by probing
|
||||
|
||||
Keyword Arguments:
|
||||
@@ -403,6 +479,10 @@ class StreamInterface(MeshInterface):
|
||||
<section>
|
||||
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
|
||||
<dl>
|
||||
<dt><code class="name"><a title="meshtastic.ble" href="ble.html">meshtastic.ble</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt><code class="name"><a title="meshtastic.mesh_pb2" href="mesh_pb2.html">meshtastic.mesh_pb2</a></code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
@@ -424,6 +504,86 @@ class StreamInterface(MeshInterface):
|
||||
<section>
|
||||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||||
<dl>
|
||||
<dt id="meshtastic.BLEInterface"><code class="flex name class">
|
||||
<span>class <span class="ident">BLEInterface</span></span>
|
||||
<span>(</span><span>address, debugOut=None)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>A not quite ready - FIXME - BLE interface to devices</p>
|
||||
<p>Constructor</p></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">class BLEInterface(MeshInterface):
|
||||
"""A not quite ready - FIXME - BLE interface to devices"""
|
||||
|
||||
def __init__(self, address, debugOut=None):
|
||||
self.address = address
|
||||
self.adapter = pygatt.GATTToolBackend() # BGAPIBackend()
|
||||
self.adapter.start()
|
||||
logging.debug(f"Connecting to {self.address}")
|
||||
self.device = self.adapter.connect(address)
|
||||
logging.debug("Connected to device")
|
||||
# fromradio = self.device.char_read(FROMRADIO_UUID)
|
||||
MeshInterface.__init__(self, debugOut=debugOut)
|
||||
|
||||
self._readFromRadio() # read the initial responses
|
||||
|
||||
def handle_data(handle, data):
|
||||
self._handleFromRadio(data)
|
||||
|
||||
self.device.subscribe(FROMNUM_UUID, callback=handle_data)
|
||||
|
||||
def _sendToRadio(self, toRadio):
|
||||
"""Send a ToRadio protobuf to the device"""
|
||||
logging.debug(f"Sending: {toRadio}")
|
||||
b = toRadio.SerializeToString()
|
||||
self.device.char_write(TORADIO_UUID, b)
|
||||
|
||||
def close(self):
|
||||
self.adapter.stop()
|
||||
|
||||
def _readFromRadio(self):
|
||||
wasEmpty = False
|
||||
while not wasEmpty:
|
||||
b = self.device.char_read(FROMRADIO_UUID)
|
||||
wasEmpty = len(b) == 0
|
||||
if not wasEmpty:
|
||||
self._handleFromRadio(b)</code></pre>
|
||||
</details>
|
||||
<h3>Ancestors</h3>
|
||||
<ul class="hlist">
|
||||
<li><a title="meshtastic.MeshInterface" href="#meshtastic.MeshInterface">MeshInterface</a></li>
|
||||
</ul>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="meshtastic.BLEInterface.close"><code class="name flex">
|
||||
<span>def <span class="ident">close</span></span>(<span>self)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"></div>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def close(self):
|
||||
self.adapter.stop()</code></pre>
|
||||
</details>
|
||||
</dd>
|
||||
</dl>
|
||||
<h3>Inherited members</h3>
|
||||
<ul class="hlist">
|
||||
<li><code><b><a title="meshtastic.MeshInterface" href="#meshtastic.MeshInterface">MeshInterface</a></b></code>:
|
||||
<ul class="hlist">
|
||||
<li><code><a title="meshtastic.MeshInterface.sendData" href="#meshtastic.MeshInterface.sendData">sendData</a></code></li>
|
||||
<li><code><a title="meshtastic.MeshInterface.sendPacket" href="#meshtastic.MeshInterface.sendPacket">sendPacket</a></code></li>
|
||||
<li><code><a title="meshtastic.MeshInterface.sendText" href="#meshtastic.MeshInterface.sendText">sendText</a></code></li>
|
||||
<li><code><a title="meshtastic.MeshInterface.writeConfig" href="#meshtastic.MeshInterface.writeConfig">writeConfig</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</dd>
|
||||
<dt id="meshtastic.MeshInterface"><code class="flex name class">
|
||||
<span>class <span class="ident">MeshInterface</span></span>
|
||||
<span>(</span><span>debugOut=None)</span>
|
||||
@@ -456,7 +616,7 @@ debugOut</p>
|
||||
self.isConnected = False
|
||||
self._startConfig()
|
||||
|
||||
def sendText(self, text, destinationId=BROADCAST_ADDR):
|
||||
def sendText(self, text, destinationId=BROADCAST_ADDR, wantAck=False):
|
||||
"""Send a utf8 string to some other node, if the node has a display it will also be shown on the device.
|
||||
|
||||
Arguments:
|
||||
@@ -466,30 +626,30 @@ debugOut</p>
|
||||
destinationId {nodeId or nodeNum} -- where to send this message (default: {BROADCAST_ADDR})
|
||||
"""
|
||||
self.sendData(text.encode("utf-8"), destinationId,
|
||||
dataType=mesh_pb2.Data.CLEAR_TEXT)
|
||||
dataType=mesh_pb2.Data.CLEAR_TEXT, wantAck=wantAck)
|
||||
|
||||
def sendData(self, byteData, destinationId=BROADCAST_ADDR, dataType=mesh_pb2.Data.OPAQUE):
|
||||
def sendData(self, byteData, destinationId=BROADCAST_ADDR, dataType=mesh_pb2.Data.OPAQUE, wantAck=False):
|
||||
"""Send a data packet to some other node"""
|
||||
meshPacket = mesh_pb2.MeshPacket()
|
||||
meshPacket.payload.data.payload = byteData
|
||||
meshPacket.payload.data.typ = dataType
|
||||
self.sendPacket(meshPacket, destinationId)
|
||||
meshPacket.decoded.data.payload = byteData
|
||||
meshPacket.decoded.data.typ = dataType
|
||||
self.sendPacket(meshPacket, destinationId, wantAck=wantAck)
|
||||
|
||||
def sendPacket(self, meshPacket, destinationId=BROADCAST_ADDR):
|
||||
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||||
def sendPacket(self, meshPacket, destinationId=BROADCAST_ADDR, wantAck=False):
|
||||
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||||
You probably don't want this - use sendData instead."""
|
||||
toRadio = mesh_pb2.ToRadio()
|
||||
# FIXME add support for non broadcast addresses
|
||||
|
||||
if isinstance(destinationId, int):
|
||||
nodeNum = destinationId
|
||||
elif nodeNum == BROADCAST_ADDR:
|
||||
elif destinationId == BROADCAST_ADDR:
|
||||
nodeNum = 255
|
||||
else:
|
||||
raise Exception(
|
||||
"invalid destination addr, we don't yet support nodeid lookup")
|
||||
nodeNum = self.nodes[destinationId].num
|
||||
|
||||
meshPacket.to = nodeNum
|
||||
meshPacket.want_ack = wantAck
|
||||
toRadio.packet.CopyFrom(meshPacket)
|
||||
self._sendToRadio(toRadio)
|
||||
|
||||
@@ -535,16 +695,17 @@ debugOut</p>
|
||||
Called by subclasses."""
|
||||
fromRadio = mesh_pb2.FromRadio()
|
||||
fromRadio.ParseFromString(fromRadioBytes)
|
||||
json = google.protobuf.json_format.MessageToJson(fromRadio)
|
||||
logging.debug(f"Received: {json}")
|
||||
asDict = google.protobuf.json_format.MessageToDict(fromRadio)
|
||||
logging.debug(f"Received: {asDict}")
|
||||
if fromRadio.HasField("my_info"):
|
||||
self.myInfo = fromRadio.my_info
|
||||
elif fromRadio.HasField("radio"):
|
||||
self.radioConfig = fromRadio.radio
|
||||
elif fromRadio.HasField("node_info"):
|
||||
node = fromRadio.node_info
|
||||
self._nodesByNum[node.num] = node
|
||||
self.nodes[node.user.id] = node
|
||||
node = asDict["nodeInfo"]
|
||||
self._fixupPosition(node["position"])
|
||||
self._nodesByNum[node["num"]] = node
|
||||
self.nodes[node["user"]["id"]] = node
|
||||
elif fromRadio.config_complete_id == MY_CONFIG_ID:
|
||||
# we ignore the config_complete_id, it is unneeded for our stream API fromRadio.config_complete_id
|
||||
self._connected()
|
||||
@@ -556,12 +717,31 @@ debugOut</p>
|
||||
else:
|
||||
logging.warn("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
|
||||
return self._nodesByNum[num]["user"]["id"]
|
||||
except:
|
||||
logging.error("Node not found for fromId")
|
||||
return None
|
||||
@@ -581,31 +761,39 @@ debugOut</p>
|
||||
asDict["toId"] = self._nodeNumToId(asDict["to"])
|
||||
|
||||
# We could provide our objects as DotMaps - which work with . notation or as dictionaries
|
||||
#asObj = DotMap(asDict)
|
||||
topic = None
|
||||
if meshPacket.payload.HasField("position"):
|
||||
# asObj = DotMap(asDict)
|
||||
topic = "meshtastic.receive" # Generic unknown packet type
|
||||
if meshPacket.decoded.HasField("position"):
|
||||
topic = "meshtastic.receive.position"
|
||||
# FIXME, update node DB as needed
|
||||
if meshPacket.payload.HasField("user"):
|
||||
p = asDict["decoded"]["position"]
|
||||
self._fixupPosition(p)
|
||||
# update node DB as needed
|
||||
self._nodesByNum[asDict["from"]]["position"] = p
|
||||
|
||||
if meshPacket.decoded.HasField("user"):
|
||||
topic = "meshtastic.receive.user"
|
||||
# FIXME, update node DB as needed
|
||||
if meshPacket.payload.HasField("data"):
|
||||
u = asDict["decoded"]["user"]
|
||||
# update node DB as needed
|
||||
self._nodesByNum[asDict["from"]]["user"] = u
|
||||
|
||||
if meshPacket.decoded.HasField("data"):
|
||||
topic = "meshtastic.receive.data"
|
||||
# For text messages, we go ahead and decode the text to ascii for our users
|
||||
# if asObj.payload.data.typ == "CLEAR_TEXT":
|
||||
# asObj.payload.data.text = asObj.payload.data.payload.decode(
|
||||
# "utf-8")
|
||||
if asDict["decoded"]["data"]["typ"] == "CLEAR_TEXT":
|
||||
asDict["decoded"]["data"]["text"] = meshPacket.decoded.data.payload.decode(
|
||||
"utf-8")
|
||||
|
||||
pub.sendMessage(topic, packet=asDict, interface=self)</code></pre>
|
||||
</details>
|
||||
<h3>Subclasses</h3>
|
||||
<ul class="hlist">
|
||||
<li><a title="meshtastic.BLEInterface" href="#meshtastic.BLEInterface">BLEInterface</a></li>
|
||||
<li><a title="meshtastic.StreamInterface" href="#meshtastic.StreamInterface">StreamInterface</a></li>
|
||||
</ul>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="meshtastic.MeshInterface.sendData"><code class="name flex">
|
||||
<span>def <span class="ident">sendData</span></span>(<span>self, byteData, destinationId='all', dataType=0)</span>
|
||||
<span>def <span class="ident">sendData</span></span>(<span>self, byteData, destinationId='all', dataType=0, wantAck=False)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Send a data packet to some other node</p></div>
|
||||
@@ -613,16 +801,16 @@ debugOut</p>
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def sendData(self, byteData, destinationId=BROADCAST_ADDR, dataType=mesh_pb2.Data.OPAQUE):
|
||||
<pre><code class="python">def sendData(self, byteData, destinationId=BROADCAST_ADDR, dataType=mesh_pb2.Data.OPAQUE, wantAck=False):
|
||||
"""Send a data packet to some other node"""
|
||||
meshPacket = mesh_pb2.MeshPacket()
|
||||
meshPacket.payload.data.payload = byteData
|
||||
meshPacket.payload.data.typ = dataType
|
||||
self.sendPacket(meshPacket, destinationId)</code></pre>
|
||||
meshPacket.decoded.data.payload = byteData
|
||||
meshPacket.decoded.data.typ = dataType
|
||||
self.sendPacket(meshPacket, destinationId, wantAck=wantAck)</code></pre>
|
||||
</details>
|
||||
</dd>
|
||||
<dt id="meshtastic.MeshInterface.sendPacket"><code class="name flex">
|
||||
<span>def <span class="ident">sendPacket</span></span>(<span>self, meshPacket, destinationId='all')</span>
|
||||
<span>def <span class="ident">sendPacket</span></span>(<span>self, meshPacket, destinationId='all', wantAck=False)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<div class="desc"><p>Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||||
@@ -631,27 +819,27 @@ You probably don't want this - use sendData instead.</p></div>
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def sendPacket(self, meshPacket, destinationId=BROADCAST_ADDR):
|
||||
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||||
<pre><code class="python">def sendPacket(self, meshPacket, destinationId=BROADCAST_ADDR, wantAck=False):
|
||||
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
|
||||
You probably don't want this - use sendData instead."""
|
||||
toRadio = mesh_pb2.ToRadio()
|
||||
# FIXME add support for non broadcast addresses
|
||||
|
||||
if isinstance(destinationId, int):
|
||||
nodeNum = destinationId
|
||||
elif nodeNum == BROADCAST_ADDR:
|
||||
elif destinationId == BROADCAST_ADDR:
|
||||
nodeNum = 255
|
||||
else:
|
||||
raise Exception(
|
||||
"invalid destination addr, we don't yet support nodeid lookup")
|
||||
nodeNum = self.nodes[destinationId].num
|
||||
|
||||
meshPacket.to = nodeNum
|
||||
meshPacket.want_ack = wantAck
|
||||
toRadio.packet.CopyFrom(meshPacket)
|
||||
self._sendToRadio(toRadio)</code></pre>
|
||||
</details>
|
||||
</dd>
|
||||
<dt id="meshtastic.MeshInterface.sendText"><code class="name flex">
|
||||
<span>def <span class="ident">sendText</span></span>(<span>self, text, destinationId='all')</span>
|
||||
<span>def <span class="ident">sendText</span></span>(<span>self, text, destinationId='all', wantAck=False)</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>
|
||||
@@ -663,7 +851,7 @@ destinationId {nodeId or nodeNum} – where to send this message (default: {
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def sendText(self, text, destinationId=BROADCAST_ADDR):
|
||||
<pre><code class="python">def sendText(self, text, destinationId=BROADCAST_ADDR, wantAck=False):
|
||||
"""Send a utf8 string to some other node, if the node has a display it will also be shown on the device.
|
||||
|
||||
Arguments:
|
||||
@@ -673,7 +861,7 @@ destinationId {nodeId or nodeNum} – where to send this message (default: {
|
||||
destinationId {nodeId or nodeNum} -- where to send this message (default: {BROADCAST_ADDR})
|
||||
"""
|
||||
self.sendData(text.encode("utf-8"), destinationId,
|
||||
dataType=mesh_pb2.Data.CLEAR_TEXT)</code></pre>
|
||||
dataType=mesh_pb2.Data.CLEAR_TEXT, wantAck=wantAck)</code></pre>
|
||||
</details>
|
||||
</dd>
|
||||
<dt id="meshtastic.MeshInterface.writeConfig"><code class="name flex">
|
||||
@@ -723,7 +911,7 @@ debugOut {stream} – If a stream is provided, any debug serial output from
|
||||
"""Interface class for meshtastic devices over a stream link (serial, TCP, etc)"""
|
||||
|
||||
def __init__(self, devPath=None, debugOut=None):
|
||||
"""Constructor, opens a connection to a specified serial port, or if unspecified try to
|
||||
"""Constructor, opens a connection to a specified serial port, or if unspecified try to
|
||||
find one Meshtastic device by probing
|
||||
|
||||
Keyword Arguments:
|
||||
@@ -874,6 +1062,7 @@ debugOut {stream} – If a stream is provided, any debug serial output from
|
||||
<ul id="index">
|
||||
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
|
||||
<ul>
|
||||
<li><code><a title="meshtastic.ble" href="ble.html">meshtastic.ble</a></code></li>
|
||||
<li><code><a title="meshtastic.mesh_pb2" href="mesh_pb2.html">meshtastic.mesh_pb2</a></code></li>
|
||||
<li><code><a title="meshtastic.test" href="test.html">meshtastic.test</a></code></li>
|
||||
<li><code><a title="meshtastic.util" href="util.html">meshtastic.util</a></code></li>
|
||||
@@ -882,6 +1071,12 @@ debugOut {stream} – If a stream is provided, any debug serial output from
|
||||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||||
<ul>
|
||||
<li>
|
||||
<h4><code><a title="meshtastic.BLEInterface" href="#meshtastic.BLEInterface">BLEInterface</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="meshtastic.BLEInterface.close" href="#meshtastic.BLEInterface.close">close</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><code><a title="meshtastic.MeshInterface" href="#meshtastic.MeshInterface">MeshInterface</a></code></h4>
|
||||
<ul class="">
|
||||
<li><code><a title="meshtastic.MeshInterface.sendData" href="#meshtastic.MeshInterface.sendData">sendData</a></code></li>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -49,7 +49,7 @@ def onReceive(packet, interface):
|
||||
print(f"From {interface.devPath}: {packet}")
|
||||
p = DotMap(packet)
|
||||
|
||||
if p.payload.data.typ == "CLEAR_TEXT":
|
||||
if p.decoded.data.typ == "CLEAR_TEXT":
|
||||
# We only care a about clear text packets
|
||||
receivedPackets.append(p)
|
||||
|
||||
@@ -82,11 +82,11 @@ def testSend(fromInterface, toInterface):
|
||||
toNode = toInterface.myInfo.my_node_num
|
||||
|
||||
# FIXME, hack to test broadcast
|
||||
toNode = 255
|
||||
# toNode = 255
|
||||
|
||||
logging.info(f"Sending test packet from {fromNode} to {toNode}")
|
||||
fromInterface.sendText(f"Test {testNumber}", toNode)
|
||||
time.sleep(40)
|
||||
fromInterface.sendText(f"Test {testNumber}", toNode, wantAck=True)
|
||||
time.sleep(30)
|
||||
return (len(receivedPackets) >= 1)
|
||||
|
||||
|
||||
@@ -212,7 +212,7 @@ def testAll():
|
||||
print(f"From {interface.devPath}: {packet}")
|
||||
p = DotMap(packet)
|
||||
|
||||
if p.payload.data.typ == "CLEAR_TEXT":
|
||||
if p.decoded.data.typ == "CLEAR_TEXT":
|
||||
# We only care a about clear text packets
|
||||
receivedPackets.append(p)</code></pre>
|
||||
</details>
|
||||
@@ -314,11 +314,11 @@ toInterface {[type]} – [description]</p>
|
||||
toNode = toInterface.myInfo.my_node_num
|
||||
|
||||
# FIXME, hack to test broadcast
|
||||
toNode = 255
|
||||
# toNode = 255
|
||||
|
||||
logging.info(f"Sending test packet from {fromNode} to {toNode}")
|
||||
fromInterface.sendText(f"Test {testNumber}", toNode)
|
||||
time.sleep(40)
|
||||
fromInterface.sendText(f"Test {testNumber}", toNode, wantAck=True)
|
||||
time.sleep(30)
|
||||
return (len(receivedPackets) >= 1)</code></pre>
|
||||
</details>
|
||||
</dd>
|
||||
|
||||
4
setup.py
4
setup.py
@@ -10,7 +10,7 @@ with open("README.md", "r") as fh:
|
||||
# This call to setup() does all the work
|
||||
setup(
|
||||
name="meshtastic",
|
||||
version="0.5.2",
|
||||
version="0.5.3",
|
||||
description="Python API & client shell for talking to Meshtastic devices",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
@@ -26,7 +26,7 @@ setup(
|
||||
packages=["meshtastic"],
|
||||
include_package_data=True,
|
||||
install_requires=["pyserial>=3.4", "protobuf>=3.6.1",
|
||||
"pypubsub>=4.0.3", "dotmap>=1.3.14" ],
|
||||
"pypubsub>=4.0.3", "dotmap>=1.3.14"],
|
||||
python_requires='>=3.4',
|
||||
entry_points={
|
||||
"console_scripts": [
|
||||
|
||||
Reference in New Issue
Block a user