-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsimulated_RFM95.py
72 lines (53 loc) · 2.02 KB
/
simulated_RFM95.py
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
import time
import random
from setup_logger import logger
class RFM95():
"""Fake communication devices of subclass of adafruit_rfm9x.RFM95
Example of how to use it:
Send a fake message:
>>> my_frm95 = RFM95()
>>> my_rfm95.send("Hello world!") # Do nothing
Receive a fake message:
>>> my_rfm95 = RFM95()
>>> my_rfm95.receive() # returns sometime something
Hello world!
"""
def __init__(self):
pass
def receive(self, timeout=0.5, keep_listening=True, with_header=False, rx_filter=255):
# sometime, return the last packet (it has to be ignored)
if random.choice([True, False]):
try: # maybe there is no last packet
return self.last_packet
except:
pass
time_until_next_message = random.uniform(0, 3)
if time_until_next_message > timeout: # No message
time.sleep(timeout)
return None
# else : a message !
b_id_from = (random.randint(0, 10)).to_bytes(1, 'big')
b_id_to = (random.randint(0, 3)).to_bytes(1, 'big')
# b_id_to = (255).to_bytes(1, 'big')
b_id_message = (random.randint(0, 254)).to_bytes(1, 'big')
b_flags = (0).to_bytes(1, 'big')
packet = b'hi'
if with_header:
packet = b_id_from+b_id_to+b_id_message+b_flags+packet
time.sleep(time_until_next_message)
logger.debug('packet received : {}'.format(packet))
self.last_packet = packet
return packet
def send(self, data, timeout=2.0, keep_listening=False, tx_header=(255, 255, 0, 0)):
packet = (
tx_header[0].to_bytes(1, 'big')
+ tx_header[1].to_bytes(1, 'big')
+ tx_header[2].to_bytes(1, 'big')
+ tx_header[3].to_bytes(1, 'big')
+ data)
logger.debug('packet sent : {}'.format(packet))
if __name__ == '__main__':
rfm95 = RFM95()
my_message = b'hello world'
rfm95.send(my_message)
print(rfm95.receive(timeout=5, with_header=True))