forked from macdylan/Snapmaker2Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSM2GCodeWriter.py
170 lines (143 loc) · 6.26 KB
/
SM2GCodeWriter.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
import base64
from io import StringIO
from typing import cast
from UM.Mesh.MeshWriter import MeshWriter
from UM.Logger import Logger
from UM.PluginRegistry import PluginRegistry
from cura.Snapshot import Snapshot
from cura.CuraApplication import CuraApplication
from cura.Settings.ExtruderManager import ExtruderManager
from cura.Utils.Threading import call_on_qt_thread
try:
from PyQt6.QtCore import QBuffer
from PyQt6.QtGui import QImage
# QImageFormat = QImage.Format.Format_Indexed8
QBufferOpenMode = QBuffer.OpenModeFlag.ReadWrite
except ImportError:
from PyQt5.QtCore import QBuffer
from PyQt5.QtGui import QImage
# QImageFormat = QImage.Format_Indexed8
QBufferOpenMode = QBuffer.ReadWrite
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
class ModError(Exception):
pass
class SM2GCodeWriter(MeshWriter):
PROCESSED_IDENTITY = ";Processed by Snapmaker2Plugin (https://github.com/macdylan/Snapmaker2Plugin)"
@call_on_qt_thread
def write(self, stream, nodes, mode=MeshWriter.OutputMode.TextMode) -> bool:
if mode != MeshWriter.OutputMode.TextMode:
Logger.log("e", "SM2GCodeWriter does not support non-text mode.")
self.setInformation(catalog.i18nc("@error:not supported", "SM2GCodeWriter does not support non-text mode."))
return False
gcode = StringIO()
writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("GCodeWriter"))
success = writer.write(gcode, None)
if not success:
self.setInformation(writer.getInformation())
return False
gcode.seek(0)
try:
result = self.mod(gcode)
stream.write(result.getvalue())
Logger.log("i", "SM2GCodeWriter done")
return True
except ModError as e:
self.setInformation(str(e))
Logger.log("e", e)
return False
def mod(self, data: StringIO) -> StringIO:
i = 0
for x in data:
if i > 100:
break
if x.find(self.PROCESSED_IDENTITY) != -1:
return data
i += 1
data.seek(0)
gcodes = data.readlines()
p = StringIO()
p.write(self.PROCESSED_IDENTITY + "\n")
p.write(";Header Start\n")
p.write(gcodes[0]) # FLAVOR
p.write(gcodes[1]) # TIME
p.write(gcodes[2]) # Filament used
p.write(gcodes[3]) # Layer height
p.write(";header_type: 3dp\n")
ss = self._createSnapshot()
if ss:
p.write(";thumbnail: data:image/png;base64,")
p.write(self._encodeSnapshot(ss))
p.write("\n")
app = CuraApplication.getInstance()
print_time = int(app.getPrintInformation().currentPrintTime) * 1.07 # Times empirical parameter: 1.07
print_speed = float(self._getValue("speed_infill"))
print_temp = float(self._getValue("material_print_temperature"))
bed_temp = float(self._getValue("material_bed_temperature")) or 0.0
if not print_speed or not print_temp:
raise ModError("Unable to slice with the current settings: speed_infill or material_print_temperature")
p.write(";file_total_lines: %d\n" % len(gcodes))
p.write(";estimated_time(s): %.0f\n" % print_time)
p.write(";nozzle_temperature(°C): %.0f\n" % print_temp)
p.write(";build_plate_temperature(°C): %.0f\n" % bed_temp)
p.write(";work_speed(mm/minute): %.0f\n" % (print_speed * 60.0))
p.write(gcodes[7].replace("MAXX:", "max_x(mm): ")) # max_x
p.write(gcodes[8].replace("MAXY:", "max_y(mm): ")) # max_y
p.write(gcodes[9].replace("MAXZ:", "max_z(mm): ")) # max_z
p.write(gcodes[4].replace("MINX:", "min_x(mm): ")) # min_x
p.write(gcodes[5].replace("MINY:", "min_y(mm): ")) # min_y
p.write(gcodes[6].replace("MINZ:", "min_z(mm): ")) # min_z
p.write(";Header End\n")
p.write("".join(gcodes[10:]))
return p
def _createSnapshot(self) -> QImage:
Logger.log("d", "Creating thumbnail image...")
try:
return Snapshot.snapshot(width=150, height=150) # .convertToFormat(QImageFormat)
except Exception:
Logger.logException("w", "Failed to create snapshot image")
return None
def _encodeSnapshot(self, snapshot: QImage) -> str:
Logger.log("d", "Encoding thumbnail image...")
try:
thumbnail_buffer = QBuffer()
thumbnail_buffer.open(QBufferOpenMode)
thumbnail_image = snapshot
thumbnail_image.save(thumbnail_buffer, "PNG")
base64_bytes = base64.b64encode(thumbnail_buffer.data())
base64_message = base64_bytes.decode('ascii')
thumbnail_buffer.close()
return base64_message
except Exception:
Logger.logException("w", "Failed to encode snapshot image")
def _getValue(self, key) -> str:
# app = CuraApplication.getInstance()
stack = ExtruderManager.getInstance().getActiveExtruderStack()
# stack2 = app.getGlobalContainerStack()
# stack3 = app.getMachineManager()
# stack = None
# if stack1.hasProperty(key, "value"):
# stack = stack1
# elif stack2.hasProperty(key, "value"):
# stack = stack2
# elif stack3.hasProperty(key, "value"):
# stack = stack3
if not stack:
return ""
GetType = stack.getProperty(key, "type")
GetVal = stack.getProperty(key, "value")
if str(GetType) == "float":
GelValStr = "{:.4f}".format(GetVal).rstrip("0").rstrip(".")
else:
# enum = Option list
if str(GetType) == "enum":
# definition_option = key + " option " + str(GetVal)
get_option = str(GetVal)
GetOption = stack.getProperty(key, "options")
GetOptionDetail = GetOption[get_option]
# GelValStr=i18n_catalog.i18nc(definition_option, GetOptionDetail)
GelValStr = GetOptionDetail
# Logger.log("d", "GetType_doTree = %s ; %s ; %s ; %s",definition_option, GelValStr, GetOption, GetOptionDetail)
else:
GelValStr = str(GetVal)
return GelValStr