forked from macdylan/Snapmaker2Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSM2OutputDeviceManager.py
More file actions
493 lines (420 loc) · 18.2 KB
/
SM2OutputDeviceManager.py
File metadata and controls
493 lines (420 loc) · 18.2 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import time
import json
from io import StringIO
from typing import List
try:
from PyQt6.QtCore import QTimer
from PyQt6.QtNetwork import (
QUdpSocket,
QHostAddress,
QHttpPart,
QNetworkRequest,
QNetworkAccessManager,
QNetworkReply)
QNetworkAccessManagerOperations = QNetworkAccessManager.Operation
QNetworkRequestAttributes = QNetworkRequest.Attribute
QNetworkReplyNetworkErrors = QNetworkReply.NetworkError
QHostAddressAny = QHostAddress.SpecialAddress.AnyIPv4
QHostAddressBroadcast = QHostAddress.SpecialAddress.Broadcast
except ImportError:
from PyQt5.QtCore import QTimer
from PyQt5.QtNetwork import (
QUdpSocket,
QHostAddress,
QHttpPart,
QNetworkRequest,
QNetworkAccessManager,
QNetworkReply
)
QNetworkAccessManagerOperations = QNetworkAccessManager
QNetworkRequestAttributes = QNetworkRequest
QNetworkReplyNetworkErrors = QNetworkReply
QHostAddressAny = QHostAddress.SpecialAddress.AnyIPv4
QHostAddressBroadcast = QHostAddress.SpecialAddress.Broadcast
from cura.CuraApplication import CuraApplication
from cura.PrinterOutput.NetworkedPrinterOutputDevice import NetworkedPrinterOutputDevice, AuthState
from cura.PrinterOutput.PrinterOutputDevice import ConnectionState
from UM.Signal import Signal
from UM.Logger import Logger
from UM.Message import Message
from UM.FileHandler.WriteFileJob import WriteFileJob
from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
from UM.Application import Application
from .SM2GCodeWriter import SM2GCodeWriter
class SM2OutputDeviceManager(OutputDevicePlugin):
"""
tokens:
{
"My3DP@Snapmaker 2 Model A350": "token1",
"MyCNC@Snapmaker 2 Model A250": "token2",
}
"""
PREFERENCE_KEY_TOKEN = "Snapmaker2PluginSettings/tokens"
discoveredDevicesChanged = Signal()
def __init__(self):
super().__init__()
self._discover_socket = QUdpSocket()
self._discover_socket.bind(QHostAddressAny)
self._discover_socket.readyRead.connect(self._udpProcessor)
self._discover_timer = QTimer()
self._discover_timer.setInterval(6000)
self._discover_timer.timeout.connect(self._onDiscovering)
self._discovered_devices = set() # set{ip:bytes, id:bytes}
self.discoveredDevicesChanged.connect(self.addOutputDevice)
app = Application.getInstance()
self._preferences = app.getPreferences()
self._preferences.addPreference(self.PREFERENCE_KEY_TOKEN, "{}")
try:
self._tokens = json.loads(
self._preferences.getValue(self.PREFERENCE_KEY_TOKEN)
)
except ValueError:
self._tokens = {}
if not isinstance(self._tokens, dict):
self._tokens = {}
Logger.log("d", "Load tokens: {}".format(self._tokens))
app.globalContainerStackChanged.connect(self.start)
app.applicationShuttingDown.connect(self.stop)
def start(self):
if self._discover_timer and not self._discover_timer.isActive():
self._onDiscovering()
self._discover_timer.start()
Logger.log("i", "Snapmaker2Plugin started.")
def stop(self):
if self._discover_socket:
self._discover_socket.abort()
if self._discover_timer and self._discover_timer.isActive():
self._discover_timer.stop()
self._saveTokens()
Logger.log("i", "Snapmaker2Plugin stopped.")
def _saveTokens(self):
updated = False
devices = self.getOutputDeviceManager().getOutputDevices()
for d in devices:
if hasattr(d, "getToken") and hasattr(d, "getModel") and d.getToken():
name = self._tokensKeyName(d.getName(), d.getModel())
if name not in self._tokens or self._tokens[name] != d.getToken():
self._tokens[name] = d.getToken()
updated = True
if updated and self._preferences:
try:
self._preferences.setValue(self.PREFERENCE_KEY_TOKEN, json.dumps(self._tokens))
Logger.log("d", "%d tokens saved." % len(self._tokens.keys()))
except ValueError:
self._tokens = {}
def startDiscovery(self):
Logger.log("i", "Discovering ...")
self._onDiscovering()
def _udpProcessor(self):
devices = set()
while self._discover_socket.hasPendingDatagrams():
data = self._discover_socket.receiveDatagram()
if data.isValid() and not data.senderAddress().isNull():
ip = data.senderAddress().toString()
try:
msg = bytes(data.data()).decode("utf-8")
if "|model:" in msg and "|status:" in msg:
devices.add((ip, msg))
else:
Logger.log("w", "Unknown device %s from %s", msg, ip)
except UnicodeDecodeError:
pass
if len(devices) and self._discovered_devices != devices:
Logger.log("i", "Discover finished, found %d devices.", len(devices))
self._discovered_devices = devices
self.discoveredDevicesChanged.emit()
def _onDiscovering(self, *args, **kwargs):
self._discover_socket.writeDatagram(b"discover", QHostAddressBroadcast, 20054)
self._saveTokens() # TODO
def addOutputDevice(self):
for ip, resp in self._discovered_devices:
Logger.log("d", "Found device [%s] %s", ip, resp)
id, name, model, status = self._parse(resp)
if not id:
continue
device = self.getOutputDeviceManager().getOutputDevice(id)
if not device:
device = SM2OutputDevice(ip, id, name, model)
self.getOutputDeviceManager().addOutputDevice(device)
key = self._tokensKeyName(name, model)
if key in self._tokens:
device.setToken(self._tokens[key])
device.setDeviceStatus(status)
def _tokensKeyName(self, name, model) -> str:
return "{}@{}".format(name, model)
def _parse(self, resp):
"""
Snapmaker-DUMMY@127.0.0.1|model:Snapmaker 2 Model A350|status:IDLE
"""
p_model = resp.find("|model:")
p_status = resp.find("|status:")
if p_model and p_status:
id = resp[:p_model]
name = id[:id.rfind("@")]
model = resp[p_model + 7:p_status]
status = resp[p_status + 8:]
return id, name, model, status
return None, None, None, None
class SM2OutputDevice(NetworkedPrinterOutputDevice):
def __init__(self, address, device_id, name, model, **kwargs):
super().__init__(
device_id=device_id,
address=address,
properties={},
**kwargs)
self._model = model
self._name = name
self._api_prefix = ":8080/api/v1"
self._auth_token = ""
self._filename = ""
self._gcode_stream = StringIO()
self._setInterface()
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._auth_token
def setToken(self, token: str):
Logger.log("d", "%s setToken: %s", self.getId(), token)
self._auth_token = token
def getModel(self) -> str:
return self._model
def setDeviceStatus(self, status: str):
Logger.log("d", "%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.log("d", "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._auth_token = ""
self._sending_gcode = False
self._need_auth.hide()
def _setInterface(self):
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))
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.log("i", "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._auth_token.encode()),
self._createFormPart('name=_', "{}".format(time.time()).encode())
]
def _hello(self) -> None:
# if self._auth_token:
# # Closed to prevent set Connected in NetworkedPrinterOutputDevice._handleOnFinished
# self.setConnectionState(ConnectionState.Closed)
self.postFormWithParts("/connect", self._queryParams(), self._onRequestFinished)
def _byebye(self):
if self._auth_token:
self.postFormWithParts("/disconnect", self._queryParams(),
lambda r: self.setConnectionState(ConnectionState.Closed))
def checkStatus(self):
url = "/status?token={}&_={}".format(self._auth_token, time.time())
self.get(url, self._onRequestFinished)
def _upload(self):
Logger.log("d", "Start upload to {} with token {}".format(self._name, self._auth_token))
if not self._auth_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 and error
):
Logger.log("w", "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.log("i", "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._auth_token != token:
Logger.log("i", "New token: %s", token)
self._auth_token = token
self.checkStatus() # check status and upload
elif http_code == 403 and self._auth_token:
# expired
self._auth_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.log("w", "Received invalid JSON from snapmaker.")
return {}
class PrintJobUploadProgressMessage(Message):
def __init__(self, device):
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) -> None:
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) -> None:
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.addAction("", "Continue", "", "")
# self.actionTriggered.connect(self._onCheck)
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, messageId, actionId):
self._device.checkStatus()
# self.hide()