33https://docs.micropython.org/en/latest/library/bluetooth.html
44"""
55
6+ import time
7+
68try :
79 import bluetooth
810except ImportError : # Linux test runner may not provide bluetooth module
@@ -90,14 +92,15 @@ def onCreate(self):
9092 set_cell_value (
9193 self .table ,
9294 row = 0 ,
93- values = ("pos" , "MAC" , "RSSI" , "count" , "Name" ),
95+ values = ("pos" , "MAC" , "RSSI" , "last" , " count" , "Name" ),
9496 )
9597 set_dynamic_column_widths (self .table )
9698
9799 self .scan_count = 0
98100 self .mac2column = {}
99101 self .mac2counts = {}
100102 self .mac2name = {}
103+ self .mac2last_seen = {}
101104
102105 self .ble = bluetooth .BLE ()
103106
@@ -112,7 +115,7 @@ async def ble_scan(self):
112115 while self .scanning :
113116 print (f"async scan for { SCAN_DURATION_MS } ms..." )
114117 self .ble .gap_scan (SCAN_DURATION_MS , INTERVAL_US , WINDOW_US , True )
115- await TaskManager .sleep_ms (SCAN_DURATION_MS + 100 )
118+ await TaskManager .sleep_ms (SCAN_DURATION_MS + 500 )
116119
117120 def onResume (self , screen ):
118121 super ().onResume (screen )
@@ -139,12 +142,20 @@ def onPause(self, screen):
139142 self .ble .active (False )
140143 self .info ("BLE deactivated" )
141144
145+ def update_last_seen (self ):
146+ current_time = int (time .time ())
147+ for addr , last_seen in self .mac2last_seen .items ():
148+ last_seen_sec = int (current_time - last_seen )
149+ column_index = self .mac2column [addr ]
150+ self .table .set_cell_value (column_index , 3 , f"{ last_seen_sec } s" )
151+
142152 def ble_irq_handler (self , event : int , data : tuple ) -> None :
143153 try :
144154 if event == _IRQ_SCAN_RESULT :
145155 addr_type , addr , adv_type , rssi , adv_data = data
146156 addr = ":" .join (f"{ b :02x} " for b in addr )
147157 print (f"{ addr = } { rssi = } { len (adv_data )= } " )
158+ self .mac2last_seen [addr ] = int (time .time ())
148159 if name := decode_name (adv_data ):
149160 self .mac2name [addr ] = name
150161 else :
@@ -164,11 +175,13 @@ def ble_irq_handler(self, event: int, data: tuple) -> None:
164175 str (column_index ),
165176 addr ,
166177 f"{ rssi } dBm" ,
178+ '0s' , # Last seen since 0 sec ;)
167179 str (self .mac2counts [addr ]),
168180 name ,
169181 ),
170182 )
171183 elif event == _IRQ_SCAN_DONE :
184+ self .update_last_seen ()
172185 set_dynamic_column_widths (self .table )
173186 self .scan_count += 1
174187 self .info (
0 commit comments