Skip to content

Commit

Permalink
Enforce Exception raise when ALARM is reported by the CNC
Browse files Browse the repository at this point in the history
Sometimes the CNC does not answer to '?'.
Returns after 10 tries to get a byte considering the 1 second timeout.
In get_status, retries if there has been no answer from the CNC
  • Loading branch information
mmouchous-ledger committed Mar 28, 2024
1 parent 51e03ec commit b312ac9
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions pystages/cncrouter.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from .stage import Stage


class CNCStatus(Enum):
class CNCStatus(str, Enum):
IDLE = "Idle"
RUN = "Run"
HOLD = "Hold"
Expand All @@ -40,6 +40,14 @@ class CNCStatus(Enum):
CHECK = "Check"


class CNCError(Exception):
"""Exception raised when a specific error is detected by the CNC"""

def __init__(self, message: str, cncstatus: CNCStatus):
super().__init__(message)
self.cncstatus = cncstatus


class CNCRouter(Stage):
"""
Class to command CNC routers.
Expand Down Expand Up @@ -168,9 +176,15 @@ def get_current_status(self) -> Optional[Tuple[CNCStatus, dict]]:
:return: A tuple containing the status and a dictionary of all other parameters in the
output of the command.
"""

self.send("?", eol="")
status = self.receive()

# Retry, sometimes it does not respond
if status == b"":
self.send("?", eol="")
status = self.receive()

# Sometimes, the CNC returns 'ok' and the actual response is following.
while status == "ok":
status = self.receive()
Expand All @@ -179,8 +193,15 @@ def get_current_status(self) -> Optional[Tuple[CNCStatus, dict]]:
if status is None:
return None

# The output
# The possible outputs
# '<Idle|MPos:1.000,3.000,4.000|FS:0,0|WCO:0.000,0.000,0.000>'
# 'ALARM:1'

if status.startswith("ALARM:1"):
# The ALARM message is followed by something like
# '[MSG:Reset to continue]'
next = self.receive()
raise CNCError(next, CNCStatus.ALARM)

# Discard any unwanted format
if not (status.startswith("<") and status.endswith(">")):
Expand Down Expand Up @@ -237,10 +258,17 @@ def receive(self) -> str:
:return: Received response string, CR-LF removed.
"""
tries = 10
# Read at least 2 bytes for CR-LF.
response = self.serial.read(2)
while response[-2:] != b"\r\n":
response += self.serial.read(1)
part = self.serial.read(1)
response += part
# Give a chance to get out of this
if part == b"":
tries -= 1
if tries == 0:
return b""
# Remove CR-LF and return as string
return response[:-2].decode()

Expand Down

0 comments on commit b312ac9

Please sign in to comment.