Feature/hardware integration#17
Conversation
|
|
||
| # 2. Setup Serial Connection | ||
| try: | ||
| arduino = serial.Serial(SERIAL_PORT, 9600, timeout=1) |
There was a problem hiding this comment.
Feels weird to have this at the module global scope, where it is executed once, on import (and before anything starts up). Is this the right place for this, or should it be tucked into a function or method somewhere?
There was a problem hiding this comment.
One pattern you could use is a global variable and a function return or init.
__ARDUINO = None # Global variable for state, init to none
def get_arduino() -> serial.Serial | None:
global __ARDUINO
if not __ARDUINO: # If we haven't initialize, try to init.
try:
__ARDUINO = serial.Serial(SERIAL_PORT, 9600, timeout=1)
except Exception as e: # Fail
print(f"❌ Hardware Error on {SERIAL_PORT}: {e}")
else: # Success
time.sleep(2)
print(f"✅ Connected to Arduino on {SERIAL_PORT}!")
return __ARDUINO # Return what we have. If we failed, this could be None.The benefit here is that the arduino instance isn't created until the first time it's called for, and then it is cached in the global scope. For each successive request, the cached copy is returned.
Lines like 42, 51 and 60 would need to change from:
# Current
arduino.write(b'W')
# New
get_arduino().write(b'W')| time.sleep(2) | ||
| print(f"✅ Connected to Arduino on {SERIAL_PORT}!") | ||
| except Exception as e: | ||
| print(f"❌ Hardware Error on {SERIAL_PORT}: {e}") |
There was a problem hiding this comment.
Assuming you don't do the above... do note that since you are handling the error, your script continues executing from here... but when you go call arduino in lines like 42, and you hit this error, you will crash at that point.
Consider either setting arduino to something like None and augmenting things to handle it, or adding raise after this line to re-raise the exception and crash here.
toonarmycaptain
left a comment
There was a problem hiding this comment.
I haven't tested or verified all the details, but I spot checked and it looks good.
Are there plans to test the bot in test channels in the next week or two?
No description provided.