FlatCAMCNCJob.py 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094
  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
  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. points.append((new_x, new_y))
  553. pt_id = 0
  554. pts_list = []
  555. for point in points:
  556. pt_id += 1
  557. pt = Point(point)
  558. pts_list.append(pt)
  559. new_dict = {
  560. 'point': pt,
  561. 'geo': None,
  562. 'height': 0.0
  563. }
  564. self.al_geometry_dict[pt_id] = deepcopy(new_dict)
  565. self.calculate_voronoi_diagram(pts=pts_list)
  566. else:
  567. self.app.inform.emit(_("Click on canvas to add a Test Point..."))
  568. if self.app.is_legacy is False:
  569. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  570. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  571. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  572. else:
  573. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  574. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  575. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  576. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  577. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  578. self.mouse_events_connected = True
  579. self.build_al_table_sig.emit()
  580. def show_voronoi_diagram(self, state):
  581. if state:
  582. pass
  583. else:
  584. pass
  585. def calculate_voronoi_diagram(self, pts):
  586. pts_union = unary_union(pts)
  587. env = self.solid_geo.envelope
  588. try:
  589. voronoi_union = voronoi_diagram(geom=pts_union, envelope=env)
  590. print(voronoi_union)
  591. except Exception as e:
  592. log.debug("CNCJobObject.calculate_voronoi_diagram() --> %s" % str(e))
  593. return
  594. for pt_key in list(self.al_geometry_dict.keys()):
  595. for poly in voronoi_union:
  596. if self.al_geometry_dict[pt_key]['point'].within(poly):
  597. self.al_geometry_dict[pt_key]['geo'] = poly
  598. # To be called after clicking on the plot.
  599. def on_mouse_click_release(self, event):
  600. if self.app.is_legacy is False:
  601. event_pos = event.pos
  602. # event_is_dragging = event.is_dragging
  603. right_button = 2
  604. else:
  605. event_pos = (event.xdata, event.ydata)
  606. # event_is_dragging = self.app.plotcanvas.is_dragging
  607. right_button = 3
  608. try:
  609. x = float(event_pos[0])
  610. y = float(event_pos[1])
  611. except TypeError:
  612. return
  613. event_pos = (x, y)
  614. # do paint single only for left mouse clicks
  615. if event.button == 1:
  616. pos = self.app.plotcanvas.translate_coords(event_pos)
  617. # use the snapped position as reference
  618. snapped_pos = self.app.geo_editor.snap(pos[0], pos[1])
  619. if not self.al_geometry_dict:
  620. new_dict = {
  621. 'point': Point(snapped_pos),
  622. 'geo': None,
  623. 'height': 0.0
  624. }
  625. self.al_geometry_dict[1] = deepcopy(new_dict)
  626. else:
  627. int_keys = [int(k) for k in self.al_geometry_dict.keys()]
  628. new_id = max(int_keys) + 1
  629. new_dict = {
  630. 'point': Point(snapped_pos),
  631. 'geo': None,
  632. 'height': 0.0
  633. }
  634. self.al_geometry_dict[new_id] = deepcopy(new_dict)
  635. # rebuild the al table
  636. self.build_al_table_sig.emit()
  637. self.app.inform.emit(_("Added Test Point... Click again to add another or right click to finish ..."))
  638. # if RMB then we exit
  639. elif event.button == right_button and self.mouse_is_dragging is False:
  640. if self.app.is_legacy is False:
  641. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  642. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  643. else:
  644. self.app.plotcanvas.graph_event_disconnect(self.kp)
  645. self.app.plotcanvas.graph_event_disconnect(self.mr)
  646. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  647. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  648. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  649. self.app.on_mouse_click_release_over_plot)
  650. # signal that the mouse events are disconnected from local methods
  651. self.mouse_events_connected = False
  652. # restore selection
  653. self.app.defaults['global_selection_shape'] = self.old_selection_state
  654. self.app.inform.emit(_("Finished manual adding of Test Point..."))
  655. pts_list = []
  656. for k in self.al_geometry_dict:
  657. pts_list.append(self.al_geometry_dict[k]['point'])
  658. self.calculate_voronoi_diagram(pts=pts_list)
  659. # rebuild the al table
  660. self.build_al_table_sig.emit()
  661. def on_key_press(self, event):
  662. # events out of the self.app.collection view (it's about Project Tab) are of type int
  663. if type(event) is int:
  664. key = event
  665. # events from the GUI are of type QKeyEvent
  666. elif type(event) == QtGui.QKeyEvent:
  667. key = event.key()
  668. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  669. key = event.key
  670. key = QtGui.QKeySequence(key)
  671. # check for modifiers
  672. key_string = key.toString().lower()
  673. if '+' in key_string:
  674. mod, __, key_text = key_string.rpartition('+')
  675. if mod.lower() == 'ctrl':
  676. # modifiers = QtCore.Qt.ControlModifier
  677. pass
  678. elif mod.lower() == 'alt':
  679. # modifiers = QtCore.Qt.AltModifier
  680. pass
  681. elif mod.lower() == 'shift':
  682. # modifiers = QtCore.Qt.ShiftModifier
  683. pass
  684. else:
  685. # modifiers = QtCore.Qt.NoModifier
  686. pass
  687. key = QtGui.QKeySequence(key_text)
  688. # events from Vispy are of type KeyEvent
  689. else:
  690. key = event.key
  691. # Escape = Deselect All
  692. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  693. if self.mouse_events_connected is True:
  694. self.mouse_events_connected = False
  695. if self.app.is_legacy is False:
  696. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  697. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  698. else:
  699. self.app.plotcanvas.graph_event_disconnect(self.kp)
  700. self.app.plotcanvas.graph_event_disconnect(self.mr)
  701. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  702. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  703. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  704. self.app.on_mouse_click_release_over_plot)
  705. if self.ui.big_cursor_cb.get_value():
  706. # restore cursor
  707. self.app.on_cursor_type(val=self.old_cursor_type)
  708. # restore selection
  709. self.app.defaults['global_selection_shape'] = self.old_selection_state
  710. # Grid toggle
  711. if key == QtCore.Qt.Key_G or key == 'G':
  712. self.app.ui.grid_snap_btn.trigger()
  713. # Jump to coords
  714. if key == QtCore.Qt.Key_J or key == 'J':
  715. l_x, l_y = self.app.on_jump_to()
  716. def on_autolevelling(self, state):
  717. self.ui.al_frame.show() if state else self.ui.al_frame.hide()
  718. self.app.defaults["cncjob_al_status"] = True if state else False
  719. def on_show_al_table(self, state):
  720. self.ui.al_probe_points_table.show() if state else self.ui.al_probe_points_table.hide()
  721. def on_mode_radio(self, val):
  722. # reset al table
  723. self.ui.al_probe_points_table.setRowCount(0)
  724. # reset the al dict
  725. self.al_geometry_dict.clear()
  726. # build AL table
  727. self.build_al_table()
  728. if val == "manual":
  729. self.ui.al_rows_entry.setDisabled(True)
  730. self.ui.al_rows_label.setDisabled(True)
  731. self.ui.al_columns_entry.setDisabled(True)
  732. self.ui.al_columns_label.setDisabled(True)
  733. else:
  734. self.ui.al_rows_entry.setDisabled(False)
  735. self.ui.al_rows_label.setDisabled(False)
  736. self.ui.al_columns_entry.setDisabled(False)
  737. self.ui.al_columns_label.setDisabled(False)
  738. def on_controller_change(self):
  739. if self.ui.al_controller_combo.get_value() == 'GRBL':
  740. self.ui.h_gcode_button.hide()
  741. self.ui.view_h_gcode_button.hide()
  742. self.ui.import_heights_button.hide()
  743. self.ui.grbl_frame.show()
  744. self.on_search_ports(muted=True)
  745. else:
  746. self.ui.h_gcode_button.show()
  747. self.ui.view_h_gcode_button.show()
  748. self.ui.import_heights_button.show()
  749. self.ui.grbl_frame.hide()
  750. def list_serial_ports(self):
  751. """
  752. Lists serial port names.
  753. From here: https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
  754. :raises EnvironmentError: On unsupported or unknown platforms
  755. :returns: A list of the serial ports available on the system
  756. """
  757. if sys.platform.startswith('win'):
  758. ports = ['COM%s' % (i + 1) for i in range(256)]
  759. elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
  760. # this excludes your current terminal "/dev/tty"
  761. ports = glob.glob('/dev/tty[A-Za-z]*')
  762. elif sys.platform.startswith('darwin'):
  763. ports = glob.glob('/dev/tty.*')
  764. else:
  765. raise EnvironmentError('Unsupported platform')
  766. result = []
  767. s = serial.Serial()
  768. for port in ports:
  769. s.port = port
  770. try:
  771. s.open()
  772. s.close()
  773. result.append(port)
  774. except (OSError, serial.SerialException):
  775. # result.append(port + " (in use)")
  776. pass
  777. return result
  778. def on_search_ports(self, muted=None):
  779. port_list = self.list_serial_ports()
  780. self.ui.com_list_combo.clear()
  781. self.ui.com_list_combo.addItems(port_list)
  782. if muted is not True:
  783. self.app.inform.emit('[WARNING_NOTCL] %s' % _("COM list updated ..."))
  784. def on_connect_grbl(self):
  785. port_name = self.ui.com_list_combo.currentText()
  786. if " (" in port_name:
  787. port_name = port_name.rpartition(" (")[0]
  788. baudrate = int(self.ui.baudrates_list_combo.currentText())
  789. try:
  790. self.grbl_ser_port = serial.serial_for_url(port_name, baudrate,
  791. bytesize=serial.EIGHTBITS,
  792. parity=serial.PARITY_NONE,
  793. stopbits=serial.STOPBITS_ONE,
  794. timeout=0.1,
  795. xonxoff=False,
  796. rtscts=False)
  797. # Toggle DTR to reset the controller loaded with GRBL (Arduino, ESP32, etc)
  798. try:
  799. self.grbl_ser_port.dtr = False
  800. except IOError:
  801. pass
  802. self.grbl_ser_port.reset_input_buffer()
  803. try:
  804. self.grbl_ser_port.dtr = True
  805. except IOError:
  806. pass
  807. answer = self.wake_grbl()
  808. answer = ['ok'] # hack for development without a GRBL controller connected
  809. for line in answer:
  810. if 'ok' in line.lower():
  811. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: seagreen;}")
  812. self.ui.com_connect_button.setText(_("Connected"))
  813. self.ui.controller_reset_button.setDisabled(False)
  814. for idx in range(self.ui.al_toolbar.count()):
  815. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  816. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('seagreen'))
  817. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  818. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  819. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  820. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  821. self.app.inform.emit("%s: %s" % (_("Port connected"), port_name))
  822. return
  823. self.grbl_ser_port.close()
  824. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to GRBL on port"), port_name))
  825. except serial.SerialException:
  826. self.grbl_ser_port = serial.Serial()
  827. self.grbl_ser_port.port = port_name
  828. self.grbl_ser_port.close()
  829. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: red;}")
  830. self.ui.com_connect_button.setText(_("Disconnected"))
  831. self.ui.controller_reset_button.setDisabled(True)
  832. for idx in range(self.ui.al_toolbar.count()):
  833. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  834. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  835. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  836. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  837. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  838. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  839. self.app.inform.emit("%s: %s" % (_("Port is connected. Disconnecting"), port_name))
  840. except Exception:
  841. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to port"), port_name))
  842. def on_add_baudrate_grbl(self):
  843. new_bd = str(self.ui.new_baudrate_entry.get_value())
  844. if int(new_bd) >= 40 and new_bd not in self.ui.baudrates_list_combo.model().stringList():
  845. self.ui.baudrates_list_combo.addItem(new_bd)
  846. self.ui.baudrates_list_combo.setCurrentText(new_bd)
  847. def on_delete_baudrate_grbl(self):
  848. current_idx = self.ui.baudrates_list_combo.currentIndex()
  849. self.ui.baudrates_list_combo.removeItem(current_idx)
  850. def wake_grbl(self):
  851. # Wake up grbl
  852. self.grbl_ser_port.write("\r\n\r\n".encode('utf-8'))
  853. # Wait for GRBL controller to initialize
  854. time.sleep(1)
  855. grbl_out = deepcopy(self.grbl_ser_port.readlines())
  856. self.grbl_ser_port.reset_input_buffer()
  857. return grbl_out
  858. def on_send_grbl_command(self):
  859. cmd = self.ui.grbl_command_entry.get_value()
  860. # show the Shell Dock
  861. self.app.ui.shell_dock.show()
  862. def worker_task():
  863. with self.app.proc_container.new(_("Sending GCode...")):
  864. self.send_grbl_command(command=cmd)
  865. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  866. def send_grbl_command(self, command, echo=True):
  867. stripped_cmd = command.strip()
  868. cmd = stripped_cmd.rpartition('\n')[0]
  869. if echo:
  870. self.app.inform_shell[str, bool].emit(cmd, False)
  871. # Send Gcode command to GRBL
  872. snd = cmd + '\n'
  873. self.grbl_ser_port.write(snd.encode('utf-8'))
  874. grbl_out = self.grbl_ser_port.readlines()
  875. result = False
  876. for line in grbl_out:
  877. if echo:
  878. try:
  879. self.app.inform_shell.emit(' : ' + line.decode('utf-8').strip().upper())
  880. except Exception as e:
  881. log.debug("CNCJobObject.send_grbl_command() --> %s" % str(e))
  882. if 'ok' in line:
  883. result = True
  884. return result
  885. def send_grbl_block(self, command, echo=True):
  886. stripped_cmd = command.strip()
  887. for l in stripped_cmd.split('\n'):
  888. if echo:
  889. self.app.inform_shell[str, bool].emit(l, False)
  890. # Send Gcode block to GRBL
  891. snd = l + '\n'
  892. self.grbl_ser_port.write(snd.encode('utf-8'))
  893. grbl_out = self.grbl_ser_port.readlines()
  894. for line in grbl_out:
  895. if echo:
  896. try:
  897. self.app.inform_shell.emit(' : ' + line.decode('utf-8').strip().upper())
  898. except Exception as e:
  899. log.debug("CNCJobObject.send_grbl_block() --> %s" % str(e))
  900. def get_grbl_parameter(self, param):
  901. if '$' in param:
  902. param = param.replace('$','')
  903. snd = '$$\n'
  904. self.grbl_ser_port.write(snd.encode('utf-8'))
  905. grbl_out = self.grbl_ser_port.readlines()
  906. for line in grbl_out:
  907. decoded_line = line.decode('utf-8')
  908. par = '$%s' % str(param)
  909. if par in decoded_line:
  910. result = float(decoded_line.rpartition('=')[2])
  911. self.app.shell_message("GRBL Parameter: %s = %s" % (str(param), str(result)), show=True)
  912. return result
  913. def on_jog(self, direction=None, step=5.0):
  914. if direction is None:
  915. return
  916. cmd = ''
  917. if direction == 'xplus':
  918. cmd = "$J=G91 %s X%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  919. if direction == 'xminus':
  920. cmd = "$J=G91 %s X-%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  921. if direction == 'yplus':
  922. cmd = "$J=G91 %s Y%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  923. if direction == 'yminus':
  924. cmd = "$J=G91 %s Y-%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  925. if direction == 'zplus':
  926. cmd = "$J=G91 %s Z%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  927. if direction == 'zminus':
  928. cmd = "$J=G91 %s Z-%s F1000" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step))
  929. self.send_grbl_command(command=cmd, echo=False)
  930. def on_grbl_reset(self):
  931. cmd = '\x18'
  932. self.wake_grbl()
  933. self.send_grbl_command(command=cmd)
  934. self.app.inform.emit("%s" % _("GRBL software reset was sent."))
  935. def probing_gcode(self, coords, pr_travel, probe_fr, pr_depth, controller):
  936. """
  937. :param coords: a list of (x, y) tuples of probe points coordinates
  938. :type coords: list
  939. :param pr_travel: the height (z) where the probe travel between probe points
  940. :type pr_travel: float
  941. :param probe_fr: feedrate when probing
  942. :type probe_fr: float
  943. :param pr_depth: how much to lower the probe searching for contact
  944. :type pr_depth: float
  945. :param controller: a string with the name of the GCode sender for which to create the probing GCode.
  946. Can be: 'MACH3', 'MACH4', 'LinuxCNC', 'GRBL'
  947. :type controller: str
  948. :return: Probing GCode
  949. :rtype: str
  950. """
  951. p_gcode = ''
  952. header = ''
  953. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  954. header += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  955. (str(self.app.version), str(self.app.version_date)) + '\n'
  956. header += '(This is a autolevelling probing GCode.)\n' \
  957. '(Make sure that before you start the job you first do a zero for all axis.)\n\n'
  958. header += '(Name: ' + str(self.options['name']) + ')\n'
  959. header += '(Type: ' + "Autolevelling Probing GCode " + ')\n'
  960. header += '(Units: ' + self.units.upper() + ')\n'
  961. header += '(Created on ' + time_str + ')\n'
  962. # commands
  963. if controller == 'MACH3':
  964. probing_command = 'G31'
  965. probing_var = '#2002'
  966. openfile_command = 'M40'
  967. closefile_command = 'M41'
  968. elif controller == 'MACH4':
  969. probing_command = 'G31'
  970. probing_var = '#5063'
  971. openfile_command = 'M40'
  972. closefile_command = 'M41'
  973. elif controller == 'LinuxCNC':
  974. probing_command = 'G38.2'
  975. probing_var = '#5422'
  976. openfile_command = '(PROBEOPEN a_probing_points_file.txt)'
  977. closefile_command = '(PROBECLOSE)'
  978. else:
  979. log.debug("CNCJobObject.probing_gcode() -> controller not supported")
  980. return
  981. # #############################################################################################################
  982. # ########################### GCODE construction ##############################################################
  983. # #############################################################################################################
  984. # header
  985. p_gcode += header + '\n'
  986. # supplementary message for LinuxCNC
  987. if controller == 'LinuxCNC':
  988. probing_var += "The file with the stored probing points can be found\n" \
  989. "in the configuration folder for LinuxCNC.\n" \
  990. "The name of the file is: a_probing_points_file.txt.\n"
  991. # units
  992. p_gcode += 'G21\n' if self.units == 'MM' else 'G20\n'
  993. # reference mode = absolute
  994. p_gcode += 'G90\n'
  995. # open a new file
  996. p_gcode += openfile_command + '\n'
  997. # move to safe height (probe travel Z)
  998. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  999. # probing points
  1000. for idx, xy_tuple in enumerate(coords, 1): # index starts from 1
  1001. x = xy_tuple[0]
  1002. y = xy_tuple[1]
  1003. # move to probing point
  1004. p_gcode += "G0 X%sY%s\n" % (
  1005. str(self.app.dec_format(x, self.coords_decimals)),
  1006. str(self.app.dec_format(y, self.coords_decimals))
  1007. )
  1008. # do the probing
  1009. p_gcode += "%s Z%s F%s\n" % (
  1010. probing_command,
  1011. str(self.app.dec_format(pr_depth, self.coords_decimals)),
  1012. str(self.app.dec_format(probe_fr, self.fr_decimals)),
  1013. )
  1014. # store in a global numeric variable the value of the detected probe Z
  1015. # I offset the global numeric variable by 500 so it does not conflict with something else
  1016. temp_var = int(idx + 500)
  1017. p_gcode += "#%d = %s\n" % (temp_var, probing_var)
  1018. # move to safe height (probe travel Z)
  1019. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1020. # close the file
  1021. p_gcode += closefile_command + '\n'
  1022. # finish the GCode
  1023. p_gcode += 'M2'
  1024. return p_gcode
  1025. def on_generate_probing_gcode(self):
  1026. coords = []
  1027. for id_key, value in self.al_geometry_dict.items():
  1028. x = value['point'].x
  1029. y = value['point'].y
  1030. coords.append(
  1031. (
  1032. self.app.dec_format(x, dec=self.app.decimals),
  1033. self.app.dec_format(y, dec=self.app.decimals)
  1034. )
  1035. )
  1036. pr_travel = self.ui.ptravelz_entry.get_value()
  1037. probe_fr = self.ui.feedrate_probe_entry.get_value()
  1038. pr_depth = self.ui.pdepth_entry.get_value()
  1039. controller = self.ui.al_controller_combo.get_value()
  1040. self.probing_gcode_text = self.probing_gcode(coords, pr_travel, probe_fr, pr_depth, controller)
  1041. def on_view_probing_gcode(self):
  1042. self.app.proc_container.view.set_busy(_("Loading..."))
  1043. gco = self.probing_gcode_text
  1044. if gco is None or gco == '':
  1045. self.app.inform.emit('[WARNING_NOTCL] %s...' % _('There is nothing to view'))
  1046. return
  1047. self.gcode_viewer_tab = AppTextEditor(app=self.app, plain_text=True)
  1048. # add the tab if it was closed
  1049. self.app.ui.plot_tab_area.addTab(self.gcode_viewer_tab, '%s' % _("Code Viewer"))
  1050. self.gcode_viewer_tab.setObjectName('code_viewer_tab')
  1051. # delete the absolute and relative position and messages in the infobar
  1052. self.app.ui.position_label.setText("")
  1053. self.app.ui.rel_position_label.setText("")
  1054. self.gcode_viewer_tab.code_editor.completer_enable = False
  1055. self.gcode_viewer_tab.buttonRun.hide()
  1056. # Switch plot_area to CNCJob tab
  1057. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_viewer_tab)
  1058. self.gcode_viewer_tab.t_frame.hide()
  1059. # then append the text from GCode to the text editor
  1060. try:
  1061. self.gcode_viewer_tab.load_text(gco, move_to_start=True, clear_text=True)
  1062. except Exception as e:
  1063. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1064. return
  1065. self.gcode_viewer_tab.t_frame.show()
  1066. self.app.proc_container.view.set_idle()
  1067. self.gcode_viewer_tab.buttonSave.hide()
  1068. self.gcode_viewer_tab.buttonOpen.hide()
  1069. self.gcode_viewer_tab.buttonPrint.hide()
  1070. self.gcode_viewer_tab.buttonPreview.hide()
  1071. self.gcode_viewer_tab.buttonReplace.hide()
  1072. self.gcode_viewer_tab.sel_all_cb.hide()
  1073. self.gcode_viewer_tab.entryReplace.hide()
  1074. self.gcode_viewer_tab.code_editor.setReadOnly(True)
  1075. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Viewer'))
  1076. def on_import_height_map(self):
  1077. """
  1078. Import the height map file into the app
  1079. :return:
  1080. :rtype:
  1081. """
  1082. _filter_ = "Text File .txt (*.txt);;All Files (*.*)"
  1083. try:
  1084. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1085. directory=self.app.get_last_folder(),
  1086. filter=_filter_)
  1087. except TypeError:
  1088. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1089. filter=_filter_)
  1090. filename = str(filename)
  1091. if filename == '':
  1092. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1093. else:
  1094. self.app.worker_task.emit({'fcn': self.import_height_map, 'params': [filename]})
  1095. def import_height_map(self, filename):
  1096. """
  1097. :param filename:
  1098. :type filename:
  1099. :return:
  1100. :rtype:
  1101. """
  1102. stream = ''
  1103. try:
  1104. if filename:
  1105. with open(filename, 'r') as f:
  1106. stream = f.readlines()
  1107. else:
  1108. return
  1109. except IOError:
  1110. log.error("Failed to open height map file: %s" % filename)
  1111. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open height map file"), filename))
  1112. return
  1113. idx = 0
  1114. for line in stream:
  1115. if line != '':
  1116. idx += 1
  1117. line = line.replace(' ', ',').replace('\n', '').split(',')
  1118. if idx not in self.al_geometry_dict:
  1119. self.al_geometry_dict[idx] = {}
  1120. self.al_geometry_dict[idx]['height'] = float(line[2])
  1121. if 'point' not in self.al_geometry_dict[idx]:
  1122. x = float(line[0])
  1123. y = float(line[1])
  1124. self.al_geometry_dict[idx]['point'] = Point((x, y))
  1125. self.build_al_table_sig.emit()
  1126. def on_updateplot_button_click(self, *args):
  1127. """
  1128. Callback for the "Updata Plot" button. Reads the form for updates
  1129. and plots the object.
  1130. """
  1131. self.read_form()
  1132. self.on_plot_kind_change()
  1133. def on_plot_kind_change(self):
  1134. kind = self.ui.cncplot_method_combo.get_value()
  1135. def worker_task():
  1136. with self.app.proc_container.new(_("Plotting...")):
  1137. self.plot(kind=kind)
  1138. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  1139. def on_exportgcode_button_click(self):
  1140. """
  1141. Handler activated by a button clicked when exporting GCode.
  1142. :param args:
  1143. :return:
  1144. """
  1145. self.app.defaults.report_usage("cncjob_on_exportgcode_button")
  1146. self.read_form()
  1147. name = self.app.collection.get_active().options['name']
  1148. save_gcode = False
  1149. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  1150. _filter_ = "RML1 Files .rol (*.rol);;All Files (*.*)"
  1151. elif 'hpgl' in self.pp_geometry_name:
  1152. _filter_ = "HPGL Files .plt (*.plt);;All Files (*.*)"
  1153. else:
  1154. save_gcode = True
  1155. _filter_ = self.app.defaults['cncjob_save_filters']
  1156. try:
  1157. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1158. filename, _f = FCFileSaveDialog.get_saved_filename(
  1159. caption=_("Export Code ..."),
  1160. directory=dir_file_to_save,
  1161. ext_filter=_filter_
  1162. )
  1163. except TypeError:
  1164. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1165. self.export_gcode_handler(filename, is_gcode=save_gcode)
  1166. def export_gcode_handler(self, filename, is_gcode=True):
  1167. preamble = ''
  1168. postamble = ''
  1169. filename = str(filename)
  1170. if filename == '':
  1171. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1172. return
  1173. else:
  1174. if is_gcode is True:
  1175. used_extension = filename.rpartition('.')[2]
  1176. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  1177. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  1178. self.ui.name_entry.set_value(new_name)
  1179. self.on_name_activate(silent=True)
  1180. try:
  1181. if self.ui.snippets_cb.get_value():
  1182. preamble = self.append_snippet
  1183. postamble = self.prepend_snippet
  1184. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  1185. except Exception as err:
  1186. log.debug("CNCJobObject.export_gcode_handler() --> %s" % str(err))
  1187. gc = self.export_gcode(filename)
  1188. if gc == 'fail':
  1189. return
  1190. if self.app.defaults["global_open_style"] is False:
  1191. self.app.file_opened.emit("gcode", filename)
  1192. self.app.file_saved.emit("gcode", filename)
  1193. self.app.inform.emit('[success] %s: %s' % (_("File saved to"), filename))
  1194. def on_edit_code_click(self, *args):
  1195. """
  1196. Handler activated by a button clicked when reviewing GCode.
  1197. :param args:
  1198. :return:
  1199. """
  1200. self.app.proc_container.view.set_busy(_("Loading..."))
  1201. preamble = self.append_snippet
  1202. postamble = self.prepend_snippet
  1203. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  1204. if gco == 'fail':
  1205. return
  1206. else:
  1207. self.app.gcode_edited = gco
  1208. self.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  1209. # add the tab if it was closed
  1210. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Review"))
  1211. self.gcode_editor_tab.setObjectName('code_editor_tab')
  1212. # delete the absolute and relative position and messages in the infobar
  1213. self.app.ui.position_label.setText("")
  1214. self.app.ui.rel_position_label.setText("")
  1215. self.gcode_editor_tab.code_editor.completer_enable = False
  1216. self.gcode_editor_tab.buttonRun.hide()
  1217. # Switch plot_area to CNCJob tab
  1218. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  1219. self.gcode_editor_tab.t_frame.hide()
  1220. # then append the text from GCode to the text editor
  1221. try:
  1222. self.gcode_editor_tab.load_text(self.app.gcode_edited.getvalue(), move_to_start=True, clear_text=True)
  1223. except Exception as e:
  1224. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1225. return
  1226. self.gcode_editor_tab.t_frame.show()
  1227. self.app.proc_container.view.set_idle()
  1228. self.gcode_editor_tab.buttonSave.hide()
  1229. self.gcode_editor_tab.buttonOpen.hide()
  1230. self.gcode_editor_tab.buttonPrint.hide()
  1231. self.gcode_editor_tab.buttonPreview.hide()
  1232. self.gcode_editor_tab.buttonReplace.hide()
  1233. self.gcode_editor_tab.sel_all_cb.hide()
  1234. self.gcode_editor_tab.entryReplace.hide()
  1235. self.gcode_editor_tab.code_editor.setReadOnly(True)
  1236. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  1237. def on_update_source_file(self):
  1238. self.source_file = self.gcode_editor_tab.code_editor.toPlainText()
  1239. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  1240. """
  1241. Will create a header to be added to all GCode files generated by FlatCAM
  1242. :param comment_start_symbol: A symbol to be used as the first symbol in a comment
  1243. :param comment_stop_symbol: A symbol to be used as the last symbol in a comment
  1244. :return: A string with a GCode header
  1245. """
  1246. log.debug("FlatCAMCNCJob.gcode_header()")
  1247. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1248. marlin = False
  1249. hpgl = False
  1250. probe_pp = False
  1251. gcode = ''
  1252. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  1253. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  1254. try:
  1255. for key in self.cnc_tools:
  1256. ppg = self.cnc_tools[key]['data']['ppname_g']
  1257. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  1258. marlin = True
  1259. break
  1260. if ppg == 'hpgl':
  1261. hpgl = True
  1262. break
  1263. if "toolchange_probe" in ppg.lower():
  1264. probe_pp = True
  1265. break
  1266. except KeyError:
  1267. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  1268. pass
  1269. try:
  1270. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  1271. marlin = True
  1272. except KeyError:
  1273. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1274. pass
  1275. try:
  1276. if "toolchange_probe" in self.options['ppname_e'].lower():
  1277. probe_pp = True
  1278. except KeyError:
  1279. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1280. pass
  1281. if marlin is True:
  1282. gcode += ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  1283. (str(self.app.version), str(self.app.version_date)) + '\n'
  1284. gcode += ';Name: ' + str(self.options['name']) + '\n'
  1285. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  1286. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1287. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1288. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  1289. gcode += ';Created on ' + time_str + '\n' + '\n'
  1290. elif hpgl is True:
  1291. gcode += 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  1292. (str(self.app.version), str(self.app.version_date)) + '";\n'
  1293. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  1294. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  1295. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1296. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1297. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  1298. gcode += 'CO "Created on ' + time_str + '";\n'
  1299. elif probe_pp is True:
  1300. gcode += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1301. (str(self.app.version), str(self.app.version_date)) + '\n'
  1302. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  1303. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  1304. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  1305. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  1306. 'Then zero the Z axis.)\n' + '\n'
  1307. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  1308. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  1309. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1310. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1311. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1312. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1313. else:
  1314. gcode += '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  1315. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  1316. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  1317. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  1318. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1319. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1320. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  1321. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  1322. return gcode
  1323. @staticmethod
  1324. def gcode_footer(end_command=None):
  1325. """
  1326. Will add the M02 to the end of GCode, if requested.
  1327. :param end_command: 'M02' or 'M30' - String
  1328. :return:
  1329. """
  1330. if end_command:
  1331. return end_command
  1332. else:
  1333. return 'M02'
  1334. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False, from_tcl=False):
  1335. """
  1336. This will save the GCode from the Gcode object to a file on the OS filesystem
  1337. :param filename: filename for the GCode file
  1338. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  1339. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  1340. :param to_file: if False then no actual file is saved but the app will know that a file was created
  1341. :param from_tcl: True if run from Tcl Shell
  1342. :return: None
  1343. """
  1344. # gcode = ''
  1345. # roland = False
  1346. # hpgl = False
  1347. # isel_icp = False
  1348. include_header = True
  1349. if preamble == '':
  1350. preamble = self.app.defaults["cncjob_prepend"]
  1351. if postamble == '':
  1352. preamble = self.app.defaults["cncjob_append"]
  1353. try:
  1354. if self.special_group:
  1355. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  1356. (_("This CNCJob object can't be processed because it is a"),
  1357. str(self.special_group),
  1358. _("CNCJob object")))
  1359. return 'fail'
  1360. except AttributeError:
  1361. pass
  1362. # if this dict is not empty then the object is a Geometry object
  1363. if self.cnc_tools:
  1364. first_key = next(iter(self.cnc_tools))
  1365. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  1366. # if this dict is not empty then the object is an Excellon object
  1367. if self.exc_cnc_tools:
  1368. first_key = next(iter(self.exc_cnc_tools))
  1369. include_header = self.app.preprocessors[
  1370. self.exc_cnc_tools[first_key]['data']['tools_drill_ppname_e']
  1371. ].include_header
  1372. gcode = ''
  1373. if include_header is False:
  1374. g = preamble
  1375. # detect if using multi-tool and make the Gcode summation correctly for each case
  1376. if self.multitool is True:
  1377. for tooluid_key in self.cnc_tools:
  1378. for key, value in self.cnc_tools[tooluid_key].items():
  1379. if key == 'gcode':
  1380. gcode += value
  1381. break
  1382. else:
  1383. gcode += self.gcode
  1384. g = g + gcode + postamble
  1385. else:
  1386. # search for the GCode beginning which is usually a G20 or G21
  1387. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  1388. # g_idx = gcode.rfind('G20')
  1389. #
  1390. # # if it did not find 'G20' then search for 'G21'
  1391. # if g_idx == -1:
  1392. # g_idx = gcode.rfind('G21')
  1393. #
  1394. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  1395. # if g_idx == -1:
  1396. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  1397. # return
  1398. # detect if using multi-tool and make the Gcode summation correctly for each case
  1399. if self.multitool is True:
  1400. if self.origin_kind == 'excellon':
  1401. for tooluid_key in self.exc_cnc_tools:
  1402. for key, value in self.exc_cnc_tools[tooluid_key].items():
  1403. if key == 'gcode' and value:
  1404. gcode += value
  1405. break
  1406. else:
  1407. for tooluid_key in self.cnc_tools:
  1408. for key, value in self.cnc_tools[tooluid_key].items():
  1409. if key == 'gcode' and value:
  1410. gcode += value
  1411. break
  1412. else:
  1413. gcode += self.gcode
  1414. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  1415. # detect if using a HPGL preprocessor
  1416. hpgl = False
  1417. if self.cnc_tools:
  1418. for key in self.cnc_tools:
  1419. if 'ppname_g' in self.cnc_tools[key]['data']:
  1420. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  1421. hpgl = True
  1422. break
  1423. elif self.exc_cnc_tools:
  1424. for key in self.cnc_tools:
  1425. if 'ppname_e' in self.cnc_tools[key]['data']:
  1426. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  1427. hpgl = True
  1428. break
  1429. if hpgl:
  1430. processed_gcode = ''
  1431. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  1432. for gline in gcode.splitlines():
  1433. match = pa_re.search(gline)
  1434. if match:
  1435. x_int = int(float(match.group(1)))
  1436. y_int = int(float(match.group(2)))
  1437. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  1438. processed_gcode += new_line
  1439. else:
  1440. processed_gcode += gline + '\n'
  1441. gcode = processed_gcode
  1442. g = self.gc_header + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  1443. else:
  1444. try:
  1445. g_idx = gcode.index('G94')
  1446. if preamble != '' and postamble != '':
  1447. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1448. gcode[(g_idx + 3):] + postamble + end_gcode
  1449. elif preamble == '':
  1450. g = self.gc_header + gcode[:g_idx + 3] + '\n' + \
  1451. gcode[(g_idx + 3):] + postamble + end_gcode
  1452. elif postamble == '':
  1453. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1454. gcode[(g_idx + 3):] + end_gcode
  1455. else:
  1456. g = self.gc_header + gcode[:g_idx + 3] + gcode[(g_idx + 3):] + end_gcode
  1457. except ValueError:
  1458. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1459. _("G-code does not have a G94 code.\n"
  1460. "Append Code snippet will not be used.."))
  1461. g = self.gc_header + '\n' + gcode + postamble + end_gcode
  1462. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  1463. # if self.ui.toolchange_cb.get_value() is True:
  1464. # # match = self.re_toolchange.search(g)
  1465. # if 'M6' in g:
  1466. # m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  1467. # if m6_code is None or m6_code == '':
  1468. # self.app.inform.emit(
  1469. # '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  1470. # )
  1471. # return 'fail'
  1472. #
  1473. # g = g.replace('M6', m6_code)
  1474. # self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  1475. lines = StringIO(g)
  1476. # Write
  1477. if filename is not None:
  1478. try:
  1479. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1480. if force_windows_line_endings and sys.platform != 'win32':
  1481. with open(filename, 'w', newline='\r\n') as f:
  1482. for line in lines:
  1483. f.write(line)
  1484. else:
  1485. with open(filename, 'w') as f:
  1486. for line in lines:
  1487. f.write(line)
  1488. except FileNotFoundError:
  1489. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1490. return
  1491. except PermissionError:
  1492. self.app.inform.emit(
  1493. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1494. "Most likely another app is holding the file open and not accessible.")
  1495. )
  1496. return 'fail'
  1497. elif to_file is False:
  1498. # Just for adding it to the recent files list.
  1499. if self.app.defaults["global_open_style"] is False:
  1500. self.app.file_opened.emit("cncjob", filename)
  1501. self.app.file_saved.emit("cncjob", filename)
  1502. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  1503. else:
  1504. return lines
  1505. # def on_toolchange_custom_clicked(self, signal):
  1506. # """
  1507. # Handler for clicking toolchange custom.
  1508. #
  1509. # :param signal:
  1510. # :return:
  1511. # """
  1512. #
  1513. # try:
  1514. # if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  1515. # if self.ui.toolchange_cb.get_value():
  1516. # self.ui.toolchange_cb.set_value(False)
  1517. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1518. # _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  1519. # except KeyError:
  1520. # try:
  1521. # for key in self.cnc_tools:
  1522. # ppg = self.cnc_tools[key]['data']['ppname_g']
  1523. # if 'toolchange_custom' not in str(ppg).lower():
  1524. # if self.ui.toolchange_cb.get_value():
  1525. # self.ui.toolchange_cb.set_value(False)
  1526. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1527. # _("The used preprocessor file has to have in it's name: "
  1528. # "'toolchange_custom'"))
  1529. # except KeyError:
  1530. # self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  1531. def get_gcode(self, preamble='', postamble=''):
  1532. """
  1533. We need this to be able to get_gcode separately for shell command export_gcode
  1534. :param preamble: Extra GCode added to the beginning of the GCode
  1535. :param postamble: Extra GCode added at the end of the GCode
  1536. :return: The modified GCode
  1537. """
  1538. return preamble + '\n' + self.gcode + "\n" + postamble
  1539. def get_svg(self):
  1540. # we need this to be able get_svg separately for shell command export_svg
  1541. pass
  1542. def on_plot_cb_click(self, *args):
  1543. """
  1544. Handler for clicking on the Plot checkbox.
  1545. :param args:
  1546. :return:
  1547. """
  1548. if self.muted_ui:
  1549. return
  1550. kind = self.ui.cncplot_method_combo.get_value()
  1551. self.plot(kind=kind)
  1552. self.read_form_item('plot')
  1553. self.ui_disconnect()
  1554. cb_flag = self.ui.plot_cb.isChecked()
  1555. for row in range(self.ui.cnc_tools_table.rowCount()):
  1556. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  1557. if cb_flag:
  1558. table_cb.setChecked(True)
  1559. else:
  1560. table_cb.setChecked(False)
  1561. self.ui_connect()
  1562. def on_plot_cb_click_table(self):
  1563. """
  1564. Handler for clicking the plot checkboxes added into a Table on each row. Purpose: toggle visibility for the
  1565. tool/aperture found on that row.
  1566. :return:
  1567. """
  1568. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1569. self.ui_disconnect()
  1570. # cw = self.sender()
  1571. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  1572. # cw_row = cw_index.row()
  1573. kind = self.ui.cncplot_method_combo.get_value()
  1574. self.shapes.clear(update=True)
  1575. if self.origin_kind == "excellon":
  1576. for r in range(self.ui.exc_cnc_tools_table.rowCount()):
  1577. row_dia = float('%.*f' % (self.decimals, float(self.ui.exc_cnc_tools_table.item(r, 1).text())))
  1578. for tooluid_key in self.exc_cnc_tools:
  1579. tooldia = float('%.*f' % (self.decimals, float(tooluid_key)))
  1580. if row_dia == tooldia:
  1581. gcode_parsed = self.exc_cnc_tools[tooluid_key]['gcode_parsed']
  1582. if self.ui.exc_cnc_tools_table.cellWidget(r, 6).isChecked():
  1583. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1584. else:
  1585. for tooluid_key in self.cnc_tools:
  1586. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1587. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1588. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  1589. for r in range(self.ui.cnc_tools_table.rowCount()):
  1590. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  1591. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  1592. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1593. self.shapes.redraw()
  1594. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1595. # if all the row plot's are enabled also enable the general plot checkbox
  1596. cb_cnt = 0
  1597. total_row = self.ui.cnc_tools_table.rowCount()
  1598. for row in range(total_row):
  1599. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  1600. cb_cnt += 1
  1601. else:
  1602. cb_cnt -= 1
  1603. if cb_cnt < total_row:
  1604. self.ui.plot_cb.setChecked(False)
  1605. else:
  1606. self.ui.plot_cb.setChecked(True)
  1607. self.ui_connect()
  1608. def plot(self, visible=None, kind='all'):
  1609. """
  1610. # Does all the required setup and returns False
  1611. # if the 'ptint' option is set to False.
  1612. :param visible: Boolean to decide if the object will be plotted as visible or disabled on canvas
  1613. :param kind: String. Can be "all" or "travel" or "cut". For CNCJob plotting
  1614. :return: None
  1615. """
  1616. if not FlatCAMObj.plot(self):
  1617. return
  1618. visible = visible if visible else self.options['plot']
  1619. if self.app.is_legacy is False:
  1620. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  1621. self.text_col.enabled = True
  1622. else:
  1623. self.text_col.enabled = False
  1624. self.annotation.redraw()
  1625. try:
  1626. if self.multitool is False: # single tool usage
  1627. try:
  1628. dia_plot = float(self.options["tooldia"])
  1629. except ValueError:
  1630. # we may have a tuple with only one element and a comma
  1631. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  1632. self.plot2(tooldia=dia_plot, obj=self, visible=visible, kind=kind)
  1633. else:
  1634. # I do this so the travel lines thickness will reflect the tool diameter
  1635. # may work only for objects created within the app and not Gcode imported from elsewhere for which we
  1636. # don't know the origin
  1637. if self.origin_kind == "excellon":
  1638. if self.exc_cnc_tools:
  1639. for tooldia_key in self.exc_cnc_tools:
  1640. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  1641. gcode_parsed = self.exc_cnc_tools[tooldia_key]['gcode_parsed']
  1642. if not gcode_parsed:
  1643. continue
  1644. # gcode_parsed = self.gcode_parsed
  1645. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1646. else:
  1647. # multiple tools usage
  1648. if self.cnc_tools:
  1649. for tooluid_key in self.cnc_tools:
  1650. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1651. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1652. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1653. self.shapes.redraw()
  1654. except (ObjectDeleted, AttributeError):
  1655. self.shapes.clear(update=True)
  1656. if self.app.is_legacy is False:
  1657. self.annotation.clear(update=True)
  1658. def on_annotation_change(self):
  1659. """
  1660. Handler for toggling the annotation display by clicking a checkbox.
  1661. :return:
  1662. """
  1663. if self.app.is_legacy is False:
  1664. if self.ui.annotation_cb.get_value():
  1665. self.text_col.enabled = True
  1666. else:
  1667. self.text_col.enabled = False
  1668. # kind = self.ui.cncplot_method_combo.get_value()
  1669. # self.plot(kind=kind)
  1670. self.annotation.redraw()
  1671. else:
  1672. kind = self.ui.cncplot_method_combo.get_value()
  1673. self.plot(kind=kind)
  1674. def convert_units(self, units):
  1675. """
  1676. Units conversion used by the CNCJob objects.
  1677. :param units: Can be "MM" or "IN"
  1678. :return:
  1679. """
  1680. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  1681. factor = CNCjob.convert_units(self, units)
  1682. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  1683. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  1684. 'endz', 'toolchangez']
  1685. temp_tools_dict = {}
  1686. tool_dia_copy = {}
  1687. data_copy = {}
  1688. for tooluid_key, tooluid_value in self.cnc_tools.items():
  1689. for dia_key, dia_value in tooluid_value.items():
  1690. if dia_key == 'tooldia':
  1691. dia_value *= factor
  1692. dia_value = float('%.*f' % (self.decimals, dia_value))
  1693. tool_dia_copy[dia_key] = dia_value
  1694. if dia_key == 'offset':
  1695. tool_dia_copy[dia_key] = dia_value
  1696. if dia_key == 'offset_value':
  1697. dia_value *= factor
  1698. tool_dia_copy[dia_key] = dia_value
  1699. if dia_key == 'type':
  1700. tool_dia_copy[dia_key] = dia_value
  1701. if dia_key == 'tool_type':
  1702. tool_dia_copy[dia_key] = dia_value
  1703. if dia_key == 'data':
  1704. for data_key, data_value in dia_value.items():
  1705. # convert the form fields that are convertible
  1706. for param in param_list:
  1707. if data_key == param and data_value is not None:
  1708. data_copy[data_key] = data_value * factor
  1709. # copy the other dict entries that are not convertible
  1710. if data_key not in param_list:
  1711. data_copy[data_key] = data_value
  1712. tool_dia_copy[dia_key] = deepcopy(data_copy)
  1713. data_copy.clear()
  1714. if dia_key == 'gcode':
  1715. tool_dia_copy[dia_key] = dia_value
  1716. if dia_key == 'gcode_parsed':
  1717. tool_dia_copy[dia_key] = dia_value
  1718. if dia_key == 'solid_geometry':
  1719. tool_dia_copy[dia_key] = dia_value
  1720. # if dia_key == 'solid_geometry':
  1721. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  1722. # if dia_key == 'gcode_parsed':
  1723. # for g in dia_value:
  1724. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1725. #
  1726. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  1727. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  1728. temp_tools_dict.update({
  1729. tooluid_key: deepcopy(tool_dia_copy)
  1730. })
  1731. tool_dia_copy.clear()
  1732. self.cnc_tools.clear()
  1733. self.cnc_tools = deepcopy(temp_tools_dict)