Skip to content

Instantly share code, notes, and snippets.

@dantaeyoung
Created May 23, 2019 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dantaeyoung/39022ebb2b1100baa97b0a9626973339 to your computer and use it in GitHub Desktop.
Save dantaeyoung/39022ebb2b1100baa97b0a9626973339 to your computer and use it in GitHub Desktop.
ntoo serial thread that detects errors and reconnects without crashing the whole program - belongs in `chatbot/inference_sensors.py`
def serial_thread():
ser = None
while True:
try:
# TRIES TO CONNECT
if(ser == None):
ser = serial.Serial(usbport)
ser.flushInput()
logger.log("[SERIAL] (Re)connecting serial thread...")
except:
# IF DOESN'T CONNECT, then disconnects and/or waits a bit
if(not(ser == None)):
ser.close()
ser = None
print("[SERIAL] Disconnecting")
logger.log("[SERIAL] Disconnecting")
print("[SERIAL] No Connection.. waiting for a bit to reconnect")
logger.log("[SERIAL] No Connection.. waiting for a bit to reconnect")
time.sleep(2)
else:
# IF SUCCESSFULLY CONNECTED, then do stuff
ser_bytes = ser.readline()
decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
print(decoded_bytes)
if decoded_bytes == 0.0:
sleep_bot()
else:
restart_bot()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment