Skip to content

Commit df0392b

Browse files
committed
refactor timeout check
1 parent 3e1c9cc commit df0392b

File tree

1 file changed

+19
-24
lines changed

1 file changed

+19
-24
lines changed

adafruit_rfm69.py

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,7 @@
5757
try:
5858
import supervisor
5959

60-
if hasattr(supervisor, "ticks_ms"):
61-
HAS_SUPERVISOR = True
60+
HAS_SUPERVISOR = hasattr(supervisor, "ticks_ms")
6261
except ImportError:
6362
pass
6463

@@ -144,6 +143,22 @@ def ticks_diff(ticks1, ticks2):
144143
return diff
145144

146145

146+
def check_timeout(flag, limit):
147+
"""test for timeout waiting for specified flag"""
148+
timed_out = False
149+
if HAS_SUPERVISOR:
150+
start = supervisor.ticks_ms()
151+
while not timed_out and not flag():
152+
if ticks_diff(supervisor.ticks_ms(), start) >= limit * 1000:
153+
timed_out = True
154+
else:
155+
start = time.monotonic()
156+
while not timed_out and not flag():
157+
if time.monotonic() - start >= limit:
158+
timed_out = True
159+
return timed_out
160+
161+
147162
class RFM69:
148163
"""Interface to a RFM69 series packet radio. Allows simple sending and
149164
receiving of wireless data at supported frequencies of the radio
@@ -778,17 +793,7 @@ def send(
778793
self.transmit()
779794
# Wait for packet sent interrupt with explicit polling (not ideal but
780795
# best that can be done right now without interrupts).
781-
timed_out = False
782-
if HAS_SUPERVISOR:
783-
start = supervisor.ticks_ms()
784-
while not timed_out and not self.packet_sent():
785-
if ticks_diff(supervisor.ticks_ms(), start) >= self.xmit_timeout * 1000:
786-
timed_out = True
787-
else:
788-
start = time.monotonic()
789-
while not timed_out and not self.packet_sent():
790-
if time.monotonic() - start >= self.xmit_timeout:
791-
timed_out = True
796+
timed_out = check_timeout(self.packet_sent, self.xmit_timeout)
792797
# Listen again if requested.
793798
if keep_listening:
794799
self.listen()
@@ -860,17 +865,7 @@ def receive(
860865
# interrupt supports.
861866
# Make sure we are listening for packets.
862867
self.listen()
863-
timed_out = False
864-
if HAS_SUPERVISOR:
865-
start = supervisor.ticks_ms()
866-
while not timed_out and not self.payload_ready():
867-
if ticks_diff(supervisor.ticks_ms(), start) >= timeout * 1000:
868-
timed_out = True
869-
else:
870-
start = time.monotonic()
871-
while not timed_out and not self.payload_ready():
872-
if time.monotonic() - start >= timeout:
873-
timed_out = True
868+
timed_out = check_timeout(self.payload_ready, timeout)
874869
# Payload ready is set, a packet is in the FIFO.
875870
packet = None
876871
# save last RSSI reading

0 commit comments

Comments
 (0)