FlatCAMCNCJob.py 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from copy import deepcopy
  12. from io import StringIO
  13. from datetime import datetime
  14. from appEditors.AppTextEditor import AppTextEditor
  15. from appObjects.FlatCAMObj import *
  16. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  17. from camlib import CNCjob
  18. from shapely.ops import unary_union
  19. from shapely.geometry import Point, MultiPoint
  20. try:
  21. from shapely.ops import voronoi_diagram
  22. except Exception:
  23. pass
  24. import os
  25. import sys
  26. import time
  27. import serial
  28. import glob
  29. import math
  30. import gettext
  31. import appTranslation as fcTranslate
  32. import builtins
  33. fcTranslate.apply_language('strings')
  34. if '_' not in builtins.__dict__:
  35. _ = gettext.gettext
  36. class CNCJobObject(FlatCAMObj, CNCjob):
  37. """
  38. Represents G-Code.
  39. """
  40. optionChanged = QtCore.pyqtSignal(str)
  41. build_al_table_sig = QtCore.pyqtSignal()
  42. ui_type = CNCObjectUI
  43. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  44. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  45. spindlespeed=None):
  46. log.debug("Creating CNCJob object...")
  47. self.decimals = self.app.decimals
  48. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  49. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  50. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  51. FlatCAMObj.__init__(self, name)
  52. self.kind = "cncjob"
  53. self.options.update({
  54. "plot": True,
  55. "tooldia": 0.03937, # 0.4mm in inches
  56. "append": "",
  57. "prepend": "",
  58. "dwell": False,
  59. "dwelltime": 1,
  60. "type": 'Geometry',
  61. # "toolchange_macro": '',
  62. # "toolchange_macro_enable": False
  63. })
  64. '''
  65. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  66. diameter of the tools and the value is another dict that will hold the data under the following form:
  67. {tooldia: {
  68. 'tooluid': 1,
  69. 'offset': 'Path',
  70. 'type_item': 'Rough',
  71. 'tool_type': 'C1',
  72. 'data': {} # a dict to hold the parameters
  73. 'gcode': "" # a string with the actual GCODE
  74. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry
  75. (cut or move)
  76. 'solid_geometry': []
  77. },
  78. ...
  79. }
  80. It is populated in the GeometryObject.mtool_gen_cncjob()
  81. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  82. '''
  83. self.cnc_tools = {}
  84. '''
  85. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  86. diameter of the tools and the value is another dict that will hold the data under the following form:
  87. {tooldia: {
  88. 'tool': int,
  89. 'nr_drills': int,
  90. 'nr_slots': int,
  91. 'offset': float,
  92. 'data': {}, a dict to hold the parameters
  93. 'gcode': "", a string with the actual GCODE
  94. 'gcode_parsed': [], list of dicts holding the CNCJob geometry and
  95. type of geometry (cut or move)
  96. 'solid_geometry': [],
  97. },
  98. ...
  99. }
  100. It is populated in the ExcellonObject.on_create_cncjob_click() but actually
  101. it's done in camlib.CNCJob.generate_from_excellon_by_tool()
  102. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  103. '''
  104. self.exc_cnc_tools = {}
  105. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  106. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  107. self.special_group = None
  108. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  109. # (like the one in the TCL Command), False
  110. self.multitool = False
  111. # determine if the GCode was generated out of a Excellon object or a Geometry object
  112. self.origin_kind = None
  113. self.coords_decimals = 4
  114. self.fr_decimals = 2
  115. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  116. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  117. self.g_x_re = re.compile(gcodex_re_string)
  118. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  119. self.g_y_re = re.compile(gcodey_re_string)
  120. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  121. self.g_z_re = re.compile(gcodez_re_string)
  122. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  123. self.g_f_re = re.compile(gcodef_re_string)
  124. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  125. self.g_t_re = re.compile(gcodet_re_string)
  126. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  127. self.g_nr_re = re.compile(gcodenr_re_string)
  128. if self.app.is_legacy is False:
  129. self.text_col = self.app.plotcanvas.new_text_collection()
  130. self.text_col.enabled = True
  131. self.annotation = self.app.plotcanvas.new_text_group(collection=self.text_col)
  132. self.gcode_editor_tab = None
  133. self.gcode_viewer_tab = None
  134. self.source_file = ''
  135. self.units_found = self.app.defaults['units']
  136. self.probing_gcode_text = ''
  137. # store the current selection shape status to be restored after manual adding test points
  138. self.old_selection_state = self.app.defaults['global_selection_shape']
  139. # if mouse is dragging set the object True
  140. self.mouse_is_dragging = False
  141. # if mouse events are bound to local methods
  142. self.mouse_events_connected = False
  143. # event handlers references
  144. self.kp = None
  145. self.mm = None
  146. self.mr = None
  147. self.append_snippet = ''
  148. self.prepend_snippet = ''
  149. self.gc_header = self.gcode_header()
  150. self.gc_start = ''
  151. self.gc_end = ''
  152. '''
  153. dictionary of dictionaries to store the informations for the autolevelling
  154. format:
  155. {
  156. id: {
  157. 'point': Shapely Point
  158. 'geo': Shapely Polygon from Voronoi diagram,
  159. 'height': float
  160. }
  161. }
  162. '''
  163. self.al_geometry_dict = {}
  164. self.solid_geo = None
  165. self.grbl_ser_port = None
  166. # Attributes to be included in serialization
  167. # Always append to it because it carries contents
  168. # from predecessors.
  169. self.ser_attrs += [
  170. 'options', 'kind', 'origin_kind', 'cnc_tools', 'exc_cnc_tools', 'multitool', 'append_snippet',
  171. 'prepend_snippet', 'gc_header'
  172. ]
  173. def build_ui(self):
  174. self.ui_disconnect()
  175. FlatCAMObj.build_ui(self)
  176. self.units = self.app.defaults['units'].upper()
  177. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  178. self.ui.cnc_tools_table.hide()
  179. if self.cnc_tools:
  180. self.ui.cnc_tools_table.show()
  181. self.build_cnc_tools_table()
  182. self.ui.exc_cnc_tools_table.hide()
  183. if self.exc_cnc_tools:
  184. self.ui.exc_cnc_tools_table.show()
  185. self.build_excellon_cnc_tools()
  186. if self.ui.sal_cb.get_value():
  187. self.build_al_table()
  188. self.ui_connect()
  189. def build_cnc_tools_table(self):
  190. tool_idx = 0
  191. n = len(self.cnc_tools)
  192. self.ui.cnc_tools_table.setRowCount(n)
  193. for dia_key, dia_value in self.cnc_tools.items():
  194. tool_idx += 1
  195. row_no = tool_idx - 1
  196. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  197. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  198. self.ui.cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  199. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  200. # There are no tool bits in MM with more than 2 decimals diameter.
  201. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  202. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['tooldia'])))
  203. offset_txt = list(str(dia_value['offset']))
  204. offset_txt[0] = offset_txt[0].upper()
  205. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  206. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  207. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  208. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  209. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  210. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  211. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  212. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  213. # hack so the checkbox stay centered in the table cell
  214. # used this:
  215. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  216. # plot_item = QtWidgets.QWidget()
  217. # checkbox = FCCheckBox()
  218. # checkbox.setCheckState(QtCore.Qt.Checked)
  219. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  220. # qhboxlayout.addWidget(checkbox)
  221. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  222. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  223. plot_item = FCCheckBox()
  224. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  225. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  226. if self.ui.plot_cb.isChecked():
  227. plot_item.setChecked(True)
  228. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  229. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  230. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  231. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  232. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  233. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  234. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  235. # make the diameter column editable
  236. # for row in range(tool_idx):
  237. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  238. # QtCore.Qt.ItemIsEnabled)
  239. for row in range(tool_idx):
  240. self.ui.cnc_tools_table.item(row, 0).setFlags(
  241. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  242. self.ui.cnc_tools_table.resizeColumnsToContents()
  243. self.ui.cnc_tools_table.resizeRowsToContents()
  244. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  245. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  246. vertical_header.hide()
  247. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  248. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  249. horizontal_header.setMinimumSectionSize(10)
  250. horizontal_header.setDefaultSectionSize(70)
  251. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  252. horizontal_header.resizeSection(0, 20)
  253. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  254. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  255. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  256. horizontal_header.resizeSection(4, 40)
  257. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  258. horizontal_header.resizeSection(4, 17)
  259. # horizontal_header.setStretchLastSection(True)
  260. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  261. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  262. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  263. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  264. # self.ui.geo_tools_table.setSortingEnabled(True)
  265. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  266. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  267. def build_excellon_cnc_tools(self):
  268. tool_idx = 0
  269. n = len(self.exc_cnc_tools)
  270. self.ui.exc_cnc_tools_table.setRowCount(n)
  271. for tooldia_key, dia_value in self.exc_cnc_tools.items():
  272. tool_idx += 1
  273. row_no = tool_idx - 1
  274. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  275. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooldia_key)))
  276. nr_drills_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_drills']))
  277. nr_slots_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_slots']))
  278. cutz_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['offset']) + self.z_cut))
  279. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  280. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  281. nr_drills_item.setFlags(QtCore.Qt.ItemIsEnabled)
  282. nr_slots_item.setFlags(QtCore.Qt.ItemIsEnabled)
  283. cutz_item.setFlags(QtCore.Qt.ItemIsEnabled)
  284. # hack so the checkbox stay centered in the table cell
  285. # used this:
  286. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  287. # plot_item = QtWidgets.QWidget()
  288. # checkbox = FCCheckBox()
  289. # checkbox.setCheckState(QtCore.Qt.Checked)
  290. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  291. # qhboxlayout.addWidget(checkbox)
  292. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  293. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  294. plot_item = FCCheckBox()
  295. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  296. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_value['tool']))
  297. if self.ui.plot_cb.isChecked():
  298. plot_item.setChecked(True)
  299. self.ui.exc_cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  300. self.ui.exc_cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  301. self.ui.exc_cnc_tools_table.setItem(row_no, 2, nr_drills_item) # Nr of drills
  302. self.ui.exc_cnc_tools_table.setItem(row_no, 3, nr_slots_item) # Nr of slots
  303. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  304. self.ui.exc_cnc_tools_table.setItem(row_no, 4, tool_uid_item) # Tool unique ID)
  305. self.ui.exc_cnc_tools_table.setItem(row_no, 5, cutz_item)
  306. self.ui.exc_cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  307. for row in range(tool_idx):
  308. self.ui.exc_cnc_tools_table.item(row, 0).setFlags(
  309. self.ui.exc_cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  310. self.ui.exc_cnc_tools_table.resizeColumnsToContents()
  311. self.ui.exc_cnc_tools_table.resizeRowsToContents()
  312. vertical_header = self.ui.exc_cnc_tools_table.verticalHeader()
  313. vertical_header.hide()
  314. self.ui.exc_cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  315. horizontal_header = self.ui.exc_cnc_tools_table.horizontalHeader()
  316. horizontal_header.setMinimumSectionSize(10)
  317. horizontal_header.setDefaultSectionSize(70)
  318. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  319. horizontal_header.resizeSection(0, 20)
  320. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  321. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  322. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  323. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
  324. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  325. # horizontal_header.setStretchLastSection(True)
  326. self.ui.exc_cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  327. self.ui.exc_cnc_tools_table.setColumnWidth(0, 20)
  328. self.ui.exc_cnc_tools_table.setColumnWidth(6, 17)
  329. self.ui.exc_cnc_tools_table.setMinimumHeight(self.ui.exc_cnc_tools_table.getHeight())
  330. self.ui.exc_cnc_tools_table.setMaximumHeight(self.ui.exc_cnc_tools_table.getHeight())
  331. def build_al_table(self):
  332. tool_idx = 0
  333. n = len(self.al_geometry_dict)
  334. self.ui.al_probe_points_table.setRowCount(n)
  335. for id_key, value in self.al_geometry_dict.items():
  336. tool_idx += 1
  337. row_no = tool_idx - 1
  338. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  339. x = value['point'].x
  340. y = value['point'].y
  341. xy_coords = self.app.dec_format(x, dec=self.app.decimals), self.app.dec_format(y, dec=self.app.decimals)
  342. coords_item = QtWidgets.QTableWidgetItem(str(xy_coords))
  343. height = self.app.dec_format(value['height'], dec=self.app.decimals)
  344. height_item = QtWidgets.QTableWidgetItem(str(height))
  345. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  346. coords_item.setFlags(QtCore.Qt.ItemIsEnabled)
  347. height_item.setFlags(QtCore.Qt.ItemIsEnabled)
  348. self.ui.al_probe_points_table.setItem(row_no, 0, t_id) # Tool name/id
  349. self.ui.al_probe_points_table.setItem(row_no, 1, coords_item) # X-Y coords
  350. self.ui.al_probe_points_table.setItem(row_no, 2, height_item) # Determined Height
  351. self.ui.al_probe_points_table.resizeColumnsToContents()
  352. self.ui.al_probe_points_table.resizeRowsToContents()
  353. h_header = self.ui.al_probe_points_table.horizontalHeader()
  354. h_header.setMinimumSectionSize(10)
  355. h_header.setDefaultSectionSize(70)
  356. h_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  357. h_header.resizeSection(0, 20)
  358. h_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  359. h_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  360. self.ui.al_probe_points_table.setMinimumHeight(self.ui.al_probe_points_table.getHeight())
  361. self.ui.al_probe_points_table.setMaximumHeight(self.ui.al_probe_points_table.getHeight())
  362. if self.ui.al_probe_points_table.model().rowCount():
  363. self.ui.voronoi_cb.setDisabled(False)
  364. self.ui.grbl_get_heightmap_button.setDisabled(False)
  365. self.ui.h_gcode_button.setDisabled(False)
  366. self.ui.view_h_gcode_button.setDisabled(False)
  367. else:
  368. self.ui.voronoi_cb.setDisabled(True)
  369. self.ui.grbl_get_heightmap_button.setDisabled(True)
  370. self.ui.h_gcode_button.setDisabled(True)
  371. self.ui.view_h_gcode_button.setDisabled(True)
  372. def set_ui(self, ui):
  373. FlatCAMObj.set_ui(self, ui)
  374. log.debug("FlatCAMCNCJob.set_ui()")
  375. assert isinstance(self.ui, CNCObjectUI), \
  376. "Expected a CNCObjectUI, got %s" % type(self.ui)
  377. self.units = self.app.defaults['units'].upper()
  378. self.units_found = self.app.defaults['units']
  379. # this signal has to be connected to it's slot before the defaults are populated
  380. # the decision done in the slot has to override the default value set below
  381. # self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  382. self.form_fields.update({
  383. "plot": self.ui.plot_cb,
  384. "tooldia": self.ui.tooldia_entry,
  385. # "append": self.ui.append_text,
  386. # "prepend": self.ui.prepend_text,
  387. # "toolchange_macro": self.ui.toolchange_text,
  388. # "toolchange_macro_enable": self.ui.toolchange_cb,
  389. "al_travelz": self.ui.ptravelz_entry,
  390. "al_probe_depth": self.ui.pdepth_entry,
  391. "al_probe_fr": self.ui.feedrate_probe_entry,
  392. "al_controller": self.ui.al_controller_combo,
  393. "al_mode": self.ui.al_mode_radio,
  394. "al_rows": self.ui.al_rows_entry,
  395. "al_columns": self.ui.al_columns_entry,
  396. })
  397. self.append_snippet = self.app.defaults['cncjob_append']
  398. self.prepend_snippet = self.app.defaults['cncjob_prepend']
  399. if self.append_snippet != '' or self.prepend_snippet:
  400. self.ui.snippets_cb.set_value(True)
  401. # Fill form fields only on object create
  402. self.to_form()
  403. # this means that the object that created this CNCJob was an Excellon or Geometry
  404. try:
  405. if self.travel_distance:
  406. self.ui.t_distance_label.show()
  407. self.ui.t_distance_entry.setVisible(True)
  408. self.ui.t_distance_entry.setDisabled(True)
  409. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  410. self.ui.units_label.setText(str(self.units).lower())
  411. self.ui.units_label.setDisabled(True)
  412. self.ui.t_time_label.show()
  413. self.ui.t_time_entry.setVisible(True)
  414. self.ui.t_time_entry.setDisabled(True)
  415. # if time is more than 1 then we have minutes, else we have seconds
  416. if self.routing_time > 1:
  417. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  418. self.ui.units_time_label.setText('min')
  419. else:
  420. time_r = self.routing_time * 60
  421. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  422. self.ui.units_time_label.setText('sec')
  423. self.ui.units_time_label.setDisabled(True)
  424. except AttributeError:
  425. pass
  426. if self.multitool is False:
  427. self.ui.tooldia_entry.show()
  428. self.ui.updateplot_button.show()
  429. else:
  430. self.ui.tooldia_entry.hide()
  431. self.ui.updateplot_button.hide()
  432. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  433. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  434. try:
  435. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  436. except (TypeError, AttributeError):
  437. pass
  438. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  439. # set if to display text annotations
  440. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  441. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  442. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  443. self.ui.review_gcode_button.clicked.connect(self.on_edit_code_click)
  444. self.ui.editor_button.clicked.connect(lambda: self.app.object2editor())
  445. # autolevelling signals
  446. self.ui.sal_cb.stateChanged.connect(self.on_autolevelling)
  447. self.ui.al_mode_radio.activated_custom.connect(self.on_mode_radio)
  448. self.ui.al_controller_combo.currentIndexChanged.connect(self.on_controller_change)
  449. self.ui.voronoi_cb.stateChanged.connect(self.show_voronoi_diagram)
  450. # GRBL
  451. self.ui.com_search_button.clicked.connect(self.on_search_ports)
  452. self.ui.add_bd_button.clicked.connect(self.on_add_baudrate_grbl)
  453. self.ui.del_bd_button.clicked.connect(self.on_delete_baudrate_grbl)
  454. self.ui.controller_reset_button.clicked.connect(self.on_grbl_reset)
  455. self.ui.com_connect_button.clicked.connect(self.on_connect_grbl)
  456. self.ui.grbl_send_button.clicked.connect(self.on_send_grbl_command)
  457. self.ui.grbl_command_entry.returnPressed.connect(self.on_send_grbl_command)
  458. #Jog
  459. self.ui.jog_up_button.clicked.connect(lambda: self.on_jog(direction='yplus', step=5.0))
  460. self.ui.jog_down_button.clicked.connect(lambda: self.on_jog(direction='yminus', step=5.0))
  461. self.ui.jog_right_button.clicked.connect(lambda: self.on_jog(direction='xplus', step=5.0))
  462. self.ui.jog_left_button.clicked.connect(lambda: self.on_jog(direction='xminus', step=5.0))
  463. self.ui.jog_z_up_button.clicked.connect(lambda: self.on_jog(direction='zplus', step=5.0))
  464. self.ui.jog_z_down_button.clicked.connect(lambda: self.on_jog(direction='zminus', step=5.0))
  465. # Sender
  466. self.ui.grbl_report_button.clicked.connect(lambda: self.send_grbl_command(command='?'))
  467. self.ui.grbl_get_param_button.clicked.connect(
  468. lambda: self.get_grbl_parameter(param=self.ui.grbl_parameter_entry.get_value()))
  469. self.ui.view_h_gcode_button.clicked.connect(self.on_view_probing_gcode)
  470. self.ui.h_gcode_button.clicked.connect(self.on_generate_probing_gcode)
  471. self.ui.import_heights_button.clicked.connect(self.on_import_height_map)
  472. self.build_al_table_sig.connect(self.build_al_table)
  473. # self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  474. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  475. # Show/Hide Advanced Options
  476. if self.app.defaults["global_app_level"] == 'b':
  477. self.ui.level.setText(_(
  478. '<span style="color:green;"><b>Basic</b></span>'
  479. ))
  480. self.ui.sal_cb.hide()
  481. self.ui.sal_cb.set_value(False)
  482. else:
  483. self.ui.level.setText(_(
  484. '<span style="color:red;"><b>Advanced</b></span>'
  485. ))
  486. self.ui.sal_cb.show()
  487. self.ui.sal_cb.set_value(self.app.defaults["cncjob_al_status"])
  488. preamble = self.append_snippet
  489. postamble = self.prepend_snippet
  490. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  491. self.source_file = gc.getvalue()
  492. self.ui.al_mode_radio.set_value(self.options['al_mode'])
  493. self.on_controller_change()
  494. # def on_cnc_custom_parameters(self, signal_text):
  495. # if signal_text == 'Parameters':
  496. # return
  497. # else:
  498. # self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  499. def ui_connect(self):
  500. for row in range(self.ui.cnc_tools_table.rowCount()):
  501. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  502. for row in range(self.ui.exc_cnc_tools_table.rowCount()):
  503. self.ui.exc_cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  504. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  505. self.ui.al_add_button.clicked.connect(self.on_add_al_probepoints)
  506. self.ui.show_al_table.stateChanged.connect(self.on_show_al_table)
  507. def ui_disconnect(self):
  508. for row in range(self.ui.cnc_tools_table.rowCount()):
  509. try:
  510. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  511. except (TypeError, AttributeError):
  512. pass
  513. for row in range(self.ui.exc_cnc_tools_table.rowCount()):
  514. try:
  515. self.ui.exc_cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  516. except (TypeError, AttributeError):
  517. pass
  518. try:
  519. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  520. except (TypeError, AttributeError):
  521. pass
  522. try:
  523. self.ui.al_add_button.clicked.disconnect()
  524. except (TypeError, AttributeError):
  525. pass
  526. try:
  527. self.ui.show_al_table.stateChanged.disconnect()
  528. except (TypeError, AttributeError):
  529. pass
  530. def on_add_al_probepoints(self):
  531. # create the solid_geo
  532. self.solid_geo = unary_union([geo['geom'] for geo in self.gcode_parsed if geo['kind'][0] == 'C'])
  533. # reset al table
  534. self.ui.al_probe_points_table.setRowCount(0)
  535. # reset the al dict
  536. self.al_geometry_dict.clear()
  537. xmin, ymin, xmax, ymax = self.solid_geo.bounds
  538. if self.ui.al_mode_radio.get_value() == 'grid':
  539. width = abs(xmax - xmin)
  540. height = abs(ymax - ymin)
  541. cols = self.ui.al_columns_entry.get_value()
  542. rows = self.ui.al_rows_entry.get_value()
  543. dx = width / (cols + 1)
  544. dy = height / (rows + 1)
  545. points = []
  546. new_y = ymin
  547. for x in range(rows):
  548. new_y += dy
  549. new_x = xmin
  550. for x in range(cols):
  551. new_x += dx
  552. formatted_point = (
  553. self.app.dec_format(new_x, self.app.decimals),
  554. self.app.dec_format(new_y, self.app.decimals)
  555. )
  556. points.append(formatted_point)
  557. pt_id = 0
  558. pts_list = []
  559. for point in points:
  560. pt_id += 1
  561. pt = Point(point)
  562. pts_list.append(pt)
  563. new_dict = {
  564. 'point': pt,
  565. 'geo': None,
  566. 'height': 0.0
  567. }
  568. self.al_geometry_dict[pt_id] = deepcopy(new_dict)
  569. self.calculate_voronoi_diagram(pts=pts_list)
  570. else:
  571. self.app.inform.emit(_("Click on canvas to add a Test Point..."))
  572. if self.app.is_legacy is False:
  573. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  574. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  575. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  576. else:
  577. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  578. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  579. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  580. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  581. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  582. self.mouse_events_connected = True
  583. self.build_al_table_sig.emit()
  584. def show_voronoi_diagram(self, state):
  585. if state:
  586. pass
  587. else:
  588. pass
  589. def calculate_voronoi_diagram(self, pts):
  590. pts_union = MultiPoint(pts)
  591. env = self.solid_geo.envelope
  592. print(pts_union.wkt)
  593. try:
  594. voronoi_union = voronoi_diagram(geom=pts_union, envelope=env)
  595. print(voronoi_union)
  596. except Exception as e:
  597. log.debug("CNCJobObject.calculate_voronoi_diagram() --> %s" % str(e))
  598. return
  599. for pt_key in list(self.al_geometry_dict.keys()):
  600. for poly in voronoi_union:
  601. if self.al_geometry_dict[pt_key]['point'].within(poly):
  602. self.al_geometry_dict[pt_key]['geo'] = poly
  603. # To be called after clicking on the plot.
  604. def on_mouse_click_release(self, event):
  605. if self.app.is_legacy is False:
  606. event_pos = event.pos
  607. # event_is_dragging = event.is_dragging
  608. right_button = 2
  609. else:
  610. event_pos = (event.xdata, event.ydata)
  611. # event_is_dragging = self.app.plotcanvas.is_dragging
  612. right_button = 3
  613. try:
  614. x = float(event_pos[0])
  615. y = float(event_pos[1])
  616. except TypeError:
  617. return
  618. event_pos = (x, y)
  619. # do paint single only for left mouse clicks
  620. if event.button == 1:
  621. pos = self.app.plotcanvas.translate_coords(event_pos)
  622. # use the snapped position as reference
  623. snapped_pos = self.app.geo_editor.snap(pos[0], pos[1])
  624. if not self.al_geometry_dict:
  625. new_dict = {
  626. 'point': Point(snapped_pos),
  627. 'geo': None,
  628. 'height': 0.0
  629. }
  630. self.al_geometry_dict[1] = deepcopy(new_dict)
  631. else:
  632. int_keys = [int(k) for k in self.al_geometry_dict.keys()]
  633. new_id = max(int_keys) + 1
  634. new_dict = {
  635. 'point': Point(snapped_pos),
  636. 'geo': None,
  637. 'height': 0.0
  638. }
  639. self.al_geometry_dict[new_id] = deepcopy(new_dict)
  640. # rebuild the al table
  641. self.build_al_table_sig.emit()
  642. self.app.inform.emit(_("Added Test Point... Click again to add another or right click to finish ..."))
  643. # if RMB then we exit
  644. elif event.button == right_button and self.mouse_is_dragging is False:
  645. if self.app.is_legacy is False:
  646. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  647. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  648. else:
  649. self.app.plotcanvas.graph_event_disconnect(self.kp)
  650. self.app.plotcanvas.graph_event_disconnect(self.mr)
  651. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  652. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  653. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  654. self.app.on_mouse_click_release_over_plot)
  655. # signal that the mouse events are disconnected from local methods
  656. self.mouse_events_connected = False
  657. # restore selection
  658. self.app.defaults['global_selection_shape'] = self.old_selection_state
  659. self.app.inform.emit(_("Finished manual adding of Test Point..."))
  660. pts_list = []
  661. for k in self.al_geometry_dict:
  662. pts_list.append(self.al_geometry_dict[k]['point'])
  663. self.calculate_voronoi_diagram(pts=pts_list)
  664. # rebuild the al table
  665. self.build_al_table_sig.emit()
  666. def on_key_press(self, event):
  667. # events out of the self.app.collection view (it's about Project Tab) are of type int
  668. if type(event) is int:
  669. key = event
  670. # events from the GUI are of type QKeyEvent
  671. elif type(event) == QtGui.QKeyEvent:
  672. key = event.key()
  673. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  674. key = event.key
  675. key = QtGui.QKeySequence(key)
  676. # check for modifiers
  677. key_string = key.toString().lower()
  678. if '+' in key_string:
  679. mod, __, key_text = key_string.rpartition('+')
  680. if mod.lower() == 'ctrl':
  681. # modifiers = QtCore.Qt.ControlModifier
  682. pass
  683. elif mod.lower() == 'alt':
  684. # modifiers = QtCore.Qt.AltModifier
  685. pass
  686. elif mod.lower() == 'shift':
  687. # modifiers = QtCore.Qt.ShiftModifier
  688. pass
  689. else:
  690. # modifiers = QtCore.Qt.NoModifier
  691. pass
  692. key = QtGui.QKeySequence(key_text)
  693. # events from Vispy are of type KeyEvent
  694. else:
  695. key = event.key
  696. # Escape = Deselect All
  697. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  698. if self.mouse_events_connected is True:
  699. self.mouse_events_connected = False
  700. if self.app.is_legacy is False:
  701. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  702. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  703. else:
  704. self.app.plotcanvas.graph_event_disconnect(self.kp)
  705. self.app.plotcanvas.graph_event_disconnect(self.mr)
  706. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  707. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  708. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  709. self.app.on_mouse_click_release_over_plot)
  710. if self.ui.big_cursor_cb.get_value():
  711. # restore cursor
  712. self.app.on_cursor_type(val=self.old_cursor_type)
  713. # restore selection
  714. self.app.defaults['global_selection_shape'] = self.old_selection_state
  715. # Grid toggle
  716. if key == QtCore.Qt.Key_G or key == 'G':
  717. self.app.ui.grid_snap_btn.trigger()
  718. # Jump to coords
  719. if key == QtCore.Qt.Key_J or key == 'J':
  720. l_x, l_y = self.app.on_jump_to()
  721. def on_autolevelling(self, state):
  722. self.ui.al_frame.show() if state else self.ui.al_frame.hide()
  723. self.app.defaults["cncjob_al_status"] = True if state else False
  724. def on_show_al_table(self, state):
  725. self.ui.al_probe_points_table.show() if state else self.ui.al_probe_points_table.hide()
  726. def on_mode_radio(self, val):
  727. # reset al table
  728. self.ui.al_probe_points_table.setRowCount(0)
  729. # reset the al dict
  730. self.al_geometry_dict.clear()
  731. # build AL table
  732. self.build_al_table()
  733. if val == "manual":
  734. self.ui.al_rows_entry.setDisabled(True)
  735. self.ui.al_rows_label.setDisabled(True)
  736. self.ui.al_columns_entry.setDisabled(True)
  737. self.ui.al_columns_label.setDisabled(True)
  738. else:
  739. self.ui.al_rows_entry.setDisabled(False)
  740. self.ui.al_rows_label.setDisabled(False)
  741. self.ui.al_columns_entry.setDisabled(False)
  742. self.ui.al_columns_label.setDisabled(False)
  743. def on_controller_change(self):
  744. if self.ui.al_controller_combo.get_value() == 'GRBL':
  745. self.ui.h_gcode_button.hide()
  746. self.ui.view_h_gcode_button.hide()
  747. self.ui.import_heights_button.hide()
  748. self.ui.grbl_frame.show()
  749. self.on_search_ports(muted=True)
  750. else:
  751. self.ui.h_gcode_button.show()
  752. self.ui.view_h_gcode_button.show()
  753. self.ui.import_heights_button.show()
  754. self.ui.grbl_frame.hide()
  755. def list_serial_ports(self):
  756. """
  757. Lists serial port names.
  758. From here: https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
  759. :raises EnvironmentError: On unsupported or unknown platforms
  760. :returns: A list of the serial ports available on the system
  761. """
  762. if sys.platform.startswith('win'):
  763. ports = ['COM%s' % (i + 1) for i in range(256)]
  764. elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
  765. # this excludes your current terminal "/dev/tty"
  766. ports = glob.glob('/dev/tty[A-Za-z]*')
  767. elif sys.platform.startswith('darwin'):
  768. ports = glob.glob('/dev/tty.*')
  769. else:
  770. raise EnvironmentError('Unsupported platform')
  771. result = []
  772. s = serial.Serial()
  773. for port in ports:
  774. s.port = port
  775. try:
  776. s.open()
  777. s.close()
  778. result.append(port)
  779. except (OSError, serial.SerialException):
  780. # result.append(port + " (in use)")
  781. pass
  782. return result
  783. def on_search_ports(self, muted=None):
  784. port_list = self.list_serial_ports()
  785. self.ui.com_list_combo.clear()
  786. self.ui.com_list_combo.addItems(port_list)
  787. if muted is not True:
  788. self.app.inform.emit('[WARNING_NOTCL] %s' % _("COM list updated ..."))
  789. def on_connect_grbl(self):
  790. port_name = self.ui.com_list_combo.currentText()
  791. if " (" in port_name:
  792. port_name = port_name.rpartition(" (")[0]
  793. baudrate = int(self.ui.baudrates_list_combo.currentText())
  794. try:
  795. self.grbl_ser_port = serial.serial_for_url(port_name, baudrate,
  796. bytesize=serial.EIGHTBITS,
  797. parity=serial.PARITY_NONE,
  798. stopbits=serial.STOPBITS_ONE,
  799. timeout=0.1,
  800. xonxoff=False,
  801. rtscts=False)
  802. # Toggle DTR to reset the controller loaded with GRBL (Arduino, ESP32, etc)
  803. try:
  804. self.grbl_ser_port.dtr = False
  805. except IOError:
  806. pass
  807. self.grbl_ser_port.reset_input_buffer()
  808. try:
  809. self.grbl_ser_port.dtr = True
  810. except IOError:
  811. pass
  812. answer = self.wake_grbl()
  813. answer = ['ok'] # hack for development without a GRBL controller connected
  814. for line in answer:
  815. if 'ok' in line.lower():
  816. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: seagreen;}")
  817. self.ui.com_connect_button.setText(_("Connected"))
  818. self.ui.controller_reset_button.setDisabled(False)
  819. for idx in range(self.ui.al_toolbar.count()):
  820. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  821. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('seagreen'))
  822. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  823. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  824. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  825. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  826. self.app.inform.emit("%s: %s" % (_("Port connected"), port_name))
  827. return
  828. self.grbl_ser_port.close()
  829. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to GRBL on port"), port_name))
  830. except serial.SerialException:
  831. self.grbl_ser_port = serial.Serial()
  832. self.grbl_ser_port.port = port_name
  833. self.grbl_ser_port.close()
  834. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: red;}")
  835. self.ui.com_connect_button.setText(_("Disconnected"))
  836. self.ui.controller_reset_button.setDisabled(True)
  837. for idx in range(self.ui.al_toolbar.count()):
  838. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  839. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  840. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  841. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  842. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  843. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  844. self.app.inform.emit("%s: %s" % (_("Port is connected. Disconnecting"), port_name))
  845. except Exception:
  846. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to port"), port_name))
  847. def on_add_baudrate_grbl(self):
  848. new_bd = str(self.ui.new_baudrate_entry.get_value())
  849. if int(new_bd) >= 40 and new_bd not in self.ui.baudrates_list_combo.model().stringList():
  850. self.ui.baudrates_list_combo.addItem(new_bd)
  851. self.ui.baudrates_list_combo.setCurrentText(new_bd)
  852. def on_delete_baudrate_grbl(self):
  853. current_idx = self.ui.baudrates_list_combo.currentIndex()
  854. self.ui.baudrates_list_combo.removeItem(current_idx)
  855. def wake_grbl(self):
  856. # Wake up grbl
  857. self.grbl_ser_port.write("\r\n\r\n".encode('utf-8'))
  858. # Wait for GRBL controller to initialize
  859. time.sleep(1)
  860. grbl_out = deepcopy(self.grbl_ser_port.readlines())
  861. self.grbl_ser_port.reset_input_buffer()
  862. return grbl_out
  863. def on_send_grbl_command(self):
  864. cmd = self.ui.grbl_command_entry.get_value()
  865. # show the Shell Dock
  866. self.app.ui.shell_dock.show()
  867. def worker_task():
  868. with self.app.proc_container.new(_("Sending GCode...")):
  869. self.send_grbl_command(command=cmd)
  870. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  871. def send_grbl_command(self, command, echo=True):
  872. stripped_cmd = command.strip()
  873. cmd = stripped_cmd.rpartition('\n')[0]
  874. if echo:
  875. self.app.inform_shell[str, bool].emit(cmd, False)
  876. # Send Gcode command to GRBL
  877. snd = cmd + '\n'
  878. self.grbl_ser_port.write(snd.encode('utf-8'))
  879. grbl_out = self.grbl_ser_port.readlines()
  880. result = False
  881. for line in grbl_out:
  882. if echo:
  883. try:
  884. self.app.inform_shell.emit(' : ' + line.decode('utf-8').strip().upper())
  885. except Exception as e:
  886. log.debug("CNCJobObject.send_grbl_command() --> %s" % str(e))
  887. if 'ok' in line:
  888. result = True
  889. return result
  890. def send_grbl_block(self, command, echo=True):
  891. stripped_cmd = command.strip()
  892. for l in stripped_cmd.split('\n'):
  893. if echo:
  894. self.app.inform_shell[str, bool].emit(l, False)
  895. # Send Gcode block to GRBL
  896. snd = l + '\n'
  897. self.grbl_ser_port.write(snd.encode('utf-8'))
  898. grbl_out = self.grbl_ser_port.readlines()
  899. for line in grbl_out:
  900. if echo:
  901. try:
  902. self.app.inform_shell.emit(' : ' + line.decode('utf-8').strip().upper())
  903. except Exception as e:
  904. log.debug("CNCJobObject.send_grbl_block() --> %s" % str(e))
  905. def get_grbl_parameter(self, param):
  906. if '$' in param:
  907. param = param.replace('$','')
  908. snd = '$$\n'
  909. self.grbl_ser_port.write(snd.encode('utf-8'))
  910. grbl_out = self.grbl_ser_port.readlines()
  911. for line in grbl_out:
  912. decoded_line = line.decode('utf-8')
  913. par = '$%s' % str(param)
  914. if par in decoded_line:
  915. result = float(decoded_line.rpartition('=')[2])
  916. self.app.shell_message("GRBL Parameter: %s = %s" % (str(param), str(result)), show=True)
  917. return result
  918. def on_jog(self, direction=None, step=5.0):
  919. if direction is None:
  920. return
  921. cmd = ''
  922. if direction == 'xplus':
  923. cmd = "$J=G91 %s X%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  924. if direction == 'xminus':
  925. cmd = "$J=G91 %s X-%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  926. if direction == 'yplus':
  927. cmd = "$J=G91 %s Y%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  928. if direction == 'yminus':
  929. cmd = "$J=G91 %s Y-%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  930. if direction == 'zplus':
  931. cmd = "$J=G91 %s Z%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  932. if direction == 'zminus':
  933. cmd = "$J=G91 %s Z-%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  934. self.send_grbl_command(command=cmd, echo=False)
  935. def on_grbl_reset(self):
  936. cmd = '\x18'
  937. self.wake_grbl()
  938. self.send_grbl_command(command=cmd)
  939. self.app.inform.emit("%s" % _("GRBL software reset was sent."))
  940. def probing_gcode(self, coords, pr_travel, probe_fr, pr_depth, controller):
  941. """
  942. :param coords: a list of (x, y) tuples of probe points coordinates
  943. :type coords: list
  944. :param pr_travel: the height (z) where the probe travel between probe points
  945. :type pr_travel: float
  946. :param probe_fr: feedrate when probing
  947. :type probe_fr: float
  948. :param pr_depth: how much to lower the probe searching for contact
  949. :type pr_depth: float
  950. :param controller: a string with the name of the GCode sender for which to create the probing GCode.
  951. Can be: 'MACH3', 'MACH4', 'LinuxCNC', 'GRBL'
  952. :type controller: str
  953. :return: Probing GCode
  954. :rtype: str
  955. """
  956. p_gcode = ''
  957. header = ''
  958. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  959. header += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  960. (str(self.app.version), str(self.app.version_date)) + '\n'
  961. header += '(This is a autolevelling probing GCode.)\n' \
  962. '(Make sure that before you start the job you first do a zero for all axis.)\n\n'
  963. header += '(Name: ' + str(self.options['name']) + ')\n'
  964. header += '(Type: ' + "Autolevelling Probing GCode " + ')\n'
  965. header += '(Units: ' + self.units.upper() + ')\n'
  966. header += '(Created on ' + time_str + ')\n'
  967. # commands
  968. if controller == 'MACH3':
  969. probing_command = 'G31'
  970. probing_var = '#2002'
  971. openfile_command = 'M40'
  972. closefile_command = 'M41'
  973. elif controller == 'MACH4':
  974. probing_command = 'G31'
  975. probing_var = '#5063'
  976. openfile_command = 'M40'
  977. closefile_command = 'M41'
  978. elif controller == 'LinuxCNC':
  979. probing_command = 'G38.2'
  980. probing_var = '#5422'
  981. openfile_command = '(PROBEOPEN a_probing_points_file.txt)'
  982. closefile_command = '(PROBECLOSE)'
  983. else:
  984. log.debug("CNCJobObject.probing_gcode() -> controller not supported")
  985. return
  986. # #############################################################################################################
  987. # ########################### GCODE construction ##############################################################
  988. # #############################################################################################################
  989. # header
  990. p_gcode += header + '\n'
  991. # supplementary message for LinuxCNC
  992. if controller == 'LinuxCNC':
  993. probing_var += "The file with the stored probing points can be found\n" \
  994. "in the configuration folder for LinuxCNC.\n" \
  995. "The name of the file is: a_probing_points_file.txt.\n"
  996. # units
  997. p_gcode += 'G21\n' if self.units == 'MM' else 'G20\n'
  998. # reference mode = absolute
  999. p_gcode += 'G90\n'
  1000. # open a new file
  1001. p_gcode += openfile_command + '\n'
  1002. # move to safe height (probe travel Z)
  1003. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1004. # probing points
  1005. for idx, xy_tuple in enumerate(coords, 1): # index starts from 1
  1006. x = xy_tuple[0]
  1007. y = xy_tuple[1]
  1008. # move to probing point
  1009. p_gcode += "G0 X%sY%s\n" % (
  1010. str(self.app.dec_format(x, self.coords_decimals)),
  1011. str(self.app.dec_format(y, self.coords_decimals))
  1012. )
  1013. # do the probing
  1014. p_gcode += "%s Z%s F%s\n" % (
  1015. probing_command,
  1016. str(self.app.dec_format(pr_depth, self.coords_decimals)),
  1017. str(self.app.dec_format(probe_fr, self.fr_decimals)),
  1018. )
  1019. # store in a global numeric variable the value of the detected probe Z
  1020. # I offset the global numeric variable by 500 so it does not conflict with something else
  1021. temp_var = int(idx + 500)
  1022. p_gcode += "#%d = %s\n" % (temp_var, probing_var)
  1023. # move to safe height (probe travel Z)
  1024. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1025. # close the file
  1026. p_gcode += closefile_command + '\n'
  1027. # finish the GCode
  1028. p_gcode += 'M2'
  1029. return p_gcode
  1030. def on_generate_probing_gcode(self):
  1031. coords = []
  1032. for id_key, value in self.al_geometry_dict.items():
  1033. x = value['point'].x
  1034. y = value['point'].y
  1035. coords.append(
  1036. (
  1037. self.app.dec_format(x, dec=self.app.decimals),
  1038. self.app.dec_format(y, dec=self.app.decimals)
  1039. )
  1040. )
  1041. pr_travel = self.ui.ptravelz_entry.get_value()
  1042. probe_fr = self.ui.feedrate_probe_entry.get_value()
  1043. pr_depth = self.ui.pdepth_entry.get_value()
  1044. controller = self.ui.al_controller_combo.get_value()
  1045. self.probing_gcode_text = self.probing_gcode(coords, pr_travel, probe_fr, pr_depth, controller)
  1046. def on_view_probing_gcode(self):
  1047. self.app.proc_container.view.set_busy(_("Loading..."))
  1048. gco = self.probing_gcode_text
  1049. if gco is None or gco == '':
  1050. self.app.inform.emit('[WARNING_NOTCL] %s...' % _('There is nothing to view'))
  1051. return
  1052. self.gcode_viewer_tab = AppTextEditor(app=self.app, plain_text=True)
  1053. # add the tab if it was closed
  1054. self.app.ui.plot_tab_area.addTab(self.gcode_viewer_tab, '%s' % _("Code Viewer"))
  1055. self.gcode_viewer_tab.setObjectName('code_viewer_tab')
  1056. # delete the absolute and relative position and messages in the infobar
  1057. self.app.ui.position_label.setText("")
  1058. self.app.ui.rel_position_label.setText("")
  1059. self.gcode_viewer_tab.code_editor.completer_enable = False
  1060. self.gcode_viewer_tab.buttonRun.hide()
  1061. # Switch plot_area to CNCJob tab
  1062. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_viewer_tab)
  1063. self.gcode_viewer_tab.t_frame.hide()
  1064. # then append the text from GCode to the text editor
  1065. try:
  1066. self.gcode_viewer_tab.load_text(gco, move_to_start=True, clear_text=True)
  1067. except Exception as e:
  1068. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1069. return
  1070. self.gcode_viewer_tab.t_frame.show()
  1071. self.app.proc_container.view.set_idle()
  1072. self.gcode_viewer_tab.buttonSave.hide()
  1073. self.gcode_viewer_tab.buttonOpen.hide()
  1074. self.gcode_viewer_tab.buttonPrint.hide()
  1075. self.gcode_viewer_tab.buttonPreview.hide()
  1076. self.gcode_viewer_tab.buttonReplace.hide()
  1077. self.gcode_viewer_tab.sel_all_cb.hide()
  1078. self.gcode_viewer_tab.entryReplace.hide()
  1079. self.gcode_viewer_tab.code_editor.setReadOnly(True)
  1080. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Viewer'))
  1081. def on_import_height_map(self):
  1082. """
  1083. Import the height map file into the app
  1084. :return:
  1085. :rtype:
  1086. """
  1087. _filter_ = "Text File .txt (*.txt);;All Files (*.*)"
  1088. try:
  1089. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1090. directory=self.app.get_last_folder(),
  1091. filter=_filter_)
  1092. except TypeError:
  1093. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1094. filter=_filter_)
  1095. filename = str(filename)
  1096. if filename == '':
  1097. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1098. else:
  1099. self.app.worker_task.emit({'fcn': self.import_height_map, 'params': [filename]})
  1100. def import_height_map(self, filename):
  1101. """
  1102. :param filename:
  1103. :type filename:
  1104. :return:
  1105. :rtype:
  1106. """
  1107. stream = ''
  1108. try:
  1109. if filename:
  1110. with open(filename, 'r') as f:
  1111. stream = f.readlines()
  1112. else:
  1113. return
  1114. except IOError:
  1115. log.error("Failed to open height map file: %s" % filename)
  1116. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open height map file"), filename))
  1117. return
  1118. idx = 0
  1119. for line in stream:
  1120. if line != '':
  1121. idx += 1
  1122. line = line.replace(' ', ',').replace('\n', '').split(',')
  1123. if idx not in self.al_geometry_dict:
  1124. self.al_geometry_dict[idx] = {}
  1125. self.al_geometry_dict[idx]['height'] = float(line[2])
  1126. if 'point' not in self.al_geometry_dict[idx]:
  1127. x = float(line[0])
  1128. y = float(line[1])
  1129. self.al_geometry_dict[idx]['point'] = Point((x, y))
  1130. self.build_al_table_sig.emit()
  1131. def on_updateplot_button_click(self, *args):
  1132. """
  1133. Callback for the "Updata Plot" button. Reads the form for updates
  1134. and plots the object.
  1135. """
  1136. self.read_form()
  1137. self.on_plot_kind_change()
  1138. def on_plot_kind_change(self):
  1139. kind = self.ui.cncplot_method_combo.get_value()
  1140. def worker_task():
  1141. with self.app.proc_container.new(_("Plotting...")):
  1142. self.plot(kind=kind)
  1143. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  1144. def on_exportgcode_button_click(self):
  1145. """
  1146. Handler activated by a button clicked when exporting GCode.
  1147. :param args:
  1148. :return:
  1149. """
  1150. self.app.defaults.report_usage("cncjob_on_exportgcode_button")
  1151. self.read_form()
  1152. name = self.app.collection.get_active().options['name']
  1153. save_gcode = False
  1154. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  1155. _filter_ = "RML1 Files .rol (*.rol);;All Files (*.*)"
  1156. elif 'hpgl' in self.pp_geometry_name:
  1157. _filter_ = "HPGL Files .plt (*.plt);;All Files (*.*)"
  1158. else:
  1159. save_gcode = True
  1160. _filter_ = self.app.defaults['cncjob_save_filters']
  1161. try:
  1162. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1163. filename, _f = FCFileSaveDialog.get_saved_filename(
  1164. caption=_("Export Code ..."),
  1165. directory=dir_file_to_save,
  1166. ext_filter=_filter_
  1167. )
  1168. except TypeError:
  1169. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1170. self.export_gcode_handler(filename, is_gcode=save_gcode)
  1171. def export_gcode_handler(self, filename, is_gcode=True):
  1172. preamble = ''
  1173. postamble = ''
  1174. filename = str(filename)
  1175. if filename == '':
  1176. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1177. return
  1178. else:
  1179. if is_gcode is True:
  1180. used_extension = filename.rpartition('.')[2]
  1181. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  1182. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  1183. self.ui.name_entry.set_value(new_name)
  1184. self.on_name_activate(silent=True)
  1185. try:
  1186. if self.ui.snippets_cb.get_value():
  1187. preamble = self.append_snippet
  1188. postamble = self.prepend_snippet
  1189. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  1190. except Exception as err:
  1191. log.debug("CNCJobObject.export_gcode_handler() --> %s" % str(err))
  1192. gc = self.export_gcode(filename)
  1193. if gc == 'fail':
  1194. return
  1195. if self.app.defaults["global_open_style"] is False:
  1196. self.app.file_opened.emit("gcode", filename)
  1197. self.app.file_saved.emit("gcode", filename)
  1198. self.app.inform.emit('[success] %s: %s' % (_("File saved to"), filename))
  1199. def on_edit_code_click(self, *args):
  1200. """
  1201. Handler activated by a button clicked when reviewing GCode.
  1202. :param args:
  1203. :return:
  1204. """
  1205. self.app.proc_container.view.set_busy(_("Loading..."))
  1206. preamble = self.append_snippet
  1207. postamble = self.prepend_snippet
  1208. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  1209. if gco == 'fail':
  1210. return
  1211. else:
  1212. self.app.gcode_edited = gco
  1213. self.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  1214. # add the tab if it was closed
  1215. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Review"))
  1216. self.gcode_editor_tab.setObjectName('code_editor_tab')
  1217. # delete the absolute and relative position and messages in the infobar
  1218. self.app.ui.position_label.setText("")
  1219. self.app.ui.rel_position_label.setText("")
  1220. self.gcode_editor_tab.code_editor.completer_enable = False
  1221. self.gcode_editor_tab.buttonRun.hide()
  1222. # Switch plot_area to CNCJob tab
  1223. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  1224. self.gcode_editor_tab.t_frame.hide()
  1225. # then append the text from GCode to the text editor
  1226. try:
  1227. self.gcode_editor_tab.load_text(self.app.gcode_edited.getvalue(), move_to_start=True, clear_text=True)
  1228. except Exception as e:
  1229. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1230. return
  1231. self.gcode_editor_tab.t_frame.show()
  1232. self.app.proc_container.view.set_idle()
  1233. self.gcode_editor_tab.buttonSave.hide()
  1234. self.gcode_editor_tab.buttonOpen.hide()
  1235. self.gcode_editor_tab.buttonPrint.hide()
  1236. self.gcode_editor_tab.buttonPreview.hide()
  1237. self.gcode_editor_tab.buttonReplace.hide()
  1238. self.gcode_editor_tab.sel_all_cb.hide()
  1239. self.gcode_editor_tab.entryReplace.hide()
  1240. self.gcode_editor_tab.code_editor.setReadOnly(True)
  1241. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  1242. def on_update_source_file(self):
  1243. self.source_file = self.gcode_editor_tab.code_editor.toPlainText()
  1244. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  1245. """
  1246. Will create a header to be added to all GCode files generated by FlatCAM
  1247. :param comment_start_symbol: A symbol to be used as the first symbol in a comment
  1248. :param comment_stop_symbol: A symbol to be used as the last symbol in a comment
  1249. :return: A string with a GCode header
  1250. """
  1251. log.debug("FlatCAMCNCJob.gcode_header()")
  1252. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1253. marlin = False
  1254. hpgl = False
  1255. probe_pp = False
  1256. gcode = ''
  1257. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  1258. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  1259. try:
  1260. for key in self.cnc_tools:
  1261. ppg = self.cnc_tools[key]['data']['ppname_g']
  1262. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  1263. marlin = True
  1264. break
  1265. if ppg == 'hpgl':
  1266. hpgl = True
  1267. break
  1268. if "toolchange_probe" in ppg.lower():
  1269. probe_pp = True
  1270. break
  1271. except KeyError:
  1272. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  1273. pass
  1274. try:
  1275. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  1276. marlin = True
  1277. except KeyError:
  1278. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1279. pass
  1280. try:
  1281. if "toolchange_probe" in self.options['ppname_e'].lower():
  1282. probe_pp = True
  1283. except KeyError:
  1284. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1285. pass
  1286. if marlin is True:
  1287. gcode += ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  1288. (str(self.app.version), str(self.app.version_date)) + '\n'
  1289. gcode += ';Name: ' + str(self.options['name']) + '\n'
  1290. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  1291. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1292. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1293. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  1294. gcode += ';Created on ' + time_str + '\n' + '\n'
  1295. elif hpgl is True:
  1296. gcode += 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  1297. (str(self.app.version), str(self.app.version_date)) + '";\n'
  1298. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  1299. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  1300. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1301. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1302. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  1303. gcode += 'CO "Created on ' + time_str + '";\n'
  1304. elif probe_pp is True:
  1305. gcode += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1306. (str(self.app.version), str(self.app.version_date)) + '\n'
  1307. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  1308. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  1309. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  1310. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  1311. 'Then zero the Z axis.)\n' + '\n'
  1312. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  1313. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  1314. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1315. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1316. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1317. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1318. else:
  1319. gcode += '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  1320. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  1321. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  1322. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  1323. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1324. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1325. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  1326. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  1327. return gcode
  1328. @staticmethod
  1329. def gcode_footer(end_command=None):
  1330. """
  1331. Will add the M02 to the end of GCode, if requested.
  1332. :param end_command: 'M02' or 'M30' - String
  1333. :return:
  1334. """
  1335. if end_command:
  1336. return end_command
  1337. else:
  1338. return 'M02'
  1339. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False, from_tcl=False):
  1340. """
  1341. This will save the GCode from the Gcode object to a file on the OS filesystem
  1342. :param filename: filename for the GCode file
  1343. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  1344. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  1345. :param to_file: if False then no actual file is saved but the app will know that a file was created
  1346. :param from_tcl: True if run from Tcl Shell
  1347. :return: None
  1348. """
  1349. # gcode = ''
  1350. # roland = False
  1351. # hpgl = False
  1352. # isel_icp = False
  1353. include_header = True
  1354. if preamble == '':
  1355. preamble = self.app.defaults["cncjob_prepend"]
  1356. if postamble == '':
  1357. preamble = self.app.defaults["cncjob_append"]
  1358. try:
  1359. if self.special_group:
  1360. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  1361. (_("This CNCJob object can't be processed because it is a"),
  1362. str(self.special_group),
  1363. _("CNCJob object")))
  1364. return 'fail'
  1365. except AttributeError:
  1366. pass
  1367. # if this dict is not empty then the object is a Geometry object
  1368. if self.cnc_tools:
  1369. first_key = next(iter(self.cnc_tools))
  1370. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  1371. # if this dict is not empty then the object is an Excellon object
  1372. if self.exc_cnc_tools:
  1373. first_key = next(iter(self.exc_cnc_tools))
  1374. include_header = self.app.preprocessors[
  1375. self.exc_cnc_tools[first_key]['data']['tools_drill_ppname_e']
  1376. ].include_header
  1377. gcode = ''
  1378. if include_header is False:
  1379. g = preamble
  1380. # detect if using multi-tool and make the Gcode summation correctly for each case
  1381. if self.multitool is True:
  1382. for tooluid_key in self.cnc_tools:
  1383. for key, value in self.cnc_tools[tooluid_key].items():
  1384. if key == 'gcode':
  1385. gcode += value
  1386. break
  1387. else:
  1388. gcode += self.gcode
  1389. g = g + gcode + postamble
  1390. else:
  1391. # search for the GCode beginning which is usually a G20 or G21
  1392. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  1393. # g_idx = gcode.rfind('G20')
  1394. #
  1395. # # if it did not find 'G20' then search for 'G21'
  1396. # if g_idx == -1:
  1397. # g_idx = gcode.rfind('G21')
  1398. #
  1399. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  1400. # if g_idx == -1:
  1401. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  1402. # return
  1403. # detect if using multi-tool and make the Gcode summation correctly for each case
  1404. if self.multitool is True:
  1405. if self.origin_kind == 'excellon':
  1406. for tooluid_key in self.exc_cnc_tools:
  1407. for key, value in self.exc_cnc_tools[tooluid_key].items():
  1408. if key == 'gcode' and value:
  1409. gcode += value
  1410. break
  1411. else:
  1412. for tooluid_key in self.cnc_tools:
  1413. for key, value in self.cnc_tools[tooluid_key].items():
  1414. if key == 'gcode' and value:
  1415. gcode += value
  1416. break
  1417. else:
  1418. gcode += self.gcode
  1419. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  1420. # detect if using a HPGL preprocessor
  1421. hpgl = False
  1422. if self.cnc_tools:
  1423. for key in self.cnc_tools:
  1424. if 'ppname_g' in self.cnc_tools[key]['data']:
  1425. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  1426. hpgl = True
  1427. break
  1428. elif self.exc_cnc_tools:
  1429. for key in self.cnc_tools:
  1430. if 'ppname_e' in self.cnc_tools[key]['data']:
  1431. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  1432. hpgl = True
  1433. break
  1434. if hpgl:
  1435. processed_gcode = ''
  1436. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  1437. for gline in gcode.splitlines():
  1438. match = pa_re.search(gline)
  1439. if match:
  1440. x_int = int(float(match.group(1)))
  1441. y_int = int(float(match.group(2)))
  1442. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  1443. processed_gcode += new_line
  1444. else:
  1445. processed_gcode += gline + '\n'
  1446. gcode = processed_gcode
  1447. g = self.gc_header + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  1448. else:
  1449. try:
  1450. g_idx = gcode.index('G94')
  1451. if preamble != '' and postamble != '':
  1452. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1453. gcode[(g_idx + 3):] + postamble + end_gcode
  1454. elif preamble == '':
  1455. g = self.gc_header + gcode[:g_idx + 3] + '\n' + \
  1456. gcode[(g_idx + 3):] + postamble + end_gcode
  1457. elif postamble == '':
  1458. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1459. gcode[(g_idx + 3):] + end_gcode
  1460. else:
  1461. g = self.gc_header + gcode[:g_idx + 3] + gcode[(g_idx + 3):] + end_gcode
  1462. except ValueError:
  1463. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1464. _("G-code does not have a G94 code.\n"
  1465. "Append Code snippet will not be used.."))
  1466. g = self.gc_header + '\n' + gcode + postamble + end_gcode
  1467. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  1468. # if self.ui.toolchange_cb.get_value() is True:
  1469. # # match = self.re_toolchange.search(g)
  1470. # if 'M6' in g:
  1471. # m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  1472. # if m6_code is None or m6_code == '':
  1473. # self.app.inform.emit(
  1474. # '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  1475. # )
  1476. # return 'fail'
  1477. #
  1478. # g = g.replace('M6', m6_code)
  1479. # self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  1480. lines = StringIO(g)
  1481. # Write
  1482. if filename is not None:
  1483. try:
  1484. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1485. if force_windows_line_endings and sys.platform != 'win32':
  1486. with open(filename, 'w', newline='\r\n') as f:
  1487. for line in lines:
  1488. f.write(line)
  1489. else:
  1490. with open(filename, 'w') as f:
  1491. for line in lines:
  1492. f.write(line)
  1493. except FileNotFoundError:
  1494. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1495. return
  1496. except PermissionError:
  1497. self.app.inform.emit(
  1498. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1499. "Most likely another app is holding the file open and not accessible.")
  1500. )
  1501. return 'fail'
  1502. elif to_file is False:
  1503. # Just for adding it to the recent files list.
  1504. if self.app.defaults["global_open_style"] is False:
  1505. self.app.file_opened.emit("cncjob", filename)
  1506. self.app.file_saved.emit("cncjob", filename)
  1507. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  1508. else:
  1509. return lines
  1510. # def on_toolchange_custom_clicked(self, signal):
  1511. # """
  1512. # Handler for clicking toolchange custom.
  1513. #
  1514. # :param signal:
  1515. # :return:
  1516. # """
  1517. #
  1518. # try:
  1519. # if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  1520. # if self.ui.toolchange_cb.get_value():
  1521. # self.ui.toolchange_cb.set_value(False)
  1522. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1523. # _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  1524. # except KeyError:
  1525. # try:
  1526. # for key in self.cnc_tools:
  1527. # ppg = self.cnc_tools[key]['data']['ppname_g']
  1528. # if 'toolchange_custom' not in str(ppg).lower():
  1529. # if self.ui.toolchange_cb.get_value():
  1530. # self.ui.toolchange_cb.set_value(False)
  1531. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1532. # _("The used preprocessor file has to have in it's name: "
  1533. # "'toolchange_custom'"))
  1534. # except KeyError:
  1535. # self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  1536. def get_gcode(self, preamble='', postamble=''):
  1537. """
  1538. We need this to be able to get_gcode separately for shell command export_gcode
  1539. :param preamble: Extra GCode added to the beginning of the GCode
  1540. :param postamble: Extra GCode added at the end of the GCode
  1541. :return: The modified GCode
  1542. """
  1543. return preamble + '\n' + self.gcode + "\n" + postamble
  1544. def get_svg(self):
  1545. # we need this to be able get_svg separately for shell command export_svg
  1546. pass
  1547. def on_plot_cb_click(self, *args):
  1548. """
  1549. Handler for clicking on the Plot checkbox.
  1550. :param args:
  1551. :return:
  1552. """
  1553. if self.muted_ui:
  1554. return
  1555. kind = self.ui.cncplot_method_combo.get_value()
  1556. self.plot(kind=kind)
  1557. self.read_form_item('plot')
  1558. self.ui_disconnect()
  1559. cb_flag = self.ui.plot_cb.isChecked()
  1560. for row in range(self.ui.cnc_tools_table.rowCount()):
  1561. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  1562. if cb_flag:
  1563. table_cb.setChecked(True)
  1564. else:
  1565. table_cb.setChecked(False)
  1566. self.ui_connect()
  1567. def on_plot_cb_click_table(self):
  1568. """
  1569. Handler for clicking the plot checkboxes added into a Table on each row. Purpose: toggle visibility for the
  1570. tool/aperture found on that row.
  1571. :return:
  1572. """
  1573. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1574. self.ui_disconnect()
  1575. # cw = self.sender()
  1576. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  1577. # cw_row = cw_index.row()
  1578. kind = self.ui.cncplot_method_combo.get_value()
  1579. self.shapes.clear(update=True)
  1580. if self.origin_kind == "excellon":
  1581. for r in range(self.ui.exc_cnc_tools_table.rowCount()):
  1582. row_dia = float('%.*f' % (self.decimals, float(self.ui.exc_cnc_tools_table.item(r, 1).text())))
  1583. for tooluid_key in self.exc_cnc_tools:
  1584. tooldia = float('%.*f' % (self.decimals, float(tooluid_key)))
  1585. if row_dia == tooldia:
  1586. gcode_parsed = self.exc_cnc_tools[tooluid_key]['gcode_parsed']
  1587. if self.ui.exc_cnc_tools_table.cellWidget(r, 6).isChecked():
  1588. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1589. else:
  1590. for tooluid_key in self.cnc_tools:
  1591. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1592. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1593. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  1594. for r in range(self.ui.cnc_tools_table.rowCount()):
  1595. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  1596. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  1597. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1598. self.shapes.redraw()
  1599. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1600. # if all the row plot's are enabled also enable the general plot checkbox
  1601. cb_cnt = 0
  1602. total_row = self.ui.cnc_tools_table.rowCount()
  1603. for row in range(total_row):
  1604. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  1605. cb_cnt += 1
  1606. else:
  1607. cb_cnt -= 1
  1608. if cb_cnt < total_row:
  1609. self.ui.plot_cb.setChecked(False)
  1610. else:
  1611. self.ui.plot_cb.setChecked(True)
  1612. self.ui_connect()
  1613. def plot(self, visible=None, kind='all'):
  1614. """
  1615. # Does all the required setup and returns False
  1616. # if the 'ptint' option is set to False.
  1617. :param visible: Boolean to decide if the object will be plotted as visible or disabled on canvas
  1618. :param kind: String. Can be "all" or "travel" or "cut". For CNCJob plotting
  1619. :return: None
  1620. """
  1621. if not FlatCAMObj.plot(self):
  1622. return
  1623. visible = visible if visible else self.options['plot']
  1624. if self.app.is_legacy is False:
  1625. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  1626. self.text_col.enabled = True
  1627. else:
  1628. self.text_col.enabled = False
  1629. self.annotation.redraw()
  1630. try:
  1631. if self.multitool is False: # single tool usage
  1632. try:
  1633. dia_plot = float(self.options["tooldia"])
  1634. except ValueError:
  1635. # we may have a tuple with only one element and a comma
  1636. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  1637. self.plot2(tooldia=dia_plot, obj=self, visible=visible, kind=kind)
  1638. else:
  1639. # I do this so the travel lines thickness will reflect the tool diameter
  1640. # may work only for objects created within the app and not Gcode imported from elsewhere for which we
  1641. # don't know the origin
  1642. if self.origin_kind == "excellon":
  1643. if self.exc_cnc_tools:
  1644. for tooldia_key in self.exc_cnc_tools:
  1645. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  1646. gcode_parsed = self.exc_cnc_tools[tooldia_key]['gcode_parsed']
  1647. if not gcode_parsed:
  1648. continue
  1649. # gcode_parsed = self.gcode_parsed
  1650. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1651. else:
  1652. # multiple tools usage
  1653. if self.cnc_tools:
  1654. for tooluid_key in self.cnc_tools:
  1655. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1656. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1657. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1658. self.shapes.redraw()
  1659. except (ObjectDeleted, AttributeError):
  1660. self.shapes.clear(update=True)
  1661. if self.app.is_legacy is False:
  1662. self.annotation.clear(update=True)
  1663. def on_annotation_change(self):
  1664. """
  1665. Handler for toggling the annotation display by clicking a checkbox.
  1666. :return:
  1667. """
  1668. if self.app.is_legacy is False:
  1669. if self.ui.annotation_cb.get_value():
  1670. self.text_col.enabled = True
  1671. else:
  1672. self.text_col.enabled = False
  1673. # kind = self.ui.cncplot_method_combo.get_value()
  1674. # self.plot(kind=kind)
  1675. self.annotation.redraw()
  1676. else:
  1677. kind = self.ui.cncplot_method_combo.get_value()
  1678. self.plot(kind=kind)
  1679. def convert_units(self, units):
  1680. """
  1681. Units conversion used by the CNCJob objects.
  1682. :param units: Can be "MM" or "IN"
  1683. :return:
  1684. """
  1685. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  1686. factor = CNCjob.convert_units(self, units)
  1687. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  1688. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  1689. 'endz', 'toolchangez']
  1690. temp_tools_dict = {}
  1691. tool_dia_copy = {}
  1692. data_copy = {}
  1693. for tooluid_key, tooluid_value in self.cnc_tools.items():
  1694. for dia_key, dia_value in tooluid_value.items():
  1695. if dia_key == 'tooldia':
  1696. dia_value *= factor
  1697. dia_value = float('%.*f' % (self.decimals, dia_value))
  1698. tool_dia_copy[dia_key] = dia_value
  1699. if dia_key == 'offset':
  1700. tool_dia_copy[dia_key] = dia_value
  1701. if dia_key == 'offset_value':
  1702. dia_value *= factor
  1703. tool_dia_copy[dia_key] = dia_value
  1704. if dia_key == 'type':
  1705. tool_dia_copy[dia_key] = dia_value
  1706. if dia_key == 'tool_type':
  1707. tool_dia_copy[dia_key] = dia_value
  1708. if dia_key == 'data':
  1709. for data_key, data_value in dia_value.items():
  1710. # convert the form fields that are convertible
  1711. for param in param_list:
  1712. if data_key == param and data_value is not None:
  1713. data_copy[data_key] = data_value * factor
  1714. # copy the other dict entries that are not convertible
  1715. if data_key not in param_list:
  1716. data_copy[data_key] = data_value
  1717. tool_dia_copy[dia_key] = deepcopy(data_copy)
  1718. data_copy.clear()
  1719. if dia_key == 'gcode':
  1720. tool_dia_copy[dia_key] = dia_value
  1721. if dia_key == 'gcode_parsed':
  1722. tool_dia_copy[dia_key] = dia_value
  1723. if dia_key == 'solid_geometry':
  1724. tool_dia_copy[dia_key] = dia_value
  1725. # if dia_key == 'solid_geometry':
  1726. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  1727. # if dia_key == 'gcode_parsed':
  1728. # for g in dia_value:
  1729. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1730. #
  1731. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  1732. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  1733. temp_tools_dict.update({
  1734. tooluid_key: deepcopy(tool_dia_copy)
  1735. })
  1736. tool_dia_copy.clear()
  1737. self.cnc_tools.clear()
  1738. self.cnc_tools = deepcopy(temp_tools_dict)