forked from OctoPrint/OctoPrint
/
profile.py
409 lines (348 loc) · 11.5 KB
/
profile.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
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
import copy
import re
import logging
from octoprint.settings import settings
from octoprint.util import dict_merge, dict_clean, dict_contains_keys
class SaveError(Exception):
pass
class CouldNotOverwriteError(SaveError):
pass
class InvalidProfileError(Exception):
pass
class BedTypes(object):
RECTANGULAR = "rectangular"
CIRCULAR = "circular"
@classmethod
def values(cls):
return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")]
class PrinterProfileManager(object):
"""
Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove,
load and save printer profiles.
A printer profile is a ``dict`` of the following structure:
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Type
- Description
* - ``id``
- ``string``
- Internal id of the printer profile
* - ``name``
- ``string``
- Human readable name of the printer profile
* - ``model``
- ``string``
- Printer model
* - ``color``
- ``string``
- Color to associate with the printer profile
* - ``volume``
- ``dict``
- Information about the print volume
* - ``volume.width``
- ``float``
- Width of the print volume (X axis)
* - ``volume.depth``
- ``float``
- Depth of the print volume (Y axis)
* - ``volume.height``
- ``float``
- Height of the print volume (Z axis)
* - ``volume.formFactor``
- ``string``
- Form factor of the print bed, either ``rectangular`` or ``circular``
* - ``centeredOrigin``
- ``bool``
- Whether the printer's origin is in the center of the bed, otherwise
- the origin is assumed to be the lower left and all valid coordinates
- positive.
* - ``heatedBed``
- ``bool``
- Whether the printer has a heated bed (``True``) or not (``False``)
* - ``extruder``
- ``dict``
- Information about the printer's extruders
* - ``extruder.count``
- ``int``
- How many extruders the printer has (default 1)
* - ``extruder.offsets``
- ``list`` of ``tuple``s
- Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0)
* - ``extruder.nozzleDiameter``
- ``float``
- Diameter of the printer nozzle
* - ``axes``
- ``dict``
- Information about the printer axes
* - ``axes.x``
- ``dict``
- Information about the printer's X axis
* - ``axes.x.speed``
- ``float``
- Speed of the X axis in mm/s
* - ``axes.x.inverted``
- ``bool``
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
* - ``axes.y``
- ``dict``
- Information about the printer's Y axis
* - ``axes.y.speed``
- ``float``
- Speed of the Y axis in mm/s
* - ``axes.y.inverted``
- ``bool``
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
* - ``axes.z``
- ``dict``
- Information about the printer's Z axis
* - ``axes.z.speed``
- ``float``
- Speed of the Z axis in mm/s
* - ``axes.z.inverted``
- ``bool``
- Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True)
* - ``axes.e``
- ``dict``
- Information about the printer's E axis
* - ``axes.e.speed``
- ``float``
- Speed of the E axis in mm/s
* - ``axes.e.inverted``
- ``bool``
- Whether a positive value change extrudes (False, default) or retracts (True) filament
"""
default = dict(
id = "_default",
name = "Default",
model = "Generic RepRap Printer",
color = "default",
volume=dict(
width = 200,
depth = 200,
height = 200,
formFactor = BedTypes.RECTANGULAR,
),
heatedBed = False,
centeredOrigin = False,
extruder=dict(
count = 1,
offsets = [
(0, 0)
],
nozzleDiameter = 0.4
),
axes=dict(
x = dict(speed=6000, inverted=False),
y = dict(speed=6000, inverted=False),
z = dict(speed=200, inverted=False),
e = dict(speed=300, inverted=False)
)
)
def __init__(self):
self._current = None
self._folder = settings().getBaseFolder("printerProfiles")
self._logger = logging.getLogger(__name__)
def select(self, identifier):
if identifier is None or not self.exists(identifier):
self._current = self.get_default()
return False
else:
self._current = self.get(identifier)
return True
def deselect(self):
self._current = None
def get_all(self):
return self._load_all()
def get(self, identifier):
try:
if identifier == "_default":
return self._load_default()
elif self.exists(identifier):
return self._load_from_path(self._get_profile_path(identifier))
else:
return None
except InvalidProfileError:
return None
def remove(self, identifier):
if identifier == "_default":
return False
return self._remove_from_path(self._get_profile_path(identifier))
def save(self, profile, allow_overwrite=False, make_default=False):
if "id" in profile:
identifier = profile["id"]
elif "name" in profile:
identifier = profile["name"]
else:
raise InvalidProfileError("profile must contain either id or name")
identifier = self._sanitize(identifier)
profile["id"] = identifier
profile = dict_clean(profile, self.__class__.default)
if identifier == "_default":
default_profile = dict_merge(self._load_default(), profile)
if not self._ensure_valid_profile(default_profile):
raise InvalidProfileError()
settings().set(["printerProfiles", "defaultProfile"], default_profile, defaults=dict(printerProfiles=dict(defaultProfile=self.__class__.default)))
settings().save()
else:
self._save_to_path(self._get_profile_path(identifier), profile, allow_overwrite=allow_overwrite)
if make_default:
settings().set(["printerProfiles", "default"], identifier)
return self.get(identifier)
def get_default(self):
default = settings().get(["printerProfiles", "default"])
if default is not None and self.exists(default):
profile = self.get(default)
if profile is not None:
return profile
return self._load_default()
def set_default(self, identifier):
all_identifiers = self._load_all_identifiers().keys()
if identifier is not None and not identifier in all_identifiers:
return
settings().set(["printerProfile", "default"], identifier)
settings().save()
def get_current_or_default(self):
if self._current is not None:
return self._current
else:
return self.get_default()
def get_current(self):
return self._current
def exists(self, identifier):
if identifier is None:
return False
elif identifier == "_default":
return True
else:
path = self._get_profile_path(identifier)
return os.path.exists(path) and os.path.isfile(path)
def _load_all(self):
all_identifiers = self._load_all_identifiers()
results = dict()
for identifier, path in all_identifiers.items():
try:
if identifier == "_default":
profile = self._load_default()
else:
profile = self._load_from_path(path)
except InvalidProfileError:
continue
if profile is None:
continue
results[identifier] = dict_merge(self._load_default(), profile)
return results
def _load_all_identifiers(self):
results = dict(_default=None)
for entry in os.listdir(self._folder):
if entry.startswith(".") or not entry.endswith(".profile") or entry == "_default.profile":
continue
path = os.path.join(self._folder, entry)
if not os.path.isfile(path):
continue
identifier = entry[:-len(".profile")]
results[identifier] = path
return results
def _load_from_path(self, path):
if not os.path.exists(path) or not os.path.isfile(path):
return None
import yaml
with open(path) as f:
profile = yaml.safe_load(f)
profile = dict_merge(self._load_default(), profile)
profile = self._ensure_valid_profile(profile)
if not profile:
self._logger.warn("Invalid profile: %s" % path)
raise InvalidProfileError()
return profile
def _save_to_path(self, path, profile, allow_overwrite=False):
validated_profile = self._ensure_valid_profile(profile)
if not validated_profile:
raise InvalidProfileError()
if os.path.exists(path) and not allow_overwrite:
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
import yaml
with open(path, "wb") as f:
try:
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
except Exception as e:
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
def _remove_from_path(self, path):
try:
os.remove(path)
return True
except:
return False
def _load_default(self):
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
profile = self._ensure_valid_profile(dict_merge(copy.deepcopy(self.__class__.default), default_overrides))
if not profile:
self._logger.warn("Invalid default profile after applying overrides")
return copy.deepcopy(self.__class__.default)
return profile
def _get_profile_path(self, identifier):
return os.path.join(self._folder, "%s.profile" % identifier)
def _sanitize(self, name):
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name
def _ensure_valid_profile(self, profile):
# ensure all keys are present
if not dict_contains_keys(self.default, profile):
return False
# conversion helper
def convert_value(profile, path, converter):
value = profile
for part in path[:-1]:
if not isinstance(value, dict) or not part in value:
raise RuntimeError("%s is not contained in profile" % ".".join(path))
value = value[part]
if not isinstance(value, dict) or not path[-1] in value:
raise RuntimeError("%s is not contained in profile" % ".".join(path))
value[path[-1]] = converter(value[path[-1]])
# convert ints
for path in (("extruder", "count"), ("axes", "x", "speed"), ("axes", "y", "speed"), ("axes", "z", "speed")):
try:
convert_value(profile, path, int)
except:
return False
# convert floats
for path in (("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter")):
try:
convert_value(profile, path, float)
except:
return False
# convert booleans
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")):
try:
convert_value(profile, path, bool)
except:
return False
# validate form factor
if not profile["volume"]["formFactor"] in BedTypes.values():
return False
# validate offsets
offsets = []
for offset in profile["extruder"]["offsets"]:
if not len(offset) == 2:
return False
x_offset, y_offset = offset
try:
offsets.append((float(x_offset), float(y_offset)))
except:
return False
profile["extruder"]["offsets"] = offsets
return profile