55class ElectroBlocks :
66
77 last_sense_data = ""
8+ verbose = False
89
9- def __init__ (self , baudrate = 115200 , timeout = 2 ):
10+ def __init__ (self , baudrate = 9600 , timeout = 2 , verbose = False ):
1011 self .ser = self ._auto_connect (baudrate , timeout )
12+ self .verbose = verbose
1113 self ._wait_for_ready ()
1214
1315 def _auto_connect (self , baudrate , timeout ):
@@ -22,17 +24,31 @@ def _auto_connect(self, baudrate, timeout):
2224 print (f"Failed to connect to { e } . Trying next port..." )
2325 continue
2426 raise Exception ("No Arduino Uno or Mega found." )
27+
28+ def _drain_serial (self ):
29+ """Drains/clears the serial port input buffer of any unread messages."""
30+ if self .ser and self .ser .is_open :
31+ self .ser .reset_input_buffer ()
32+
2533
2634 def _wait_for_message (self , message ):
27- while True :
35+ count = 0
36+ while count < 10 :
2837 if self .ser .in_waiting :
2938 line = self .ser .readline ().decode ("utf-8" , errors = "ignore" ).strip ()
3039 if message in line :
3140 return line
41+ count += 1
42+ time .sleep (0.05 )
43+ if self .verbose :
44+ print (f"DEBUG: MESSAGE NOT FOUND: '{ message } '" )
45+ return ""
3246
3347 def _get_sensor_str (self ):
34- self ._send ( "sense" )
48+ self .ser . write ( b "sense| " )
3549 message = self ._wait_for_message ("SENSE_COMPLETE" )
50+ if self .verbose :
51+ print (f"FULL SENSOR MESSSAGE: { message } " )
3652 message = message .replace ("SENSE_COMPLETE" , "" )
3753 sensorsStr = message .split (";" )
3854 return sensorsStr
@@ -64,6 +80,23 @@ def config_digital_read(self, pin):
6480 def digital_read (self , pin ):
6581 return self ._find_sensor_str (pin , "dr" ) == "1"
6682
83+ # RFID
84+ def config_rfid (self , rxPin , txPin ):
85+ self ._send (f"config:rfid={ rxPin } ,{ txPin } " )
86+
87+ def rfid_card_number (self ):
88+ sensedata = self ._find_sensor_str ("0" , "rfid" )
89+ datum = sensedata .split ("-" )
90+ print (sensedata , datum )
91+ return datum [0 ] if len (datum ) == 2 else ""
92+
93+ def rfid_tag_number (self ):
94+ sensedata = self ._find_sensor_str ("0" , "rfid" )
95+ datum = sensedata .split ("-" )
96+ print (sensedata , datum )
97+ return datum [1 ] if len (datum ) == 2 else ""
98+
99+
67100 # Motion Sensors
68101 def config_motion_sensor (self , echoPin , trigPin ):
69102 self ._send (f"config:m={ echoPin } ,{ trigPin } " )
0 commit comments