Skip to content

Commit

Permalink
Merge pull request #10 from jmsojo/patch-1
Browse files Browse the repository at this point in the history
Add automated search for COM port if one wasn't provided.
  • Loading branch information
roesel authored Aug 30, 2024
2 parents 3b79ad6 + 69201e5 commit 20cda38
Showing 1 changed file with 69 additions and 28 deletions.
97 changes: 69 additions & 28 deletions src/elliptec/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,79 @@ class Controller:
last_response = None
last_status = None

def __init__(
self,
port,
baudrate=9600,
bytesize=8,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=2,
write_timeout=0.5,
debug=True,
):
try:
self.s = serial.Serial(
port,
baudrate=baudrate,
bytesize=bytesize,
parity=parity,
stopbits=stopbits,
timeout=timeout,
write_timeout=write_timeout,
)
except serial.SerialException:
print("Could not open port {port}.")
# TODO: nicer/more logical shutdown (this kills the entire app?)
sys.exit()
def __init__(self,
port = None,
baudrate=9600,
bytesize=8,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=2,
write_timeout=0.5,
debug=True):
if port == None:
self.__search_and_connect(baudrate,
bytesize,
parity,
stopbits,
timeout,
write_timeout)
else:
self.__connect_to_port(port,
baudrate,
bytesize,
parity,
stopbits,
timeout,
write_timeout)

self.debug = debug
self.port = port
def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.close()

def __connect_to_port(self,
port,
baudrate,
bytesize,
parity,
stopbits,
timeout,
write_timeout):
try:
self.s = serial.Serial(port,
baudrate=baudrate,
bytesize=bytesize,
parity=parity,
stopbits=stopbits,
timeout=timeout,
write_timeout=write_timeout)

except serial.SerialException:
print('Could not open port %s' % port)
self.s.close()

if self.s.is_open:
if self.debug:
print(f"Controller on port {port}: Connection established!")
print('Controller on port {}: Connection established!'.format(port))

def __search_and_connect(self,
baudrate,
bytesize,
parity,
stopbits,
timeout,
write_timeout):
port_list = serial.tools.list_ports.comports()
for port in port_list:
self.__connect_to_port(port,
baudrate,
bytesize,
parity,
stopbits,
timeout,
write_timeout)
break

def __enter__(self):
return self
Expand Down

0 comments on commit 20cda38

Please sign in to comment.