This repository has been archived by the owner on May 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathOutputDevice.py
321 lines (263 loc) · 11.8 KB
/
OutputDevice.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import time
import json
from typing import List
from io import StringIO
from cura.CuraApplication import CuraApplication
from cura.PrinterOutput.NetworkedPrinterOutputDevice import NetworkedPrinterOutputDevice, AuthState
from cura.PrinterOutput.PrinterOutputDevice import ConnectionState
from UM.Logger import Logger
from UM.Message import Message
from UM.FileHandler.WriteFileJob import WriteFileJob
from .qt_comp import *
from .GCodeWriter import SM2GCodeWriter
class SM2OutputDevice(NetworkedPrinterOutputDevice):
def __init__(self, device_id, address, token, properties={}, **kwargs):
assert "@" in device_id
super().__init__(device_id, address, properties, **kwargs)
self._name, self._model = device_id.rsplit("@", 1)
self._token = token
self._filename = ""
self._api_prefix = ":8080/api/v1"
self._gcode_stream = StringIO()
self.setPriority(2)
self.setShortDescription("Send to {}".format(self._address)) # button
self.setDescription("Send to {}".format(self._id)) # pop menu
self.setConnectionText("Connected to {}".format(self._id))
self.authenticationStateChanged.connect(
self._onAuthenticationStateChanged)
self.connectionStateChanged.connect(self._onConnectionStateChanged)
self.writeFinished.connect(self._byebye)
self._progress = PrintJobUploadProgressMessage(self)
self._need_auth = PrintJobNeedAuthMessage(self)
def getToken(self) -> str:
return self._token
def setToken(self, token: str):
self._token = token
def getModel(self) -> str:
return self._model
def setDeviceStatus(self, status: str):
Logger.debug("%s setDeviceStatus: %s, last state: %s", self.getId(),
status, self.connectionState)
if status == "IDLE":
if self.connectionState != ConnectionState.Connected:
self.setConnectionState(ConnectionState.Connected)
elif status in ("RUNNING", "PAUSED", "STOPPED"):
if self.connectionState != ConnectionState.Busy:
self.setConnectionState(ConnectionState.Busy)
def _onConnectionStateChanged(self, id):
Logger.debug("onConnectionStateChanged: id: %s, state: %s", id,
self.connectionState)
if id != self.getId():
return
if (self.connectionState == ConnectionState.Connected
and self.authenticationState == AuthState.Authenticated):
if self._sending_gcode and not self._progress.visible:
self._progress.show()
self._upload()
def _onAuthenticationStateChanged(self):
if self.authenticationState == AuthState.Authenticated:
self._need_auth.hide()
elif self.authenticationState == AuthState.AuthenticationRequested:
self._need_auth.show()
elif self.authenticationState == AuthState.AuthenticationDenied:
self._token = ""
self._sending_gcode = False
self._need_auth.hide()
def requestWrite(self,
nodes,
file_name=None,
limit_mimetypes=False,
file_handler=None,
filter_by_machine=False,
**kwargs) -> None:
if self.connectionState == ConnectionState.Busy:
Message(title="Unable to upload",
text="{} is busy.".format(self.getId())).show()
return
if self._progress.visible or self._need_auth.visible:
Logger.info("Still working in progress.")
return
# reset
self._sending_gcode = True
self.setConnectionState(ConnectionState.Closed)
self.setAuthenticationState(AuthState.NotAuthenticated)
self.writeStarted.emit(self)
self._gcode_stream = StringIO()
job = WriteFileJob(SM2GCodeWriter(), self._gcode_stream, nodes,
SM2GCodeWriter.OutputMode.TextMode)
job.finished.connect(self._onWriteJobFinished)
message = Message(title="Preparing for upload",
progress=-1,
lifetime=0,
dismissable=False,
use_inactivity_timer=False)
message.show()
job.setMessage(message)
job.start()
def _onWriteJobFinished(self, job):
self._hello()
def _queryParams(self) -> List[QHttpPart]:
return [
self._createFormPart('name=token', self._token.encode()),
self._createFormPart('name=_', "{}".format(time.time()).encode())
]
def _hello(self) -> None:
self.postFormWithParts("/connect", self._queryParams(),
self._onRequestFinished)
def _byebye(self):
if self._token:
self.postFormWithParts(
"/disconnect", self._queryParams(),
lambda r: self.setConnectionState(ConnectionState.Closed))
def checkStatus(self):
url = "/status?token={}&_={}".format(self._token, time.time())
self.get(url, self._onRequestFinished)
def _upload(self):
Logger.debug("Start upload to {}".format(self._name))
if not self._token:
return
print_info = CuraApplication.getInstance().getPrintInformation()
job_name = print_info.jobName.strip()
print_time = print_info.currentPrintTime
material_name = "-".join(print_info.materialNames)
self._filename = "{}_{}_{}.gcode".format(
job_name, material_name,
"{}h{}m{}s".format(print_time.days * 24 + print_time.hours,
print_time.minutes, print_time.seconds))
parts = self._queryParams()
parts.append(
self._createFormPart(
'name=file; filename="{}"'.format(self._filename),
self._gcode_stream.getvalue().encode()))
self._gcode_stream.close()
self.postFormWithParts("/upload",
parts,
on_finished=self._onRequestFinished,
on_progress=self._onUploadProgress)
def _onUploadProgress(self, bytes_sent: int, bytes_total: int):
if bytes_total > 0:
perc = (bytes_sent / bytes_total) if bytes_total else 0
self._progress.setProgress(perc * 100)
self.writeProgress.emit()
def _onRequestFinished(self, reply: QNetworkReply) -> None:
http_url = reply.url().toString()
if reply.error() not in (
QNetworkReplyNetworkErrors.NoError,
QNetworkReplyNetworkErrors.
AuthenticationRequiredError # 204 is No Content, not an error
):
Logger.warning("Error %d from %s", reply.error(), http_url)
self.setConnectionState(ConnectionState.Closed)
Message(title="Error",
text=reply.errorString(),
lifetime=0,
dismissable=True).show()
return
http_code = reply.attribute(
QNetworkRequestAttributes.HttpStatusCodeAttribute)
Logger.info("Request: %s - %d", http_url, http_code)
if not http_code:
return
http_method = reply.operation()
if http_method == QNetworkAccessManagerOperations.GetOperation:
if self._api_prefix + "/status" in http_url:
if http_code == 200:
self.setAuthenticationState(AuthState.Authenticated)
resp = self._jsonReply(reply)
device_status = resp.get("status", "UNKNOWN")
self.setDeviceStatus(device_status)
elif http_code == 401:
self.setAuthenticationState(AuthState.AuthenticationDenied)
elif http_code == 204:
self.setAuthenticationState(
AuthState.AuthenticationRequested)
else:
self.setAuthenticationState(AuthState.NotAuthenticated)
elif http_method == QNetworkAccessManagerOperations.PostOperation:
if self._api_prefix + "/connect" in http_url:
if http_code == 200:
resp = self._jsonReply(reply)
token = resp.get("token")
if self._token != token:
self._token = token
self.checkStatus() # check status and upload
elif http_code == 403 and self._token:
# expired
self._token = ""
self.connect()
else:
self.setConnectionState(ConnectionState.Closed)
Message(
title="Error",
text=
"Please check the touchscreen and try again (Err: {})."
.format(http_code),
lifetime=10,
dismissable=True).show()
# elif self._api_prefix + "/disconnect" in http_url:
# self.setConnectionState(ConnectionState.Closed)
elif self._api_prefix + "/upload" in http_url:
self._progress.hide()
self.writeFinished.emit()
self._sending_gcode = False
Message(title="Sent to {}".format(self.getId()),
text="Start print on the touchscreen: {}".format(
self._filename),
lifetime=60).show()
def _jsonReply(self, reply: QNetworkReply):
try:
return json.loads(bytes(reply.readAll()).decode("utf-8"))
except json.decoder.JSONDecodeError:
Logger.warning("Received invalid JSON from snapmaker.")
return {}
class PrintJobUploadProgressMessage(Message):
def __init__(self, device: SM2OutputDevice):
super().__init__(title="Sending to {}".format(device.getId()),
progress=-1,
lifetime=0,
dismissable=False,
use_inactivity_timer=False)
self._device = device
self._gTimer = QTimer()
self._gTimer.setInterval(3 * 1000)
self._gTimer.timeout.connect(lambda: self._heartbeat())
self.inactivityTimerStart.connect(self._startTimer)
self.inactivityTimerStop.connect(self._stopTimer)
def show(self):
self.setProgress(0)
super().show()
def update(self, percentage: int):
if not self._visible:
super().show()
self.setProgress(percentage)
def _heartbeat(self):
self._device.checkStatus()
def _startTimer(self):
if self._gTimer and not self._gTimer.isActive():
self._gTimer.start()
def _stopTimer(self):
if self._gTimer and self._gTimer.isActive():
self._gTimer.stop()
class PrintJobNeedAuthMessage(Message):
def __init__(self, device: SM2OutputDevice):
super().__init__(
title="Screen authorization needed",
text="Please tap Yes on Snapmaker touchscreen to continue.",
lifetime=0,
dismissable=True,
use_inactivity_timer=False)
self._device = device
self.setProgress(-1)
self._gTimer = QTimer()
self._gTimer.setInterval(1500)
self._gTimer.timeout.connect(lambda: self._onCheck(None, None))
self.inactivityTimerStart.connect(self._startTimer)
self.inactivityTimerStop.connect(self._stopTimer)
def _startTimer(self):
if self._gTimer and not self._gTimer.isActive():
self._gTimer.start()
def _stopTimer(self):
if self._gTimer and self._gTimer.isActive():
self._gTimer.stop()
def _onCheck(self, *args, **kwargs):
self._device.checkStatus()