Skip to content

Commit b312ac9

Browse files
Enforce Exception raise when ALARM is reported by the CNC
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
1 parent 51e03ec commit b312ac9

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

pystages/cncrouter.py

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from .stage import Stage
3131

3232

33-
class CNCStatus(Enum):
33+
class CNCStatus(str, Enum):
3434
IDLE = "Idle"
3535
RUN = "Run"
3636
HOLD = "Hold"
@@ -40,6 +40,14 @@ class CNCStatus(Enum):
4040
CHECK = "Check"
4141

4242

43+
class CNCError(Exception):
44+
"""Exception raised when a specific error is detected by the CNC"""
45+
46+
def __init__(self, message: str, cncstatus: CNCStatus):
47+
super().__init__(message)
48+
self.cncstatus = cncstatus
49+
50+
4351
class CNCRouter(Stage):
4452
"""
4553
Class to command CNC routers.
@@ -168,9 +176,15 @@ def get_current_status(self) -> Optional[Tuple[CNCStatus, dict]]:
168176
:return: A tuple containing the status and a dictionary of all other parameters in the
169177
output of the command.
170178
"""
179+
171180
self.send("?", eol="")
172181
status = self.receive()
173182

183+
# Retry, sometimes it does not respond
184+
if status == b"":
185+
self.send("?", eol="")
186+
status = self.receive()
187+
174188
# Sometimes, the CNC returns 'ok' and the actual response is following.
175189
while status == "ok":
176190
status = self.receive()
@@ -179,8 +193,15 @@ def get_current_status(self) -> Optional[Tuple[CNCStatus, dict]]:
179193
if status is None:
180194
return None
181195

182-
# The output
196+
# The possible outputs
183197
# '<Idle|MPos:1.000,3.000,4.000|FS:0,0|WCO:0.000,0.000,0.000>'
198+
# 'ALARM:1'
199+
200+
if status.startswith("ALARM:1"):
201+
# The ALARM message is followed by something like
202+
# '[MSG:Reset to continue]'
203+
next = self.receive()
204+
raise CNCError(next, CNCStatus.ALARM)
184205

185206
# Discard any unwanted format
186207
if not (status.startswith("<") and status.endswith(">")):
@@ -237,10 +258,17 @@ def receive(self) -> str:
237258
238259
:return: Received response string, CR-LF removed.
239260
"""
261+
tries = 10
240262
# Read at least 2 bytes for CR-LF.
241263
response = self.serial.read(2)
242264
while response[-2:] != b"\r\n":
243-
response += self.serial.read(1)
265+
part = self.serial.read(1)
266+
response += part
267+
# Give a chance to get out of this
268+
if part == b"":
269+
tries -= 1
270+
if tries == 0:
271+
return b""
244272
# Remove CR-LF and return as string
245273
return response[:-2].decode()
246274

0 commit comments

Comments
 (0)