-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrogtastic.py
More file actions
246 lines (226 loc) · 9.72 KB
/
frogtastic.py
File metadata and controls
246 lines (226 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import datetime
import meshtastic
import meshtastic.serial_interface
from pubsub import pub
import time
def onConnection(id, interface, topic=pub.AUTO_TOPIC): # called when we (re)connect to the radio
# defaults to broadcast, specify a destination ID if you wish
interface.sendText("Node {} Online".format(self.id))
class MeshtasticClient():
def __init__(self, device):
self.rec = None
self.new = False
self.rect = 0
self.packet = None
self.maxlen = 240
#print(meshtastic.serial_interface)
self.meshint = meshtastic.serial_interface.SerialInterface(device)
myinfo = self.meshint.getMyUser()
self.id = myinfo['id']
self.messages = []
pub.subscribe(self.onReceive, "meshtastic.receive")
def onReceive(self, packet, interface): # called when a packet arrives
#print(f"Received: {packet}")
try:
snr = packet['rxSnr']
except KeyError:
snr = None
try:
rssi = packet['rxRssi']
except KeyError:
rssi = None
try:
hopLimit = packet['hopLimit']
except KeyError:
hopLimit = None
sender = packet['fromId']
self.packet = packet
self.rect = time.time()
if packet['decoded']['portnum']=='TEXT_MESSAGE_APP':
try:
try:
if 'altitude' in packet['decoded']['position'].keys():
pos = (packet['decoded']['position']['latitude'], packet['decoded']['position']['longitude'], packet['decoded']['position']['altitude'])
else:
pos = (packet['decoded']['position']['latitude'], packet['decoded']['position']['longitude'], 0)
except KeyError:
#print('Pos error')
pos = None
try:
longname = interface.nodes[sender]['user']['longName']
except KeyError:
#print('Sender error')
longname = None
try:
#t = datetime.datetime.fromtimestamp(packet['rxTime']).strftime('%Y-%m-%d %H:%M:%S')
t = packet['rxTime']
except KeyError:
#print('Time error')
t = time.time()
self.rec = {
'senderid': sender,
'sender': longname,
'type': 'TEXT_MESSAGE_APP',
'port': None,
'pos': pos,
'snr': snr,
'rssi': rssi,
'dest': packet['toId'],
'time': t,
'data': packet['decoded']['text'],
'hoplimit': hopLimit
}
#print(self.rec)
self.messages.append(self.rec)
self.new = True
except Exception as e:
print('=========================================')
print('Error')
print(packet)
print(e)
print('=========================================')
elif packet['decoded']['portnum']=='POSITION_APP':
try:
try:
pos = {
"latitude": packet['decoded']['position']['latitude'],
"longitude": packet['decoded']['position']['longitude'],
"altitude": packet['decoded']['position'].get('altitude',0),
"time": packet['decoded']['position']['time'],
"PDOP": packet['decoded']['position']['PDOP'],
"groundSpeed": packet['decoded']['position']['groundSpeed'],
"groundTrack": packet['decoded']['position']['groundTrack'],
"satsInView": packet['decoded']['position']['satsInView'],
}
except KeyError:
print('Pos error')
pos = None
try:
longname = interface.nodes[sender]['user']['longName']
except KeyError:
#print('Sender error')
longname = None
try:
t = packet['rxTime']
except KeyError:
#print('Time error')
t = time.time()
self.rec = {
'senderid': sender,
'sender': longname,
'type': 'POSITION_APP',
'port': None,
'pos': pos,
'snr': snr,
'rssi': rssi,
'dest': packet['toId'],
'time': t,
'data': None,
'hoplimit': hopLimit
}
#print(self.rec)
self.messages.append(self.rec)
self.new = True
except Exception as e:
print('=========================================')
print('Error')
print(packet)
print(e)
print('=========================================')
elif packet['decoded']['portnum']=='PRIVATE_APP' or type(packet['decoded']['portnum']) is int:
try:
try:
longname = interface.nodes[sender]['user']['longName']
except KeyError:
#print('Sender error')
longname = None
try:
t = packet['rxTime']
except KeyError:
#print('Time error')
t = time.time()
self.rec = {
'senderid': sender,
'sender': longname,
'type': 'PRIVATE_APP',
'port': packet['decoded']['portnum'],
'snr': snr,
'rssi': rssi,
'pos': None,
'dest': packet['toId'],
'time': t,
'data': packet['decoded']['payload'],
'hoplimit': hopLimit
}
#print(self.rec)
self.messages.append(self.rec)
self.new = True
except Exception as e:
print('=========================================')
print('Error')
print(packet)
print(e)
print('=========================================')
def checkMail(self):
if self.new:
self.new = False
msgs = self.messages
self.messages = []
return msgs
else:
return []
def getPosition(self):
a = client.meshint.getMyNodeInfo()
if 'altitude' in a['position'].keys():
return (a['position']['latitude'], a['position']['longitude'], a['position']['altitude'])
else:
return (a['position']['latitude'], a['position']['longitude'], 0)
if __name__ == "__main__":
#from meshlib import *
# https://python.meshtastic.org/mesh_interface.html
client = MeshtasticClient('/dev/ttyACM0')
client.meshint.getMyNodeInfo()
client.checkMail()
client.meshint.sendText("Test", wantAck=True)
client.meshint.sendText("DM Test", destinationId='!xxxxxx', wantAck=True)
client.meshint.sendPosition(latitude=44, longitude=-71, altitude=20, wantAck=True)
client.meshint.sendData(b'[TestData]', portNum=258, wantAck=True) #256-511 for private apps
client.meshint.sendPosition(latitude=0.0, longitude=0.0, altitude=0, timeSec=0, destinationId='^all', wantAck=False, wantResponse=False)
client.meshint.close()
#client.meshint.sendText(
# text: str,
# destinationId: Union[int, str] = '^all',
# wantAck: bool = False,
# wantResponse: bool = False,
# onResponse: Optional[Callable[[dict], Any]] = None,
# channelIndex: int = 0)
#client.meshint.sendPosition(
# latitude: float = 0.0,
# longitude: float = 0.0,
# altitude: int = 0,
# destinationId: Union[int, str] = '^all',
# wantAck: bool = False,
# wantResponse: bool = False,
# channelIndex: int = 0)
#client.meshint.sendData(
# data,
# destinationId: Union[int, str] = '^all',
# portNum: int = 256,
# wantAck: bool = False,
# wantResponse: bool = False,
# onResponse: Optional[Callable[[dict], Any]] = None,
# onResponseAckPermitted: bool = False,
# channelIndex: int = 0,
# hopLimit: Optional[int] = None,
# pkiEncrypted: Optional[bool] = False,
# publicKey: Optional[bytes] = None)
"""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)
onResponseAckPermitted – should the onResponse callback be called for regular ACKs (True) or just data responses & NAKs (False) Note that if the onResponse callback is called 'onAckNak' this will implicitly be true.
channelIndex – channel number to use
hopLimit – hop limit to use"""