Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Sep 10, 2024. It is now read-only.

Commit bc8aa8e

Browse files
committed
Ble Mac Characteristic and Mesh Key RPC
1 parent 467ec21 commit bc8aa8e

File tree

10 files changed

+156
-58
lines changed

10 files changed

+156
-58
lines changed

pymesh/pymesh_frozen/lib/battery.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
'''
88

99
import machine
10-
from machine import Timer,Pin,ADC
10+
from machine import Timer,Pin
1111
import time
1212

1313
__version__ = '1'

pymesh/pymesh_frozen/lib/ble_rpc.py

Lines changed: 65 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import _thread
99
import time
1010
from machine import Timer
11+
from machine import RTC
1112
from network import Bluetooth
1213
import sys
1314
import json
@@ -24,10 +25,7 @@
2425
except:
2526
from _pymesh_config import PymeshConfig
2627

27-
try:
28-
from gps import Gps
29-
except:
30-
from _gps import Gps
28+
from gps import Gps
3129

3230
class BleRpc:
3331

@@ -63,9 +61,23 @@ def on_rcv_message(self, message):
6361
'ts' : message.ts,
6462
'id' : message.id,
6563
}
66-
67-
msg = msgpack.packb(['notify', 'msg', message_data])
64+
msg = str(message.payload)
65+
if (message.mac == self.mesh.mesh.MAC):
66+
payload = b'G@'
67+
gps_loc = str(Gps.get_location())
68+
payload = payload + gps_loc
69+
message_data['payload'] = payload
70+
msg=str(payload)
71+
if (not (msg.find('@')<0)):
72+
msg_gps = msg.split("@")[0][2:]
73+
if (msg_gps == 'G'):
74+
msg = msgpack.packb(['notify', 'gps', message_data])
75+
print("notify gps=", message_data)
76+
else:
77+
msg = msgpack.packb(['notify', 'msg', message_data])
78+
print("message_data", message_data)
6879
self.rx_worker.put(msg)
80+
print("putting", msg)
6981
print(message_data['payload'])
7082
print("%d ================= RECEIVED :) :) :) "%time.ticks_ms())
7183

@@ -99,16 +111,20 @@ def __init__(self, ble_comm):
99111
self._timer = Timer.Alarm(self.interval_cb, self.INTERVAL, periodic=True)
100112

101113
def put(self, bytes):
102-
with self.q_lock:
103-
self.q = self.q + bytes
114+
if(self.ble_comm.status['connected']):
115+
with self.q_lock:
116+
self.q = self.q + bytes
117+
print("q=",self.q, " bytes=",bytes)
104118

105-
##Notification necessary
106-
# chunks = [ self.q[i:i+self.HEADSIZE] for i in range(0, len(self.q), self.HEADSIZE) ]
107-
# for chunk in chunks:
108-
# self.chr.value(chunk)
109-
#
110-
# self.chr.value('')
111-
# self.chr.value(bytes)
119+
##Notification necessary
120+
chunks = [ self.q[i:i+self.HEADSIZE] for i in range(0, len(self.q), self.HEADSIZE) ]
121+
for chunk in chunks:
122+
self.chr.value(chunk)
123+
print("chunk=",chunk, " len=", len(chunk))
124+
125+
self.chr.value('')
126+
# self.chr.value(bytes)
127+
# print("bytes", bytes)
112128

113129
def interval_cb(self, alarm):
114130
self.call_cnt = self.call_cnt + 1
@@ -149,15 +165,15 @@ def __init__(self, ble_comm):
149165

150166
self.chr.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=self.cb_handler)
151167

152-
def cb_handler(self, chr):
168+
def cb_handler(self, chr, data):
153169
events = chr.events()
154170
if events & Bluetooth.CHAR_WRITE_EVENT:
155171
self.last_value = chr.value()
156-
#print("Write request with value = {}".format(self.last_value))
172+
# print("Write request with value = {}".format(self.last_value))
157173

158174
self.on_write(self.last_value)
159175
else:
160-
#print('Read request on char 1')
176+
# print('Read request on char 1')
161177
return self.last_value
162178

163179
class RPCHandler:
@@ -171,9 +187,12 @@ def __init__(self, rx_worker, tx_worker, mesh, ble_comm):
171187

172188
tx_worker.on_write = self.feed
173189

190+
self.rtc = None
191+
174192
def feed(self, message):
175-
#print('feeding (rpc)', message)
193+
print('feeding (rpc)', message)
176194
self.unpacker.feed(message)
195+
print('will try')
177196
try:
178197
[self.resolve(x) for x in self.unpacker]
179198
except Exception as e:
@@ -185,8 +204,9 @@ def feed(self, message):
185204

186205

187206
def resolve(self, obj):
188-
#print('resolving: ', obj)
207+
print('resolving: ', obj)
189208
obj = list(obj)
209+
# print("obj: "obj)
190210
type = obj[0]
191211

192212
if type == 'call':
@@ -212,8 +232,8 @@ def resolve(self, obj):
212232
return
213233

214234

215-
#print('result', result)
216-
#print('message', message)
235+
# print('result', result)
236+
print('message', message)
217237
self.rx_worker.put(message)
218238

219239
# def demo_echo_fn(self, *args):
@@ -278,6 +298,23 @@ def get_node_info(self, mac_id = ' '):
278298
return node_info
279299

280300
def send_message(self, data):
301+
""" sends a message with id, to m(MAC)
302+
return True if there is buffer to store it (to be sent)"""
303+
""" data is dictionary data = {
304+
'to': 0x5,
305+
'b': 'text',
306+
'id': 12345,
307+
'ts': 123123123,
308+
}"""
309+
# if self.rtc == None:
310+
# ts_rcvd = time.localtime(data['ts'])/1000
311+
# self.rtc=RTC()
312+
# self.rtc.init(ts_rcvd)
313+
# print("ts=", data['ts'])
314+
print("%d: Send Msg ---------------------->>>>>>>> "%time.ticks_ms())
315+
return self.mesh.send_message(data)
316+
317+
def get_gps(self, data):
281318
""" sends a message with id, to m(MAC)
282319
return True if there is buffer to store it (to be sent)"""
283320
""" data is dictionary data = {
@@ -313,11 +350,13 @@ def receive_message(self):
313350
} """
314351
return self.mesh.get_rcv_message()
315352

316-
def gps(self):
317-
return self.mesh.get_gps()
353+
def set_mesh_key(self, key):
354+
rslt = self.mesh.set_mesh_key(key)
355+
return rslt
318356

319-
def battery(self):
320-
return self.mesh.get_battery()
357+
def get_mesh_key(self):
358+
key = self.mesh.get_mesh_key()
359+
return key
321360

322361
# def send_image(self, data):
323362
# """ sends an image

pymesh/pymesh_frozen/lib/ble_services.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
from network import Bluetooth
99
import time
1010
import msgpack
11+
import machine
12+
import ubinascii
1113

1214
VERSION = "1.0.0"
1315

@@ -18,7 +20,7 @@ def __init__(self, ble_name):
1820
self.ble_name = ble_name
1921
self.on_disconnect = None
2022
self._init()
21-
23+
2224
def _init(self):
2325
self.status = {
2426
'connected' : False
@@ -40,6 +42,21 @@ def _init(self):
4042

4143
self.unpacker = None
4244

45+
srv_mac = bluetooth.service(uuid=0xee00, isprimary=True)
46+
self.chr_mac = srv_mac.characteristic(uuid=0xee0e, permissions=(1 << 0), properties=(1 << 1) | (1 << 4), value='mac')
47+
48+
self.chr_mac.callback(trigger=Bluetooth.CHAR_READ_EVENT, handler=self.chr_mac_handler)
49+
50+
def chr_mac_handler(self, chr, data):
51+
events = chr.events()
52+
if events & Bluetooth.CHAR_READ_EVENT:
53+
ble_mac_str = ubinascii.hexlify(machine.unique_id()).decode("utf-8")
54+
ble_mac_int = int(ble_mac_str,16) + 2
55+
ble_mac_str = str(hex(ble_mac_int))
56+
b=ble_mac_str[2:]
57+
ble_mac_str=b[:2]+":"+b[2:4]+":"+b[4:6]+":"+b[6:8]+":"+b[8:10]+":"+b[10:]
58+
chr.value(ble_mac_str.upper())
59+
4360
def conn_cb(self, bt_o):
4461
#global ble_connected
4562
events = bt_o.events()
@@ -77,4 +94,3 @@ def restart(self):
7794
# time.sleep(1)
7895
# self._init()
7996
pass
80-

pymesh/pymesh_frozen/lib/cli.py

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,16 @@ def process(self, arg1, arg2):
5757
if cmd == 'ip':
5858
print(self.mesh.ip())
5959

60+
elif cmd == 'key':
61+
try:
62+
key = input('(key)<')
63+
except:
64+
continue
65+
if key != '':
66+
self.mesh.set_mesh_key(key)
67+
else:
68+
print(self.mesh.get_mesh_key())
69+
6070
elif cmd == 'battery':
6171
print("Battery: ", str(self.mesh.get_battery())+"%")
6272

@@ -83,12 +93,13 @@ def process(self, arg1, arg2):
8393
print("self info:", node_info)
8494

8595
elif cmd == 'mni':
86-
for mac in last_mesh_mac_list:
87-
node_info = self.mesh.get_node_info(mac)
88-
time.sleep(.5)
89-
if len(node_info) > 0:
90-
last_mesh_node_info[mac] = node_info
91-
print('last_mesh_node_info', json.dumps(last_mesh_node_info))
96+
if len(last_mesh_mac_list) != 0:
97+
for mac in last_mesh_mac_list[0]:
98+
node_info = self.mesh.get_node_info(mac)
99+
time.sleep(.5)
100+
if len(node_info) > 0:
101+
last_mesh_node_info[mac] = node_info
102+
print('last_mesh_node_info', json.dumps(last_mesh_node_info))
92103

93104
elif cmd == 'mp':
94105
mesh_pairs = self.mesh.get_mesh_pairs()
@@ -119,13 +130,14 @@ def process(self, arg1, arg2):
119130
'id': 12345,
120131
'ts': int(time.time()),
121132
}
133+
# print(self.mesh.send_message(data))
122134
while repetitions > 0:
123135
print(self.mesh.send_message(data))
124136
repetitions = repetitions - 1
125137
if repetitions > 0:
126138
print("Remaining TX packets:", repetitions)
127139
time.sleep(interval)
128-
140+
129141

130142
elif cmd == 'ws':
131143
to = int(input('(to)<'))
@@ -286,7 +298,7 @@ def process(self, arg1, arg2):
286298

287299
elif cmd == "resume":
288300
self.pymesh.resume()
289-
301+
290302
elif cmd == "tx_pow":
291303
print("LoRa stats:", self.pymesh.mesh.mesh.mesh.lora.stats())
292304
tx_str = input('(tx_pow[2-20])<')
@@ -298,7 +310,7 @@ def process(self, arg1, arg2):
298310
self.pymesh.resume(tx_pow)
299311
except:
300312
print("Invalid value")
301-
313+
302314
elif cmd == "stop":
303315
self.pymesh.cli = None
304316
_thread.exit()

pymesh/pymesh_frozen/lib/gps.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from pymesh_debug import print_debug
1111
except:
1212
from _pymesh_debug import print_debug
13-
13+
1414
import time
1515
# from pytrack import Pytrack
1616
# from L76GNSS import L76GNSS
@@ -29,14 +29,14 @@ class Gps:
2929
l76 = None
3030
_timer = None
3131
#is_set = False
32-
32+
3333
@staticmethod
3434
def set_location(latitude, longitude):
3535
dlat = str(type(latitude))
3636
dlon = str(type(longitude))
3737
if dlat == dlon == "<class 'float'>":
3838
Gps.lat = latitude
39-
Gps.lon = longitude
39+
Gps.lon = longitude
4040
is_set = True
4141
else:
4242
print_debug(3, "Error parsing ", latitude, longitude)

pymesh/pymesh_frozen/lib/loramesh.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ class Loramesh:
7070
def __init__(self, config):
7171
""" Constructor """
7272
self.config_lora = config.get('LoRa')
73+
self.config_mesh = config.get('Pymesh')
7374
self._lora_init()
7475

7576
# get Lora MAC address
@@ -119,7 +120,9 @@ def _lora_init(self, tx_dBm = 14):
119120
bandwidth = self.config_lora.get("bandwidth"),
120121
sf = self.config_lora.get("sf"),
121122
tx_power = tx_dBm)
122-
self.mesh = self.lora.Mesh() #start Mesh
123+
124+
masterkey = ubinascii.unhexlify(self.config_mesh.get("key"))
125+
self.mesh = self.lora.Mesh(key=masterkey) #start Mesh
123126

124127
def pause(self):
125128
self.mesh.deinit()
@@ -133,7 +136,7 @@ def ip_mac_unique(self, mac):
133136
return ip
134137

135138
def ip_broadcast(self):
136-
ip = "ff02::1"
139+
ip = "ff03::1"
137140
return ip
138141

139142
def _add_ipv6_unicast(self):

0 commit comments

Comments
 (0)