-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultimaker.py
1589 lines (1489 loc) · 67.4 KB
/
ultimaker.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
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
An object-oriented model of working with the Ultimaker API. The primary class is the Ultimaker
class which deals with communication with the printer and authentication if necessary. A few of
the pieces of the API that are not well documented (e.g. wifi networks) are possibly not implemented
correctly but the vast majority of parts are tested and working correctly.
Instead of accessing the API through a URL like http://<ip>/api/v1/printer/status attribute lookup
is used:
u = Ultimaker('<ip_or_hostname>')
u.printer.status
Any simple put/post operations can be done with assignments, such as:
u.printer.led.hue = 0.5
There are several functions as well for dealing with more complex requests. If any request requires
authentication and no authentication is provided to the Ultimaker constructor, then a username is
made up and a password is requested from the printer itself, however this requires the user to
accept the connection on the printer itself. The credentials are saved on this machine and won't
be required again.
"""
import copy, time, datetime, os # pylint: disable=multiple-imports
from enum import Enum
import collections.abc
from collections.abc import Sequence, Mapping
import requests
from requests.auth import HTTPDigestAuth
# pylint: disable=protected-access, multiple-statements
# pylint: disable=missing-docstring
def _dt(string): return None if not string else datetime.datetime.fromisoformat(string.rstrip("Z"))
def _extract(dictionary, *keys): return {k:dictionary[k] for k in keys}
class Ultimaker:
def __init__(self, hostname, username=None, password=None):
self._hostname = hostname
if username is not None and password is not None:
self._auth = HTTPDigestAuth(username, password)
def __eq__(self, other):
return isinstance(other, Ultimaker) and self._hostname == other._hostname
def __ne__(self, other): return not self == other
def _url(self, cmd): return 'http://'+self._hostname+'/api/v1/'+cmd
@staticmethod
def _check_response(response):
if response.status_code == 204: return None
if response.status_code == 405: raise AttributeError()
if not response:
try: data = response.json()
except ValueError: data = {}
if 'message' in data:
if response.status_code == 404:
raise KeyError(data['message'])
raise ValueError(data['message'])
else: response.raise_for_status()
res = response.json()
if isinstance(res, dict) and (res.get('return_value', 1) in (0, False) or
res.get('result', 1) in (0, False)):
raise ValueError('invalid value')
return res
_auth = None
def _get_auth(self):
if self._auth is None:
# Try to load a saved copy of the authetication credentials
if not self.auth.load():
id,key = self.auth.acquire('ultimaker-py-api')
self._id = id
self._key = key
self.auth.store()
return self._auth
def _get(self, cmd):
return Ultimaker._check_response(requests.get(self._url(cmd), auth=self._auth))
def _put(self, cmd, data):
return Ultimaker._check_response(requests.put(self._url(cmd),
json=data, auth=self._get_auth()))
def _post(self, cmd, data):
return Ultimaker._check_response(requests.post(self._url(cmd),
json=data, auth=self._get_auth()))
def _delete(self, cmd, data=None):
return Ultimaker._check_response(requests.delete(self._url(cmd),
json=data, auth=self._get_auth()))
def _get_file(self, cmd):
response = requests.get(self._url(cmd), auth=self._get_auth())
response.raise_for_status()
return response.text
def _post_file(self, cmd, file, data=None):
# file can be:
# a string with a filename
# a file-like object (should have a name attribute)
# a tuple of filename and file-like object
# a tuple of filename and data
# a dictionary of that can be immediately passed to requests
# file-like objects should be open in 'rb' mode
if isinstance(file, dict):
files = file
elif isinstance(file, str):
files = {'file':(os.path.basename(file), open(file, 'rb'))}
return Ultimaker._check_response(
requests.post(self._url(cmd), data=data, files=files, auth=self._get_auth()))
def _put_file(self, cmd, file, data=None):
if isinstance(file, dict): files = file
elif isinstance(file, str): files = {'file':(os.path.basename(file), open(file, 'rb'))}
return Ultimaker._check_response(requests.put(self._url(cmd), data=data, files=files,
auth=self._get_auth()))
@property
def id(self): return self._auth.username #pylint: disable=invalid-name
@property
def key(self): return self._auth.password
@property
def auth(self): return Auth(self)
@property
def materials(self): return Materials(self)
@property
def printer(self): return Printer(self)
@property
def network(self): return PrinterNetwork(self)
@property
def print_job(self): return PrintJob(self)
@property
def system(self): return System(self)
@property
def history(self): return History(self)
@property
def camera(self): return Camera(self)
class Auth:
def __init__(self, ultimaker): self._ultimaker = ultimaker
def __eq__(self, other): return isinstance(other, Auth) and self._ultimaker == other._ultimaker
def __ne__(self, other): return not self == other
def request(self, application, user=None, host_name=None, exclusion_key=None):
if user is None:
from getpass import getuser
user = getuser()
if host_name is None:
import platform
host_name = platform.node()
data = {'application':application, 'user':user, 'host_name':host_name}
if exclusion_key is not None: data['exclusion_key'] = exclusion_key
response = requests.post(self._ultimaker._url('auth/request'), data=data)
if response.status_code != 200: response.raise_for_status()
data = Ultimaker._check_response(response)
return data["id"], data["key"]
# Returns one of 'authorized', 'unknown' (currently prompting), or 'unauthorized'
# 'authorized' is only returned for a short time after the authentication acquisition process,
# otherwise everyone is marked as 'unauthorized'
def check(self, id_): return self._ultimaker._get('auth/check/'+id_)["message"]
def verify(self, auth=None):
response = requests.get(self._ultimaker._url('auth/verify'),
auth=auth or self._ultimaker._auth)
return response.status_code == 200 and response.json()["message"] == "ok"
# otherwise:
# response.status_code == 403 and response.json()["message"] == "Authorization required."
def acquire(self, application, user=None, host_name=None, exclusion_key=None, set_auth=True):
"""
Combination of request(), check(), and verify(). By default this also replaces the
authorization on the Ultimaker with the new authorization if successful. Turn it off by
passing set_auth=False. Always returns the id/key acquired if successful. If not successful
a PermissionError is raised.
"""
# Create the id and key
id_, key = self.request(application, user, host_name, exclusion_key)
# Wait for the user to choose an option
while self.check(id_) == "unknown": time.sleep(0.25)
# Raise an error if denied
if self.check(id_) == "unauthorized": raise PermissionError()
# Establish the authentication and verify
auth = HTTPDigestAuth(id_, key)
if not self.verify(auth): raise PermissionError()
if set_auth: self._ultimaker._auth = auth
# Return the results
return id_, key
@staticmethod
def _user_config_dir(appname):
import sys
system = sys.platform
if system.startswith('java'):
import platform
os_name = platform.java_ver()[3][0]
if os_name.startswith('Windows'): system = 'win32'
elif os_name.startswith('Mac'): system = 'darwin'
else: system = 'linux2'
if system == "win32":
import ctypes
buf = ctypes.create_unicode_buffer(4096)
ctypes.windll.shell32.SHGetFolderPathW(None, 28, None, 0, buf)
if any(ord(c) > 255 for c in buf):
buf2 = ctypes.create_unicode_buffer(4096)
if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 4096):
buf = buf2
path = os.path.normpath(buf.value)
elif system == 'darwin': path = os.path.expanduser('~/Library/Application Support/')
else: path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config"))
return os.path.join(path, appname)
@staticmethod
def _get_config_path():
appdir = Auth._user_config_dir('ultimaker-py-api')
os.makedirs(appdir, exist_ok=True)
config_path = os.path.join(appdir, 'config.ini')
with open(config_path, 'a') as file: file.write('')
return config_path
def store(self):
from configparser import ConfigParser
config_path = Auth._get_config_path()
config = ConfigParser()
config.read(config_path)
hostname = self._ultimaker._hostname
config.setdefault(hostname, {})
config[hostname]['id'] = self._ultimaker._id
config[hostname]['key'] = self._ultimaker._key
with open(config_path, 'w') as file: config.write(file)
def load(self):
from configparser import ConfigParser
config = ConfigParser()
config.read(Auth._get_config_path())
hostname = self._ultimaker._hostname
if hostname not in config: return False
info = config[hostname]
auth = HTTPDigestAuth(info['id'], info['key'])
if not self.verify(auth): return False
self._ultimaker._auth = auth
return True
class _Mapping(Mapping):
"""
A collection of objects that are treated as a dictionary or mapping. This is used for the
Materials which map GUIDs to Material objects and Wifi Networks which maps SSIDs to Wifi
Networks. In both cases the keys are strings. The length of the collection is cached between
calls. Nothing else is cached.
You can also remove items using `del mapping[key]` or `mapping.clear()` however this only works
in special situations.
Additionally the concrete classes have some additional methods for adding or setting.
"""
_subtype = None
class KeysView(collections.abc.KeysView): # pylint: disable=too-many-ancestors
def __len__(self): return len(self._mapping)
def __contains__(self, key): return key in self._mapping
def __iter__(self): return iter(self._mapping)
class ValuesView(collections.abc.ValuesView):
def __len__(self): return len(self._mapping)
def __contains__(self, value):
return isinstance(value, self._mapping._subtype) and \
self._mapping.get(self._mapping._get_key(value)) == value
def __iter__(self):
subtype = self._mapping._subtype
for value in self._mapping.raw: yield subtype(value)
class ItemsView(collections.abc.ItemsView): # pylint: disable=too-many-ancestors
def __len__(self): return len(self._mapping)
def __contains__(self, item):
return (isinstance(item, tuple) and len(item) == 2 and
isinstance(item[0], str) and isinstance(item[1], self._mapping._subtype) and
item[1] == self._mapping.get(item[0]))
def __iter__(self):
for value in self._mapping.raw:
value = self._mapping._subtype(value)
yield (self._mapping._get_key(value), value)
# pylint: disable=not-callable
_subtype = None # concrete class must specify this along with _get_key below
_len = -1
def __init__(self, ultimaker, base):
self._ultimaker = ultimaker
self._base = base
@classmethod
def _get_key(cls, value): raise NotImplementedError()
@property
def raw(self): return self._ultimaker._get(self._base)
def __iter__(self):
subtype = self._subtype
for entry in self.raw: yield self._get_key(subtype(entry))
def keys(self): return _Mapping.KeysView(self)
def values(self): return _Mapping.ValuesView(self)
def items(self): return _Mapping.ItemsView(self)
def __len__(self):
if self._len == -1: self._len = len(self.raw)
return self._len
def __contains__(self, key):
# Simple implementation of this, best to overload with better if possible
try:
_ = self[key]
return True
except KeyError: return False
def __getitem__(self, key):
# Simple implementation of this, best to overload with better if possible
for k, value in self.items():
if k == key: return value
raise KeyError
def get(self, key, default=None):
try: return self[key]
except (ValueError, KeyError): return default
def __eq__(self, other):
if not isinstance(other, _Mapping) or self._base != other._base: return False
a, b = self.raw, other.raw # pylint: disable=invalid-name
if a == b: return True
if len(a) != len(b): return False
a.sort()
b.sort()
return a == b
def __ne__(self, other): return not self == other
# Deleting Items
def __delitem__(self, key):
self._ultimaker._delete('%s/%s'%(self._base, key))
self._len = -1
def clear(self):
count = 0
for key in self:
try:
del self[key]
count += 1
except (ValueError, KeyError): pass
return count
class Material: # pylint: disable=too-many-public-methods, too-many-instance-attributes
@staticmethod
def _opt_val(node, conv=str):
return None if node is None else conv(node.text)
@staticmethod
def _opt_vals(node, tags, namespace):
out = {}
for tag in tags:
val = node.find('{%s}%s' % (namespace, tag))
if val is not None: out[tag] = val.text
return out
@staticmethod
def _get_contact_info(node, namespace):
if node is None: return None
out = Material._opt_vals(node, ('organization', 'contact', 'email', 'phone'), namespace)
addr = node.find('{%s}%s'%(namespace, 'address'))
if addr is not None:
out['address'] = Material._opt_vals(addr, (
'street', 'city', 'region', 'zip', 'country'
), namespace)
return out
@staticmethod
def _get_settings(node, namespace):
settings = {}
for setting in node.iterfind('{%s}setting'%namespace):
key = setting.attrib['key']
points = setting.findall('{%s}point'%namespace)
if points:
val = [{k:float(v) for k, v in pt.attrib.items()} for pt in points]
else:
val = setting.text
val = val == 'yes' if val in ('yes', 'no') else float(val)
settings[key] = val
return settings
def __init__(self, xml):
from xml.etree import ElementTree
self.__xml = xml
ns = 'http://www.ultimaker.com/material' # pylint: disable=invalid-name
root = ElementTree.fromstring(xml) # fdmmaterial
self.__xml_doc_version = root.attrib['version']
metadata = root.find('{%s}metadata'%ns)
name = metadata.find('{%s}name'%ns)
self.__brand = name.find('{%s}brand'%ns).text
self.__material = name.find('{%s}material'%ns).text
self.__color = name.find('{%s}color'%ns).text
self.__label = Material._opt_val(name.find('{%s}label'%ns))
self.__guid = metadata.find('{%s}GUID'%ns).text
self.__version = int(metadata.find('{%s}version'%ns).text)
self.__color_code = metadata.find('{%s}color_code'%ns).text
self.__description = Material._opt_val(metadata.find('{%s}description'%ns))
self.__adhesion_info = Material._opt_val(metadata.find('{%s}adhesion_info'%ns))
self.__instruction_link = Material._opt_val(metadata.find('{%s}instruction_link'%ns))
self.__ean = Material._opt_val(metadata.find('{%s}EAN'%ns))
self.__tds = Material._opt_val(metadata.find('{%s}TDS'%ns))
self.__msds = Material._opt_val(metadata.find('{%s}MSDS'%ns))
self.__supplier = Material._get_contact_info(metadata.find('{%s}supplier'%ns), ns)
self.__author = Material._get_contact_info(metadata.find('{%s}author'%ns), ns)
props = root.find('{%s}properties'%ns)
self.__diameter = float(props.find('{%s}diameter'%ns).text)
self.__density = Material._opt_val(props.find('density'), float)
self.__weight = Material._opt_val(props.find('weight'), float)
settings = root.find('{%s}settings'%ns)
self.__settings = Material._get_settings(settings, ns)
self.__machines = [{
'machine_identifiers':
[mi.attrib for mi in machine.iterfind('{%s}machine_identifier'%ns)],
'hotends':
{he.attrib['id']:Material._get_settings(he, ns) \
for he in machine.iterfind('{%s}hotend'%ns)},
'buildplates':
{bp.attrib['id']:Material._get_settings(bp, ns) \
for bp in machine.iterfind('{%s}buildplate'%ns)},
'settings': Material._get_settings(machine, ns),
} for machine in settings.iterfind('{%s}machine'%ns)]
@property
def raw(self): return self.__xml
@property
def dict(self):
return {'metadata':self.metadata,
'properties':self.properties,
'settings':self.settings,
'machines':self.machines}
def __str__(self): return self.guid + ' ' + self.name
def __eq__(self, other):
return isinstance(other, Material) and \
self.__guid == other.__guid and self.metadata == other.metadata
def __ne__(self, other): return not self == other
def __hash__(self): return hash(self.__guid)
@property
def xml_document_version(self): return self.__xml_doc_version
@property
def metadata(self):
data = {'name':self.name_data, 'guid':self.__guid,
'version':self.__version, 'color_code':self.__color_code}
for name in ('description', 'adhesion_info', 'instruction_link', 'ean', 'tds', 'msds'):
val = getattr(self, '_Material__'+name)
if val is not None: data[name] = val
if self.__supplier is not None: data['supplier'] = self.supplier
if self.__author is not None: data['author'] = self.author
return data
@property
def name(self):
name = '%s %s' % (self.__brand, self.__material)
if self.__color != 'Generic': name += ' - %s' % self.__color
if self.__label is not None: name += ' (%s)' % self.__label
return name
@property
def name_data(self):
data = {'brand': self.__brand, 'material': self.__material, 'color': self.__color}
if self.__label is not None: data['label'] = self.__label
return data
@property
def brand(self): return self.__brand
@property
def material(self): return self.__material
@property
def color(self): return self.__color
@property
def label(self): return self.__label
@property
def guid(self): return self.__guid
@property
def version(self): return self.__version
@property
def color_code(self): return self.__color_code
@property
def description(self): return self.__description
@property
def adhesion_info(self): return self.__adhesion_info
@property
def instruction_link(self): return self.__instruction_link
@property
def ean(self): return self.__ean
@property
def tds(self): return self.__tds
@property
def msds(self): return self.__msds
@property
def supplier(self): return copy.deepcopy(self.__supplier)
@property
def author(self): return copy.deepcopy(self.__author)
@property
def properties(self):
data = {'diameter':self.__diameter}
if self.__density is not None: data['density'] = self.__density
if self.__weight is not None: data['weight'] = self.__weight
return data
@property
def diameter(self): return self.__diameter
@property
def density(self): return self.__density
@property
def weight(self): return self.__weight
@property
def settings(self): return copy.deepcopy(self.__settings)
@property
def machines(self): return copy.deepcopy(self.__machines)
class Materials(_Mapping):
_subtype = Material
def __init__(self, ultimaker): super().__init__(ultimaker, 'materials')
@classmethod
def _get_key(cls, value): return value.guid
def __contains__(self, key):
try: self._ultimaker._get('%s/%s'%(self._base, key))
except (ValueError, KeyError): return False
return True
def __getitem__(self, key):
return self._subtype(self._ultimaker._get('%s/%s'%(self._base, key)))
# Adding and Updating Materials
@staticmethod
def __get_filedata(value):
from io import IOBase
if isinstance(value, IOBase): return value.read()
if isinstance(value, str):
if not os.path.isfile(value): return value
with open(value, 'rb') as file: return file.read()
raise TypeError()
@staticmethod
def __get_material(value):
if isinstance(value, Material): return value
return Material(Materials.__get_filedata(value))
@staticmethod
def __get_files(material, signature=None):
material = Materials.__get_material(material)
files = {'file':(material.guid+'.xml', material.raw)}
if signature is not None:
signature = Materials.__get_filedata(Materials)
files['signature_file'] = (material.guid+'.sig', signature)
return files
def __setitem__(self, key, value):
material = Materials.__get_material(value)
if material.guid != key: raise ValueError()
return self.add(material) if key not in self else self.update(material)
def add(self, value, signature_file=None):
material = Materials.__get_material(value)
if material.guid in self: raise KeyError()
files = Materials.__get_files(material, signature_file)
res = self._ultimaker._post_file(self._base, files)
self._len = -1
return res
def update(self, value, signature_file=None):
material = Materials.__get_material(value)
previous = self[material.guid]
if material.version <= previous.version: raise ValueError()
files = Materials.__get_files(material, signature_file)
res = self._ultimaker._put_file('%s/%s'%(self._base, material.guid), files)
self._len = -1
return res
class PrinterStatus(Enum):
IDLE = "idle"
PRINTING = "printing"
ERROR = "error"
MAINTENANCE = "maintenance"
BOOTING = "booting"
class Printer:
def __init__(self, ultimaker): self._ultimaker = ultimaker
def __eq__(self, other):
return isinstance(other, Printer) and self._ultimaker == other._ultimaker
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get('printer')
@property
def dict(self): return Printer.transform_raw(self.raw)
@staticmethod
def transform_raw(data):
del data['beep']
del data['diagnostics']
del data['validate_header']
data['led'] = PrinterLED.transform_raw(data['led'])
data['heads'] = PrinterHeads.transform_raw(data['heads'])
data['bed'] = PrinterBed.transform_raw(data['bed'])
data['network'] = PrinterNetwork.transform_raw(data['network'])
return data
@property
def diagnostics(self): return PrinterDiagnostics(self._ultimaker)
@property
def status(self): return PrinterStatus(self._ultimaker._get('printer/status'))
@property
def led(self): return PrinterLED(self._ultimaker)
@property
def head(self): return PrinterHead(self._ultimaker, 'printer/heads', 0)
@property
def heads(self): return PrinterHeads(self._ultimaker)
@property
def bed(self): return PrinterBed(self._ultimaker)
def validate_header(self, gcode):
return self._ultimaker._post_file('printer/validate_header', gcode)
def beep(self, frequency, duration):
return self._ultimaker._post('printer/beep', {
'frequency':float(frequency), 'duration':float(duration)
})
@property
def network(self): return PrinterNetwork(self._ultimaker)
class PrinterDiagnostics:
def __init__(self, ultimaker): self._ultimaker = ultimaker
def __eq__(self, other):
return isinstance(other, PrinterDiagnostics) and self._ultimaker == other._ultimaker
def __ne__(self, other): return not self == other
def cap_sensor_noise(self, loop_count=100, sample_count=50):
return self._ultimaker._get('printer/diagnostics/cap_sensor_noise/%d/%d'%(
int(loop_count), int(sample_count)
))
def temperature_flow(self, sample_count, numpy=False):
data = self._ultimaker._get('printer/diagnostics/temperature_flow/%d'%int(sample_count))
if numpy:
import numpy as np
data = np.array(data[1:])
return data
def probing_report(self):
return self._ultimaker._get('printer/diagnostics/probing_report')
class PrinterLED:
def __init__(self, ultimaker): self._ultimaker = ultimaker
def __eq__(self, other):
return isinstance(other, PrinterLED) and self._ultimaker == other._ultimaker
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get('printer/led')
@property
def dict(self): return _extract(self.raw, 'hue', 'saturation', 'brightness')
@staticmethod
def transform_raw(data): return _extract(data, 'hue', 'saturation', 'brightness')
@property
def hue(self): return self._ultimaker._get('printer/led/hue')
@hue.setter
def hue(self, value): self._ultimaker._put('printer/led/hue', float(value))
@property
def saturation(self): return self._ultimaker._get('printer/led/saturation')
@saturation.setter
def saturation(self, value): self._ultimaker._put('printer/led/saturation', float(value))
@property
def brightness(self): return self._ultimaker._get('printer/led/brightness')
@brightness.setter
def brightness(self, value): self._ultimaker._put('printer/led/brightness', float(value))
def blink(self, frequency=1, count=1):
return self._ultimaker._post('printer/led/blink', {
'frequency':float(frequency), 'count':int(count)
})
def set_color(self, h, s, b): # pylint: disable=invalid-name
return self._ultimaker._put('printer/led', {
"hue":float(h), "saturation":float(s), "brightness":float(b)
})
def set_color_rgb(self, r, g, b): # pylint: disable=invalid-name
# pylint: disable=invalid-name
mx = max(r, g, b)
mn = min(r, g, b)
if mx == mn: h = 0
elif mx == r: h = (g-b)/(mx-mn)
elif mx == g: h = 2 + (b-r)/(mx-mn)
elif mx == b: h = 4 + (r-g)/(mx-mn)
h *= 60
if h < 0: h += 360
l = (mx+mn)/2
s = 0 if mx == 0 or mn == 1 else (mx-l)/min(l, 1-l)
return self.set_color(h, s, l)
class _PrinterSeq(Sequence):
# pylint: disable=not-callable
_subtype = None
_len = -1
def __init__(self, ultimaker, base):
self._ultimaker = ultimaker
self._base = base
def __eq__(self, other):
return isinstance(other, _PrinterSeq) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def list(self): return type(self).transform_raw(self.raw)
@classmethod
def transform_raw(cls, data): return [cls._subtype.transform_raw(item) for item in data]
def __len__(self):
if self._len == -1: self._len = len(self.raw)
return self._len
def __iter__(self):
for i in range(len(self)): yield self._subtype(self._ultimaker, self._base, i)
def __reversed__(self):
for i in range(len(self)-1, -1, -1): yield self._subtype(self._ultimaker, self._base, i)
def __contains__(self, value):
return isinstance(value, self._subtype) and value._ultimaker == self._ultimaker
def index(self, value, start=None, stop=None):
if value in self: raise ValueError('not in list')
idx = int(value._base.split('/')[2])
if start is not None and start < 0: start = max(len(self) + start, 0)
if stop is not None and stop < 0: stop += len(self)
if (start is not None and idx < start) or (stop is not None and idx >= stop):
raise ValueError('not in sublist')
return idx
def count(self, value): return 1 if value in self else 0
def __getitem__(self, idx):
if idx != 0: # there will always be an index 0 so we don't need to check it
if idx < 0: idx += len(self)
if idx < 0 or idx >= len(self): raise IndexError()
return self._subtype(self._ultimaker, self._base, idx)
class PrinterHead:
def __init__(self, ultimaker, base, idx):
self._ultimaker = ultimaker
self._base = base + '/' + str(idx)
def __eq__(self, other):
return isinstance(other, PrinterHead) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def dict(self): return PrinterHead.transform_raw(self.raw)
@staticmethod
def transform_raw(data):
data['jerk'] = PrinterHeadXYZ.transform_raw(data['jerk'])
data['max_speed'] = PrinterHeadXYZ.transform_raw(data['max_speed'])
data['position'] = PrinterHeadXYZ.transform_raw(data['position'])
data['extruders'] = PrinterHeadExtruders.transform_raw(data['extruders'])
return data
@property
def acceleration(self): return self._ultimaker._get(self._base+'/acceleration')
@acceleration.setter
# doing a put silently fails, default is 3000.0, constrained >= 5.0, gcode M204 S%g
def acceleration(self, value): self._ultimaker._put(self._base+'/acceleration', float(value))
@property
def fan(self): return self._ultimaker._get(self._base+'/fan')
@property
def jerk(self): return PrinterHeadXYZ(self._ultimaker, self._base, 'jerk')
@jerk.setter
# doing a put silently fails, x/y are coupled, default 20.0, constrained >= 0.0, gcode M205 X%g
# jerk z defaults to 0.4, constrained >= 0.0, gcode M205 Z%g
def jerk(self, value): self.jerk.xyz = value
def set_jerk(self, xy, z): return self.jerk._set(xy, xy, z) # pylint: disable=invalid-name
@property
def max_speed(self): return PrinterHeadXYZ(self._ultimaker, self._base, 'max_speed')
@max_speed.setter
# doing a put silently fails, x and y default to 300.0, constrained >= 5.0,
# gcode M203 X%g and M203 Y%g
# max_speed z defaults to 40.0, constrained >= 5.0, gcode M203 Z%g
def max_speed(self, value): self.max_speed.xyz = value
def set_max_speed(self, x, y, z): return self.max_speed._set(x, y, z) # pylint: disable=invalid-name
@property
def position(self): return PrinterHeadPosition(self._ultimaker, self._base)
@position.setter
def position(self, value): self.position.xyz = value
def set_position(self, x, y, z): return self.position._set(x, y, z) # pylint: disable=invalid-name
@property
def extruders(self): return PrinterHeadExtruders(self._ultimaker, self._base)
class PrinterHeads(_PrinterSeq): # pylint: disable=too-many-ancestors
_subtype = PrinterHead
def __init__(self, ultimaker): super().__init__(ultimaker, 'printer/heads')
class PrinterHeadXYZ:
def __init__(self, ultimaker, base, name):
self._ultimaker = ultimaker
self._base = base + '/' + name
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def dict(self): return _extract(self.raw, 'x', 'y', 'z')
@staticmethod
def transform_raw(data): return _extract(data, 'x', 'y', 'z')
def __eq__(self, other):
return isinstance(other, PrinterHeadXYZ) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
# pylint: disable=invalid-name
@property
def x(self): return self.raw['x']
@x.setter
def x(self, value): raw = self.raw; self._set(value, raw['y'], raw['z'])
@property
def y(self): return self.raw['y']
@y.setter
def y(self, value): raw = self.raw; self._set(raw['x'], value, raw['z'])
@property
def z(self): return self.raw['z']
@z.setter
def z(self, value): raw = self.raw; self._set(raw['x'], raw['y'], value)
@property
def xyz(self): raw = self.raw; return (raw['x'], raw['y'], raw['z'])
@xyz.setter
def xyz(self, value):
_ = self._set(**value) if isinstance(value, Mapping) else self._set(*value)
def _set(self, x, y, z):
return self._ultimaker._put(self._base, {'x', float(x), 'y', float(y), 'z', float(z)})
class PrinterHeadPosition(PrinterHeadXYZ):
# Position can have x, y, and z queried independently and has integer values instead of float
def __init__(self, ultimaker, base): super().__init__(ultimaker, base, 'position')
@property
def x(self): return self._ultimaker._get(self._base+'/x')
@x.setter
def x(self, value): self._ultimaker._put(self._base+'/x', int(value))
@property
def y(self): return self._ultimaker._get(self._base+'/y')
@y.setter
def y(self, value): self._ultimaker._put(self._base+'/y', int(value))
@property
def z(self): return self._ultimaker._get(self._base+'/z')
@z.setter
def z(self, value): self._ultimaker._put(self._base+'/z', int(value))
def _set(self, x, y, z): return self._ultimaker._put(self._base,
{'x', int(x), 'y', int(y), 'z', int(z)})
class PrinterHeadExtruder:
def __init__(self, ultimaker, base, idx):
self._ultimaker = ultimaker
self._base = base + '/' + str(idx)
def __eq__(self, other):
return isinstance(other, PrinterHeadExtruder) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def dict(self): return PrinterHeadExtruder.transform_raw(self.raw)
@staticmethod
def transform_raw(data):
data['active_material'] = \
PrinterHeadExtruderActiveMaterial.transform_raw(data['active_material'])
data['feeder'] = PrinterHeadExtruderFeeder.transform_raw(data['feeder'])
data['hotend'] = PrinterHeadExtruderHotend.transform_raw(data['hotend'])
return data
@property
def active_material(self): return PrinterHeadExtruderActiveMaterial(self._ultimaker, self._base)
@property
def feeder(self): return PrinterHeadExtruderFeeder(self._ultimaker, self._base)
@property
def hotend(self): return PrinterHeadExtruderHotend(self._ultimaker, self._base)
class PrinterHeadExtruders(_PrinterSeq): # pylint: disable=too-many-ancestors
_subtype = PrinterHeadExtruder
def __init__(self, ultimaker, base): super().__init__(ultimaker, base + '/extruders')
class PrinterHeadExtruderActiveMaterial:
def __init__(self, ultimaker, base):
self._ultimaker = ultimaker
self._base = base + '/active_material'
def __eq__(self, other):
return isinstance(other, PrinterHeadExtruderActiveMaterial) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def dict(self): return PrinterHeadExtruderActiveMaterial.transform_raw(self.raw)
@staticmethod
def transform_raw(data):
if data['length_remaining'] == -1: data['length_remaining'] = None
data.pop('GUID', None)
return data
@property
def guid(self): return self._ultimaker._get(self._base+'/guid')
@property
def material(self): return self._ultimaker.materials[self.guid]
@property
def length_remaining(self):
value = self._ultimaker._get(self._base+'/length_remaining')
return None if value == -1 else value
class PrinterHeadExtruderFeeder:
def __init__(self, ultimaker, base):
self._ultimaker = ultimaker
self._base = base + '/feeder'
def __eq__(self, other):
return isinstance(other, PrinterHeadExtruderFeeder) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def dict(self): return self.raw
@staticmethod
def transform_raw(data): return data
#@property # this shows up in the model for Feeder but no where else (not even in the source)
#def position(self): return self._ultimaker._get(self._base+'/position')
@property # doing a put silently fails, default is 3000.0, constrained >= 5.0, gcode M204 T%g
def acceleration(self): return self._ultimaker._get(self._base+'/acceleration')
@property # doing a put silently fails, default is 5.0, constrained >= 0, gcode M205 E%g
def jerk(self): return self._ultimaker._get(self._base+'/jerk')
@property # doing a put silently fails, default is 45.0, constrained >= 5.0, gcode M203 E%g
def max_speed(self): return self._ultimaker._get(self._base+'/max_speed')
class PrinterHeadExtruderHotend:
def __init__(self, ultimaker, base):
self._ultimaker = ultimaker
self._base = base + '/hotend'
def __eq__(self, other):
return isinstance(other, PrinterHeadExtruderHotend) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def dict(self): return PrinterHeadExtruderHotend.transform_raw(self.raw)
@staticmethod
def transform_raw(data):
data['offset'] = PrinterHeadExtruderHotendOffset.transform_raw(data['offset'])
data['statistics'] = PrinterHeadExtruderHotendStatistics.transform_raw(data['statistics'])
data['temperature'] = PrinterTemperature.transform_raw(data['temperature'])
return data
@property
def id(self): return self._ultimaker._get(self._base+'/id') # pylint: disable=invalid-name
@property
def serial(self): return self._ultimaker._get(self._base+'/serial')
@property
def offset(self): return PrinterHeadExtruderHotendOffset(self._ultimaker, self._base)
@property
def statistics(self): return PrinterHeadExtruderHotendStatistics(self._ultimaker, self._base)
@property
def temperature(self): return PrinterTemperature(self._ultimaker, self._base)
@temperature.setter
def temperature(self, target):
self._ultimaker._put(self._base+'/temperature/target', float(target))
class PrinterHeadExtruderHotendOffset:
def __init__(self, ultimaker, base):
self._ultimaker = ultimaker
self._base = base + '/offset'
def __eq__(self, other):
return isinstance(other, PrinterHeadExtruderHotendOffset) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def dict(self): return PrinterHeadExtruderHotendOffset.transform_raw(self.raw)
@staticmethod
def transform_raw(data):
data['valid'] = data['state'] == "valid"
del data['state']
return data
@property
def valid(self): return self._ultimaker._get(self._base+'/state') == "valid"
# pylint: disable=invalid-name
@property
def x(self): return self._ultimaker._get(self._base+'/x')
@property
def y(self): return self._ultimaker._get(self._base+'/y')
@property
def z(self): return self._ultimaker._get(self._base+'/z')
class PrinterHeadExtruderHotendStatistics:
def __init__(self, ultimaker, base):
self._ultimaker = ultimaker
self._base = base + '/statistics'
def __eq__(self, other):
return isinstance(other, PrinterHeadExtruderHotendStatistics) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def dict(self): return PrinterHeadExtruderHotendStatistics.transform_raw(self.raw)
@staticmethod
def transform_raw(data):
data['time_spent_hot'] = datetime.timedelta(seconds=data['time_spent_hot'])
return data
@property
def last_material_guid(self): return self._ultimaker._get(self._base+'/last_material_guid')
@property
def last_material(self): return self._ultimaker.materials[self.last_material_guid]
@property
def material_extruded(self): return self._ultimaker._get(self._base+'/material_extruded')
@property
def max_temperature_exposed(self):
return self._ultimaker._get(self._base+'/max_temperature_exposed')
@property
def time_spent_hot(self):
return datetime.timedelta(seconds=self._ultimaker._get(self._base+'/time_spent_hot'))
class PrinterTemperature:
def __init__(self, ultimaker, base):
self._ultimaker = ultimaker
self._base = base + '/temperature'
def __eq__(self, other):
return isinstance(other, PrinterTemperature) and \
self._ultimaker == other._ultimaker and self._base == other._base
def __ne__(self, other): return not self == other
@property
def raw(self): return self._ultimaker._get(self._base)
@property
def dict(self): return self.raw
@staticmethod
def transform_raw(data): return data
@property
def current(self): return self._ultimaker._get(self._base + '/current')
@property
def target(self): return self._ultimaker._get(self._base + '/target')
@target.setter