FlatCAMCNCJob.py 104 KB

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