FlatCAMCNCJob.py 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482
  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.grbl_get_heightmap_button.setDisabled(False)
  375. self.ui.grbl_save_height_map_button.setDisabled(False)
  376. self.ui.h_gcode_button.setDisabled(False)
  377. self.ui.view_h_gcode_button.setDisabled(False)
  378. else:
  379. self.ui.grbl_get_heightmap_button.setDisabled(True)
  380. self.ui.grbl_save_height_map_button.setDisabled(True)
  381. self.ui.h_gcode_button.setDisabled(True)
  382. self.ui.view_h_gcode_button.setDisabled(True)
  383. def set_ui(self, ui):
  384. FlatCAMObj.set_ui(self, ui)
  385. log.debug("FlatCAMCNCJob.set_ui()")
  386. assert isinstance(self.ui, CNCObjectUI), \
  387. "Expected a CNCObjectUI, got %s" % type(self.ui)
  388. self.units = self.app.defaults['units'].upper()
  389. self.units_found = self.app.defaults['units']
  390. # this signal has to be connected to it's slot before the defaults are populated
  391. # the decision done in the slot has to override the default value set below
  392. # self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  393. self.form_fields.update({
  394. "plot": self.ui.plot_cb,
  395. "tooldia": self.ui.tooldia_entry,
  396. # "append": self.ui.append_text,
  397. # "prepend": self.ui.prepend_text,
  398. # "toolchange_macro": self.ui.toolchange_text,
  399. # "toolchange_macro_enable": self.ui.toolchange_cb,
  400. "al_travelz": self.ui.ptravelz_entry,
  401. "al_probe_depth": self.ui.pdepth_entry,
  402. "al_probe_fr": self.ui.feedrate_probe_entry,
  403. "al_controller": self.ui.al_controller_combo,
  404. "al_method": self.ui.al_method_radio,
  405. "al_mode": self.ui.al_mode_radio,
  406. "al_rows": self.ui.al_rows_entry,
  407. "al_columns": self.ui.al_columns_entry,
  408. "al_grbl_jog_step": self.ui.jog_step_entry,
  409. "al_grbl_jog_fr": self.ui.jog_fr_entry,
  410. })
  411. self.append_snippet = self.app.defaults['cncjob_append']
  412. self.prepend_snippet = self.app.defaults['cncjob_prepend']
  413. if self.append_snippet != '' or self.prepend_snippet:
  414. self.ui.snippets_cb.set_value(True)
  415. # Fill form fields only on object create
  416. self.to_form()
  417. # this means that the object that created this CNCJob was an Excellon or Geometry
  418. try:
  419. if self.travel_distance:
  420. self.ui.t_distance_label.show()
  421. self.ui.t_distance_entry.setVisible(True)
  422. self.ui.t_distance_entry.setDisabled(True)
  423. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  424. self.ui.units_label.setText(str(self.units).lower())
  425. self.ui.units_label.setDisabled(True)
  426. self.ui.t_time_label.show()
  427. self.ui.t_time_entry.setVisible(True)
  428. self.ui.t_time_entry.setDisabled(True)
  429. # if time is more than 1 then we have minutes, else we have seconds
  430. if self.routing_time > 1:
  431. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  432. self.ui.units_time_label.setText('min')
  433. else:
  434. time_r = self.routing_time * 60
  435. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  436. self.ui.units_time_label.setText('sec')
  437. self.ui.units_time_label.setDisabled(True)
  438. except AttributeError:
  439. pass
  440. if self.multitool is False:
  441. self.ui.tooldia_entry.show()
  442. self.ui.updateplot_button.show()
  443. else:
  444. self.ui.tooldia_entry.hide()
  445. self.ui.updateplot_button.hide()
  446. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  447. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  448. try:
  449. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  450. except (TypeError, AttributeError):
  451. pass
  452. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  453. # set if to display text annotations
  454. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  455. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  456. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  457. self.ui.review_gcode_button.clicked.connect(self.on_edit_code_click)
  458. self.ui.editor_button.clicked.connect(lambda: self.app.object2editor())
  459. # autolevelling signals
  460. self.ui.sal_cb.stateChanged.connect(self.on_autolevelling)
  461. self.ui.al_mode_radio.activated_custom.connect(self.on_mode_radio)
  462. self.ui.al_method_radio.activated_custom.connect(self.on_method_radio)
  463. self.ui.al_controller_combo.currentIndexChanged.connect(self.on_controller_change)
  464. self.ui.plot_probing_pts_cb.stateChanged.connect(self.show_voronoi_diagram)
  465. # GRBL
  466. self.ui.com_search_button.clicked.connect(self.on_grbl_search_ports)
  467. self.ui.add_bd_button.clicked.connect(self.on_grbl_add_baudrate)
  468. self.ui.del_bd_button.clicked.connect(self.on_grbl_delete_baudrate_grbl)
  469. self.ui.controller_reset_button.clicked.connect(self.on_grbl_reset)
  470. self.ui.com_connect_button.clicked.connect(self.on_grbl_connect)
  471. self.ui.grbl_send_button.clicked.connect(self.on_grbl_send_command)
  472. self.ui.grbl_command_entry.returnPressed.connect(self.on_grbl_send_command)
  473. # Jog
  474. self.ui.jog_wdg.jog_up_button.clicked.connect(lambda: self.on_grbl_jog(direction='yplus'))
  475. self.ui.jog_wdg.jog_down_button.clicked.connect(lambda: self.on_grbl_jog(direction='yminus'))
  476. self.ui.jog_wdg.jog_right_button.clicked.connect(lambda: self.on_grbl_jog(direction='xplus'))
  477. self.ui.jog_wdg.jog_left_button.clicked.connect(lambda: self.on_grbl_jog(direction='xminus'))
  478. self.ui.jog_wdg.jog_z_up_button.clicked.connect(lambda: self.on_grbl_jog(direction='zplus'))
  479. self.ui.jog_wdg.jog_z_down_button.clicked.connect(lambda: self.on_grbl_jog(direction='zminus'))
  480. self.ui.jog_wdg.jog_origin_button.clicked.connect(lambda: self.on_grbl_jog(direction='origin'))
  481. # Zero
  482. self.ui.zero_axs_wdg.grbl_zerox_button.clicked.connect(lambda: self.on_grbl_zero(axis='x'))
  483. self.ui.zero_axs_wdg.grbl_zeroy_button.clicked.connect(lambda: self.on_grbl_zero(axis='y'))
  484. self.ui.zero_axs_wdg.grbl_zeroz_button.clicked.connect(lambda: self.on_grbl_zero(axis='z'))
  485. self.ui.zero_axs_wdg.grbl_zero_all_button.clicked.connect(lambda: self.on_grbl_zero(axis='all'))
  486. self.ui.zero_axs_wdg.grbl_homing_button.clicked.connect(self.on_grbl_homing)
  487. # Sender
  488. self.ui.grbl_report_button.clicked.connect(lambda: self.send_grbl_command(command='?'))
  489. self.ui.grbl_get_param_button.clicked.connect(
  490. lambda: self.on_grbl_get_parameter(param=self.ui.grbl_parameter_entry.get_value()))
  491. self.ui.view_h_gcode_button.clicked.connect(self.on_edit_probing_gcode)
  492. self.ui.h_gcode_button.clicked.connect(self.on_save_probing_gcode)
  493. self.ui.import_heights_button.clicked.connect(self.on_import_height_map)
  494. self.ui.pause_resume_button.clicked.connect(self.on_grbl_pause_resume)
  495. self.ui.grbl_get_heightmap_button.clicked.connect(self.on_grbl_autolevel)
  496. self.ui.grbl_save_height_map_button.clicked.connect(self.on_grbl_heightmap_save)
  497. self.build_al_table_sig.connect(self.build_al_table)
  498. # self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  499. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  500. # Show/Hide Advanced Options
  501. if self.app.defaults["global_app_level"] == 'b':
  502. self.ui.level.setText(_(
  503. '<span style="color:green;"><b>Basic</b></span>'
  504. ))
  505. self.ui.sal_cb.hide()
  506. self.ui.sal_cb.set_value(False)
  507. else:
  508. self.ui.level.setText(_(
  509. '<span style="color:red;"><b>Advanced</b></span>'
  510. ))
  511. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name or 'hpgl' in \
  512. self.pp_geometry_name:
  513. self.ui.sal_cb.hide()
  514. self.ui.sal_cb.set_value(False)
  515. else:
  516. self.ui.sal_cb.show()
  517. self.ui.sal_cb.set_value(self.app.defaults["cncjob_al_status"])
  518. preamble = self.append_snippet
  519. postamble = self.prepend_snippet
  520. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  521. self.source_file = gc.getvalue()
  522. self.ui.al_mode_radio.set_value(self.options['al_mode'])
  523. self.on_controller_change()
  524. self.on_method_radio(val=self.options['al_method'])
  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 = 0 if cols == 1 else width / (cols - 1)
  575. dy = 0 if rows == 1 else 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.plot_probing_pts_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.plot_probing_pts_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.plot_probing_pts_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_method_radio(self, val):
  895. if val == 'b':
  896. self.ui.al_columns_entry.setMinimum(2)
  897. self.ui.al_rows_entry.setMinimum(2)
  898. else:
  899. self.ui.al_columns_entry.setMinimum(1)
  900. self.ui.al_rows_entry.setMinimum(1)
  901. def on_controller_change(self):
  902. if self.ui.al_controller_combo.get_value() == 'GRBL':
  903. self.ui.h_gcode_button.hide()
  904. self.ui.view_h_gcode_button.hide()
  905. self.ui.import_heights_button.hide()
  906. self.ui.grbl_frame.show()
  907. self.on_grbl_search_ports(muted=True)
  908. else:
  909. self.ui.h_gcode_button.show()
  910. self.ui.view_h_gcode_button.show()
  911. self.ui.import_heights_button.show()
  912. self.ui.grbl_frame.hide()
  913. # if the is empty then there is a chance that we've added probe points but the GRBL controller was selected
  914. # therefore no Probing GCode was genrated (it is different for GRBL on how it gets it's Probing GCode
  915. if not self.probing_gcode_text or self.probing_gcode_text == '':
  916. # generate Probing GCode
  917. self.probing_gcode_text = self.probing_gcode()
  918. def on_grbl_list_serial_ports(self):
  919. """
  920. Lists serial port names.
  921. From here: https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
  922. :raises EnvironmentError: On unsupported or unknown platforms
  923. :returns: A list of the serial ports available on the system
  924. """
  925. if sys.platform.startswith('win'):
  926. ports = ['COM%s' % (i + 1) for i in range(256)]
  927. elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
  928. # this excludes your current terminal "/dev/tty"
  929. ports = glob.glob('/dev/tty[A-Za-z]*')
  930. elif sys.platform.startswith('darwin'):
  931. ports = glob.glob('/dev/tty.*')
  932. else:
  933. raise EnvironmentError('Unsupported platform')
  934. result = []
  935. s = serial.Serial()
  936. for port in ports:
  937. s.port = port
  938. try:
  939. s.open()
  940. s.close()
  941. result.append(port)
  942. except (OSError, serial.SerialException):
  943. # result.append(port + " (in use)")
  944. pass
  945. return result
  946. def on_grbl_search_ports(self, muted=None):
  947. port_list = self.on_grbl_list_serial_ports()
  948. self.ui.com_list_combo.clear()
  949. self.ui.com_list_combo.addItems(port_list)
  950. if muted is not True:
  951. self.app.inform.emit('[WARNING_NOTCL] %s' % _("COM list updated ..."))
  952. def on_grbl_connect(self):
  953. port_name = self.ui.com_list_combo.currentText()
  954. if " (" in port_name:
  955. port_name = port_name.rpartition(" (")[0]
  956. baudrate = int(self.ui.baudrates_list_combo.currentText())
  957. try:
  958. self.grbl_ser_port = serial.serial_for_url(port_name, baudrate,
  959. bytesize=serial.EIGHTBITS,
  960. parity=serial.PARITY_NONE,
  961. stopbits=serial.STOPBITS_ONE,
  962. timeout=0.1,
  963. xonxoff=False,
  964. rtscts=False)
  965. # Toggle DTR to reset the controller loaded with GRBL (Arduino, ESP32, etc)
  966. try:
  967. self.grbl_ser_port.dtr = False
  968. except IOError:
  969. pass
  970. self.grbl_ser_port.reset_input_buffer()
  971. try:
  972. self.grbl_ser_port.dtr = True
  973. except IOError:
  974. pass
  975. answer = self.on_grbl_wake()
  976. answer = ['ok'] # hack for development without a GRBL controller connected
  977. for line in answer:
  978. if 'ok' in line.lower():
  979. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: seagreen;}")
  980. self.ui.com_connect_button.setText(_("Connected"))
  981. self.ui.controller_reset_button.setDisabled(False)
  982. for idx in range(self.ui.al_toolbar.count()):
  983. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  984. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('seagreen'))
  985. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  986. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  987. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  988. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  989. self.app.inform.emit("%s: %s" % (_("Port connected"), port_name))
  990. return
  991. self.grbl_ser_port.close()
  992. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to GRBL on port"), port_name))
  993. except serial.SerialException:
  994. self.grbl_ser_port = serial.Serial()
  995. self.grbl_ser_port.port = port_name
  996. self.grbl_ser_port.close()
  997. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: red;}")
  998. self.ui.com_connect_button.setText(_("Disconnected"))
  999. self.ui.controller_reset_button.setDisabled(True)
  1000. for idx in range(self.ui.al_toolbar.count()):
  1001. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  1002. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  1003. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  1004. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  1005. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  1006. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  1007. self.app.inform.emit("%s: %s" % (_("Port is connected. Disconnecting"), port_name))
  1008. except Exception:
  1009. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to port"), port_name))
  1010. def on_grbl_add_baudrate(self):
  1011. new_bd = str(self.ui.new_baudrate_entry.get_value())
  1012. if int(new_bd) >= 40 and new_bd not in self.ui.baudrates_list_combo.model().stringList():
  1013. self.ui.baudrates_list_combo.addItem(new_bd)
  1014. self.ui.baudrates_list_combo.setCurrentText(new_bd)
  1015. def on_grbl_delete_baudrate_grbl(self):
  1016. current_idx = self.ui.baudrates_list_combo.currentIndex()
  1017. self.ui.baudrates_list_combo.removeItem(current_idx)
  1018. def on_grbl_wake(self):
  1019. # Wake up grbl
  1020. self.grbl_ser_port.write("\r\n\r\n".encode('utf-8'))
  1021. # Wait for GRBL controller to initialize
  1022. time.sleep(1)
  1023. grbl_out = deepcopy(self.grbl_ser_port.readlines())
  1024. self.grbl_ser_port.reset_input_buffer()
  1025. return grbl_out
  1026. def on_grbl_send_command(self):
  1027. cmd = self.ui.grbl_command_entry.get_value()
  1028. # show the Shell Dock
  1029. self.app.ui.shell_dock.show()
  1030. def worker_task():
  1031. with self.app.proc_container.new(_("Sending GCode...")):
  1032. self.send_grbl_command(command=cmd)
  1033. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  1034. def send_grbl_command(self, command, echo=True):
  1035. """
  1036. :param command: GCode command
  1037. :type command: str
  1038. :param echo: if to send a '\n' char after
  1039. :type echo: bool
  1040. :return: the text returned by the GRBL controller after each command
  1041. :rtype: str
  1042. """
  1043. cmd = command.strip()
  1044. if echo:
  1045. self.app.inform_shell[str, bool].emit(cmd, False)
  1046. # Send Gcode command to GRBL
  1047. snd = cmd + '\n'
  1048. self.grbl_ser_port.write(snd.encode('utf-8'))
  1049. grbl_out = self.grbl_ser_port.readlines()
  1050. if not grbl_out:
  1051. self.app.inform_shell[str, bool].emit('\t\t\t: No answer\n', False)
  1052. result = ''
  1053. for line in grbl_out:
  1054. if echo:
  1055. try:
  1056. self.app.inform_shell.emit('\t\t\t: ' + line.decode('utf-8').strip().upper())
  1057. except Exception as e:
  1058. log.debug("CNCJobObject.send_grbl_command() --> %s" % str(e))
  1059. if 'ok' in line:
  1060. result = grbl_out
  1061. return result
  1062. def send_grbl_block(self, command, echo=True):
  1063. stripped_cmd = command.strip()
  1064. for l in stripped_cmd.split('\n'):
  1065. if echo:
  1066. self.app.inform_shell[str, bool].emit(l, False)
  1067. # Send Gcode block to GRBL
  1068. snd = l + '\n'
  1069. self.grbl_ser_port.write(snd.encode('utf-8'))
  1070. grbl_out = self.grbl_ser_port.readlines()
  1071. for line in grbl_out:
  1072. if echo:
  1073. try:
  1074. self.app.inform_shell.emit(' : ' + line.decode('utf-8').strip().upper())
  1075. except Exception as e:
  1076. log.debug("CNCJobObject.send_grbl_block() --> %s" % str(e))
  1077. def on_grbl_get_parameter(self, param):
  1078. if '$' in param:
  1079. param = param.replace('$','')
  1080. snd = '$$\n'
  1081. self.grbl_ser_port.write(snd.encode('utf-8'))
  1082. grbl_out = self.grbl_ser_port.readlines()
  1083. for line in grbl_out:
  1084. decoded_line = line.decode('utf-8')
  1085. par = '$%s' % str(param)
  1086. if par in decoded_line:
  1087. result = float(decoded_line.rpartition('=')[2])
  1088. self.app.shell_message("GRBL Parameter: %s = %s" % (str(param), str(result)), show=True)
  1089. return result
  1090. def on_grbl_jog(self, direction=None):
  1091. if direction is None:
  1092. return
  1093. cmd = ''
  1094. step = self.ui.jog_step_entry.get_value(),
  1095. feedrate = self.ui.jog_fr_entry.get_value()
  1096. travelz = float(self.app.defaults["cncjob_al_grbl_travelz"])
  1097. if direction == 'xplus':
  1098. cmd = "$J=G91 %s X%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1099. if direction == 'xminus':
  1100. cmd = "$J=G91 %s X-%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1101. if direction == 'yplus':
  1102. cmd = "$J=G91 %s Y%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1103. if direction == 'yminus':
  1104. cmd = "$J=G91 %s Y-%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1105. if direction == 'zplus':
  1106. cmd = "$J=G91 %s Z%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1107. if direction == 'zminus':
  1108. cmd = "$J=G91 %s Z-%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1109. if direction == 'origin':
  1110. cmd = "$J=G90 %s Z%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(travelz), str(feedrate))
  1111. self.send_grbl_command(command=cmd, echo=False)
  1112. cmd = "$J=G90 %s X0.0 Y0.0 F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(feedrate))
  1113. self.send_grbl_command(command=cmd, echo=False)
  1114. return
  1115. self.send_grbl_command(command=cmd, echo=False)
  1116. def on_grbl_zero(self, axis):
  1117. current_mode = self.on_grbl_get_parameter('10')
  1118. if current_mode is None:
  1119. return
  1120. cmd = '$10=0'
  1121. self.send_grbl_command(command=cmd, echo=False)
  1122. if axis == 'x':
  1123. cmd = 'G10 L2 P1 X0'
  1124. elif axis == 'y':
  1125. cmd = 'G10 L2 P1 Y0'
  1126. elif axis == 'z':
  1127. cmd = 'G10 L2 P1 Z0'
  1128. else:
  1129. # all
  1130. cmd = 'G10 L2 P1 X0 Y0 Z0'
  1131. self.send_grbl_command(command=cmd, echo=False)
  1132. # restore previous mode
  1133. cmd = '$10=%d' % int(current_mode)
  1134. self.send_grbl_command(command=cmd, echo=False)
  1135. def on_grbl_homing(self):
  1136. cmd = '$H'
  1137. self.app.inform.emit("%s" % _("GRBL is doing a home cycle."))
  1138. self.on_grbl_wake()
  1139. self.send_grbl_command(command=cmd)
  1140. def on_grbl_reset(self):
  1141. cmd = '\x18'
  1142. self.app.inform.emit("%s" % _("GRBL software reset was sent."))
  1143. self.on_grbl_wake()
  1144. self.send_grbl_command(command=cmd)
  1145. def on_grbl_pause_resume(self, checked):
  1146. if checked is False:
  1147. cmd = '~'
  1148. self.send_grbl_command(command=cmd)
  1149. self.app.inform.emit("%s" % _("GRBL resumed."))
  1150. else:
  1151. cmd = '!'
  1152. self.send_grbl_command(command=cmd)
  1153. self.app.inform.emit("%s" % _("GRBL paused."))
  1154. def probing_gcode(self):
  1155. """
  1156. :return: Probing GCode
  1157. :rtype: str
  1158. """
  1159. p_gcode = ''
  1160. header = ''
  1161. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1162. coords = []
  1163. for id_key, value in self.al_geometry_dict.items():
  1164. x = value['point'].x
  1165. y = value['point'].y
  1166. coords.append(
  1167. (
  1168. self.app.dec_format(x, dec=self.app.decimals),
  1169. self.app.dec_format(y, dec=self.app.decimals)
  1170. )
  1171. )
  1172. pr_travel = self.ui.ptravelz_entry.get_value()
  1173. probe_fr = self.ui.feedrate_probe_entry.get_value()
  1174. pr_depth = self.ui.pdepth_entry.get_value()
  1175. controller = self.ui.al_controller_combo.get_value()
  1176. header += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1177. (str(self.app.version), str(self.app.version_date)) + '\n'
  1178. header += '(This is a autolevelling probing GCode.)\n' \
  1179. '(Make sure that before you start the job you first do a zero for all axis.)\n\n'
  1180. header += '(Name: ' + str(self.options['name']) + ')\n'
  1181. header += '(Type: ' + "Autolevelling Probing GCode " + ')\n'
  1182. header += '(Units: ' + self.units.upper() + ')\n'
  1183. header += '(Created on ' + time_str + ')\n'
  1184. # commands
  1185. if controller == 'MACH3':
  1186. probing_command = 'G31'
  1187. # probing_var = '#2002'
  1188. openfile_command = 'M40'
  1189. closefile_command = 'M41'
  1190. elif controller == 'MACH4':
  1191. probing_command = 'G31'
  1192. # probing_var = '#5063'
  1193. openfile_command = 'M40'
  1194. closefile_command = 'M41'
  1195. elif controller == 'LinuxCNC':
  1196. probing_command = 'G38.2'
  1197. # probing_var = '#5422'
  1198. openfile_command = '(PROBEOPEN a_probing_points_file.txt)'
  1199. closefile_command = '(PROBECLOSE)'
  1200. elif controller == 'GRBL':
  1201. # do nothing here because the Probing GCode for GRBL is obtained differently
  1202. return
  1203. else:
  1204. log.debug("CNCJobObject.probing_gcode() -> controller not supported")
  1205. return
  1206. # #############################################################################################################
  1207. # ########################### GCODE construction ##############################################################
  1208. # #############################################################################################################
  1209. # header
  1210. p_gcode += header + '\n'
  1211. # supplementary message for LinuxCNC
  1212. if controller == 'LinuxCNC':
  1213. p_gcode += "The file with the stored probing points can be found\n" \
  1214. "in the configuration folder for LinuxCNC.\n" \
  1215. "The name of the file is: a_probing_points_file.txt.\n"
  1216. # units
  1217. p_gcode += 'G21\n' if self.units == 'MM' else 'G20\n'
  1218. # reference mode = absolute
  1219. p_gcode += 'G90\n'
  1220. # open a new file
  1221. p_gcode += openfile_command + '\n'
  1222. # move to safe height (probe travel Z)
  1223. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1224. # probing points
  1225. for idx, xy_tuple in enumerate(coords, 1): # index starts from 1
  1226. x = xy_tuple[0]
  1227. y = xy_tuple[1]
  1228. # move to probing point
  1229. p_gcode += "G0 X%sY%s\n" % (
  1230. str(self.app.dec_format(x, self.coords_decimals)),
  1231. str(self.app.dec_format(y, self.coords_decimals))
  1232. )
  1233. # do the probing
  1234. p_gcode += "%s Z%s F%s\n" % (
  1235. probing_command,
  1236. str(self.app.dec_format(pr_depth, self.coords_decimals)),
  1237. str(self.app.dec_format(probe_fr, self.fr_decimals)),
  1238. )
  1239. # store in a global numeric variable the value of the detected probe Z
  1240. # I offset the global numeric variable by 500 so it does not conflict with something else
  1241. # temp_var = int(idx + 500)
  1242. # p_gcode += "#%d = %s\n" % (temp_var, probing_var)
  1243. # move to safe height (probe travel Z)
  1244. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1245. # close the file
  1246. p_gcode += closefile_command + '\n'
  1247. # finish the GCode
  1248. p_gcode += 'M2'
  1249. return p_gcode
  1250. def on_save_probing_gcode(self):
  1251. lines = StringIO(self.probing_gcode_text)
  1252. _filter_ = self.app.defaults['cncjob_save_filters']
  1253. name = "probing_gcode"
  1254. try:
  1255. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1256. filename, _f = FCFileSaveDialog.get_saved_filename(
  1257. caption=_("Export Code ..."),
  1258. directory=dir_file_to_save,
  1259. ext_filter=_filter_
  1260. )
  1261. except TypeError:
  1262. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1263. if filename == '':
  1264. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1265. return
  1266. else:
  1267. try:
  1268. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1269. if force_windows_line_endings and sys.platform != 'win32':
  1270. with open(filename, 'w', newline='\r\n') as f:
  1271. for line in lines:
  1272. f.write(line)
  1273. else:
  1274. with open(filename, 'w') as f:
  1275. for line in lines:
  1276. f.write(line)
  1277. except FileNotFoundError:
  1278. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1279. return
  1280. except PermissionError:
  1281. self.app.inform.emit(
  1282. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1283. "Most likely another app is holding the file open and not accessible.")
  1284. )
  1285. return 'fail'
  1286. def on_edit_probing_gcode(self):
  1287. self.app.proc_container.view.set_busy(_("Loading..."))
  1288. gco = self.probing_gcode_text
  1289. if gco is None or gco == '':
  1290. self.app.inform.emit('[WARNING_NOTCL] %s...' % _('There is nothing to view'))
  1291. return
  1292. self.gcode_viewer_tab = AppTextEditor(app=self.app, plain_text=True)
  1293. # add the tab if it was closed
  1294. self.app.ui.plot_tab_area.addTab(self.gcode_viewer_tab, '%s' % _("Code Viewer"))
  1295. self.gcode_viewer_tab.setObjectName('code_viewer_tab')
  1296. # delete the absolute and relative position and messages in the infobar
  1297. self.app.ui.position_label.setText("")
  1298. self.app.ui.rel_position_label.setText("")
  1299. self.gcode_viewer_tab.code_editor.completer_enable = False
  1300. self.gcode_viewer_tab.buttonRun.hide()
  1301. # Switch plot_area to CNCJob tab
  1302. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_viewer_tab)
  1303. self.gcode_viewer_tab.t_frame.hide()
  1304. # then append the text from GCode to the text editor
  1305. try:
  1306. self.gcode_viewer_tab.load_text(gco, move_to_start=True, clear_text=True)
  1307. except Exception as e:
  1308. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1309. return
  1310. self.gcode_viewer_tab.t_frame.show()
  1311. self.app.proc_container.view.set_idle()
  1312. self.gcode_viewer_tab.buttonSave.hide()
  1313. self.gcode_viewer_tab.buttonOpen.hide()
  1314. self.gcode_viewer_tab.buttonPrint.hide()
  1315. self.gcode_viewer_tab.buttonPreview.hide()
  1316. self.gcode_viewer_tab.buttonReplace.hide()
  1317. self.gcode_viewer_tab.sel_all_cb.hide()
  1318. self.gcode_viewer_tab.entryReplace.hide()
  1319. self.gcode_viewer_tab.button_update_code.show()
  1320. # self.gcode_viewer_tab.code_editor.setReadOnly(True)
  1321. self.gcode_viewer_tab.button_update_code.clicked.connect(self.on_update_probing_gcode)
  1322. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Viewer'))
  1323. def on_update_probing_gcode(self):
  1324. self.probing_gcode_text = self.gcode_viewer_tab.code_editor.toPlainText()
  1325. def on_import_height_map(self):
  1326. """
  1327. Import the height map file into the app
  1328. :return:
  1329. :rtype:
  1330. """
  1331. _filter_ = "Text File .txt (*.txt);;All Files (*.*)"
  1332. try:
  1333. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1334. directory=self.app.get_last_folder(),
  1335. filter=_filter_)
  1336. except TypeError:
  1337. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1338. filter=_filter_)
  1339. filename = str(filename)
  1340. if filename == '':
  1341. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1342. else:
  1343. self.app.worker_task.emit({'fcn': self.import_height_map, 'params': [filename]})
  1344. def import_height_map(self, filename):
  1345. """
  1346. :param filename:
  1347. :type filename:
  1348. :return:
  1349. :rtype:
  1350. """
  1351. stream = ''
  1352. try:
  1353. if filename:
  1354. with open(filename, 'r') as f:
  1355. stream = f.readlines()
  1356. else:
  1357. return
  1358. except IOError:
  1359. log.error("Failed to open height map file: %s" % filename)
  1360. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open height map file"), filename))
  1361. return
  1362. idx = 0
  1363. for line in stream:
  1364. if line != '':
  1365. idx += 1
  1366. line = line.replace(' ', ',').replace('\n', '').split(',')
  1367. if idx not in self.al_geometry_dict:
  1368. self.al_geometry_dict[idx] = {}
  1369. self.al_geometry_dict[idx]['height'] = float(line[2])
  1370. if 'point' not in self.al_geometry_dict[idx]:
  1371. x = float(line[0])
  1372. y = float(line[1])
  1373. self.al_geometry_dict[idx]['point'] = Point((x, y))
  1374. self.build_al_table_sig.emit()
  1375. def on_grbl_autolevel(self):
  1376. # show the Shell Dock
  1377. self.app.ui.shell_dock.show()
  1378. def worker_task():
  1379. with self.app.proc_container.new(_("Sending GCode...")):
  1380. self.grbl_probe_result = ''
  1381. pr_travelz = str(self.ui.ptravelz_entry.get_value())
  1382. probe_fr = str(self.ui.feedrate_probe_entry.get_value())
  1383. pr_depth = str(self.ui.pdepth_entry.get_value())
  1384. cmd = 'G21\n'
  1385. self.send_grbl_command(command=cmd)
  1386. cmd = 'G90\n'
  1387. self.send_grbl_command(command=cmd)
  1388. for pt_key in self.al_geometry_dict:
  1389. x = str(self.al_geometry_dict[pt_key]['point'].x)
  1390. y = str(self.al_geometry_dict[pt_key]['point'].y)
  1391. cmd = 'G0 Z%s\n' % pr_travelz
  1392. self.send_grbl_command(command=cmd)
  1393. cmd = 'G0 X%s Y%s\n' % (x, y)
  1394. self.send_grbl_command(command=cmd)
  1395. cmd = 'G38.2 Z%s F%s' % (pr_depth, probe_fr)
  1396. output = self.send_grbl_command(command=cmd)
  1397. self.grbl_probe_result += output + '\n'
  1398. cmd = 'M2\n'
  1399. self.send_grbl_command(command=cmd)
  1400. self.app.inform.emit('%s' % _("Finished probing. Doing the autolevelling."))
  1401. # apply autolevel here
  1402. self.on_grbl_apply_autolevel()
  1403. self.app.inform.emit('%s' % _("Sending probing GCode to the GRBL controller."))
  1404. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  1405. def on_grbl_heightmap_save(self):
  1406. if self.grbl_probe_result != '':
  1407. _filter_ = "Text File .txt (*.txt);;All Files (*.*)"
  1408. name = "probing_gcode"
  1409. try:
  1410. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1411. filename, _f = FCFileSaveDialog.get_saved_filename(
  1412. caption=_("Export Code ..."),
  1413. directory=dir_file_to_save,
  1414. ext_filter=_filter_
  1415. )
  1416. except TypeError:
  1417. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1418. if filename == '':
  1419. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1420. return
  1421. else:
  1422. try:
  1423. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1424. if force_windows_line_endings and sys.platform != 'win32':
  1425. with open(filename, 'w', newline='\r\n') as f:
  1426. for line in self.grbl_probe_result:
  1427. f.write(line)
  1428. else:
  1429. with open(filename, 'w') as f:
  1430. for line in self.grbl_probe_result:
  1431. f.write(line)
  1432. except FileNotFoundError:
  1433. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1434. return
  1435. except PermissionError:
  1436. self.app.inform.emit(
  1437. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1438. "Most likely another app is holding the file open and not accessible.")
  1439. )
  1440. return 'fail'
  1441. else:
  1442. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Empty GRBL heightmap."))
  1443. def on_grbl_apply_autolevel(self):
  1444. # TODO here we call the autolevell method
  1445. self.app.inform.emit('%s' % _("Finished autolevelling."))
  1446. def on_updateplot_button_click(self, *args):
  1447. """
  1448. Callback for the "Updata Plot" button. Reads the form for updates
  1449. and plots the object.
  1450. """
  1451. self.read_form()
  1452. self.on_plot_kind_change()
  1453. def on_plot_kind_change(self):
  1454. kind = self.ui.cncplot_method_combo.get_value()
  1455. def worker_task():
  1456. with self.app.proc_container.new(_("Plotting...")):
  1457. self.plot(kind=kind)
  1458. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  1459. def on_exportgcode_button_click(self):
  1460. """
  1461. Handler activated by a button clicked when exporting GCode.
  1462. :param args:
  1463. :return:
  1464. """
  1465. self.app.defaults.report_usage("cncjob_on_exportgcode_button")
  1466. self.read_form()
  1467. name = self.app.collection.get_active().options['name']
  1468. save_gcode = False
  1469. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  1470. _filter_ = "RML1 Files .rol (*.rol);;All Files (*.*)"
  1471. elif 'hpgl' in self.pp_geometry_name:
  1472. _filter_ = "HPGL Files .plt (*.plt);;All Files (*.*)"
  1473. else:
  1474. save_gcode = True
  1475. _filter_ = self.app.defaults['cncjob_save_filters']
  1476. try:
  1477. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1478. filename, _f = FCFileSaveDialog.get_saved_filename(
  1479. caption=_("Export Code ..."),
  1480. directory=dir_file_to_save,
  1481. ext_filter=_filter_
  1482. )
  1483. except TypeError:
  1484. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1485. self.export_gcode_handler(filename, is_gcode=save_gcode)
  1486. def export_gcode_handler(self, filename, is_gcode=True):
  1487. preamble = ''
  1488. postamble = ''
  1489. filename = str(filename)
  1490. if filename == '':
  1491. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1492. return
  1493. else:
  1494. if is_gcode is True:
  1495. used_extension = filename.rpartition('.')[2]
  1496. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  1497. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  1498. self.ui.name_entry.set_value(new_name)
  1499. self.on_name_activate(silent=True)
  1500. try:
  1501. if self.ui.snippets_cb.get_value():
  1502. preamble = self.append_snippet
  1503. postamble = self.prepend_snippet
  1504. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  1505. except Exception as err:
  1506. log.debug("CNCJobObject.export_gcode_handler() --> %s" % str(err))
  1507. gc = self.export_gcode(filename)
  1508. if gc == 'fail':
  1509. return
  1510. if self.app.defaults["global_open_style"] is False:
  1511. self.app.file_opened.emit("gcode", filename)
  1512. self.app.file_saved.emit("gcode", filename)
  1513. self.app.inform.emit('[success] %s: %s' % (_("File saved to"), filename))
  1514. def on_edit_code_click(self, *args):
  1515. """
  1516. Handler activated by a button clicked when reviewing GCode.
  1517. :param args:
  1518. :return:
  1519. """
  1520. self.app.proc_container.view.set_busy(_("Loading..."))
  1521. preamble = self.append_snippet
  1522. postamble = self.prepend_snippet
  1523. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  1524. if gco == 'fail':
  1525. return
  1526. else:
  1527. self.app.gcode_edited = gco
  1528. self.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  1529. # add the tab if it was closed
  1530. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Review"))
  1531. self.gcode_editor_tab.setObjectName('code_editor_tab')
  1532. # delete the absolute and relative position and messages in the infobar
  1533. self.app.ui.position_label.setText("")
  1534. self.app.ui.rel_position_label.setText("")
  1535. self.gcode_editor_tab.code_editor.completer_enable = False
  1536. self.gcode_editor_tab.buttonRun.hide()
  1537. # Switch plot_area to CNCJob tab
  1538. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  1539. self.gcode_editor_tab.t_frame.hide()
  1540. # then append the text from GCode to the text editor
  1541. try:
  1542. self.gcode_editor_tab.load_text(self.app.gcode_edited.getvalue(), move_to_start=True, clear_text=True)
  1543. except Exception as e:
  1544. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1545. return
  1546. self.gcode_editor_tab.t_frame.show()
  1547. self.app.proc_container.view.set_idle()
  1548. self.gcode_editor_tab.buttonSave.hide()
  1549. self.gcode_editor_tab.buttonOpen.hide()
  1550. self.gcode_editor_tab.buttonPrint.hide()
  1551. self.gcode_editor_tab.buttonPreview.hide()
  1552. self.gcode_editor_tab.buttonReplace.hide()
  1553. self.gcode_editor_tab.sel_all_cb.hide()
  1554. self.gcode_editor_tab.entryReplace.hide()
  1555. self.gcode_editor_tab.code_editor.setReadOnly(True)
  1556. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  1557. def on_update_source_file(self):
  1558. self.source_file = self.gcode_editor_tab.code_editor.toPlainText()
  1559. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  1560. """
  1561. Will create a header to be added to all GCode files generated by FlatCAM
  1562. :param comment_start_symbol: A symbol to be used as the first symbol in a comment
  1563. :param comment_stop_symbol: A symbol to be used as the last symbol in a comment
  1564. :return: A string with a GCode header
  1565. """
  1566. log.debug("FlatCAMCNCJob.gcode_header()")
  1567. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1568. marlin = False
  1569. hpgl = False
  1570. probe_pp = False
  1571. gcode = ''
  1572. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  1573. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  1574. try:
  1575. for key in self.cnc_tools:
  1576. ppg = self.cnc_tools[key]['data']['ppname_g']
  1577. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  1578. marlin = True
  1579. break
  1580. if ppg == 'hpgl':
  1581. hpgl = True
  1582. break
  1583. if "toolchange_probe" in ppg.lower():
  1584. probe_pp = True
  1585. break
  1586. except KeyError:
  1587. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  1588. pass
  1589. try:
  1590. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  1591. marlin = True
  1592. except KeyError:
  1593. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1594. pass
  1595. try:
  1596. if "toolchange_probe" in self.options['ppname_e'].lower():
  1597. probe_pp = True
  1598. except KeyError:
  1599. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1600. pass
  1601. if marlin is True:
  1602. gcode += ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  1603. (str(self.app.version), str(self.app.version_date)) + '\n'
  1604. gcode += ';Name: ' + str(self.options['name']) + '\n'
  1605. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  1606. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1607. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1608. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  1609. gcode += ';Created on ' + time_str + '\n' + '\n'
  1610. elif hpgl is True:
  1611. gcode += 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  1612. (str(self.app.version), str(self.app.version_date)) + '";\n'
  1613. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  1614. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  1615. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1616. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1617. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  1618. gcode += 'CO "Created on ' + time_str + '";\n'
  1619. elif probe_pp is True:
  1620. gcode += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1621. (str(self.app.version), str(self.app.version_date)) + '\n'
  1622. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  1623. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  1624. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  1625. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  1626. 'Then zero the Z axis.)\n' + '\n'
  1627. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  1628. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  1629. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1630. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1631. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1632. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1633. else:
  1634. gcode += '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  1635. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  1636. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  1637. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  1638. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1639. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1640. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  1641. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  1642. return gcode
  1643. @staticmethod
  1644. def gcode_footer(end_command=None):
  1645. """
  1646. Will add the M02 to the end of GCode, if requested.
  1647. :param end_command: 'M02' or 'M30' - String
  1648. :return:
  1649. """
  1650. if end_command:
  1651. return end_command
  1652. else:
  1653. return 'M02'
  1654. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False, from_tcl=False):
  1655. """
  1656. This will save the GCode from the Gcode object to a file on the OS filesystem
  1657. :param filename: filename for the GCode file
  1658. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  1659. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  1660. :param to_file: if False then no actual file is saved but the app will know that a file was created
  1661. :param from_tcl: True if run from Tcl Shell
  1662. :return: None
  1663. """
  1664. # gcode = ''
  1665. # roland = False
  1666. # hpgl = False
  1667. # isel_icp = False
  1668. include_header = True
  1669. if preamble == '':
  1670. preamble = self.app.defaults["cncjob_prepend"]
  1671. if postamble == '':
  1672. preamble = self.app.defaults["cncjob_append"]
  1673. try:
  1674. if self.special_group:
  1675. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  1676. (_("This CNCJob object can't be processed because it is a"),
  1677. str(self.special_group),
  1678. _("CNCJob object")))
  1679. return 'fail'
  1680. except AttributeError:
  1681. pass
  1682. # if this dict is not empty then the object is a Geometry object
  1683. if self.cnc_tools:
  1684. first_key = next(iter(self.cnc_tools))
  1685. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  1686. # if this dict is not empty then the object is an Excellon object
  1687. if self.exc_cnc_tools:
  1688. first_key = next(iter(self.exc_cnc_tools))
  1689. include_header = self.app.preprocessors[
  1690. self.exc_cnc_tools[first_key]['data']['tools_drill_ppname_e']
  1691. ].include_header
  1692. gcode = ''
  1693. if include_header is False:
  1694. g = preamble
  1695. # detect if using multi-tool and make the Gcode summation correctly for each case
  1696. if self.multitool is True:
  1697. for tooluid_key in self.cnc_tools:
  1698. for key, value in self.cnc_tools[tooluid_key].items():
  1699. if key == 'gcode':
  1700. gcode += value
  1701. break
  1702. else:
  1703. gcode += self.gcode
  1704. g = g + gcode + postamble
  1705. else:
  1706. # search for the GCode beginning which is usually a G20 or G21
  1707. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  1708. # g_idx = gcode.rfind('G20')
  1709. #
  1710. # # if it did not find 'G20' then search for 'G21'
  1711. # if g_idx == -1:
  1712. # g_idx = gcode.rfind('G21')
  1713. #
  1714. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  1715. # if g_idx == -1:
  1716. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  1717. # return
  1718. # detect if using multi-tool and make the Gcode summation correctly for each case
  1719. if self.multitool is True:
  1720. if self.origin_kind == 'excellon':
  1721. for tooluid_key in self.exc_cnc_tools:
  1722. for key, value in self.exc_cnc_tools[tooluid_key].items():
  1723. if key == 'gcode' and value:
  1724. gcode += value
  1725. break
  1726. else:
  1727. for tooluid_key in self.cnc_tools:
  1728. for key, value in self.cnc_tools[tooluid_key].items():
  1729. if key == 'gcode' and value:
  1730. gcode += value
  1731. break
  1732. else:
  1733. gcode += self.gcode
  1734. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  1735. # detect if using a HPGL preprocessor
  1736. hpgl = False
  1737. if self.cnc_tools:
  1738. for key in self.cnc_tools:
  1739. if 'ppname_g' in self.cnc_tools[key]['data']:
  1740. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  1741. hpgl = True
  1742. break
  1743. elif self.exc_cnc_tools:
  1744. for key in self.cnc_tools:
  1745. if 'ppname_e' in self.cnc_tools[key]['data']:
  1746. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  1747. hpgl = True
  1748. break
  1749. if hpgl:
  1750. processed_gcode = ''
  1751. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  1752. for gline in gcode.splitlines():
  1753. match = pa_re.search(gline)
  1754. if match:
  1755. x_int = int(float(match.group(1)))
  1756. y_int = int(float(match.group(2)))
  1757. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  1758. processed_gcode += new_line
  1759. else:
  1760. processed_gcode += gline + '\n'
  1761. gcode = processed_gcode
  1762. g = self.gc_header + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  1763. else:
  1764. try:
  1765. g_idx = gcode.index('G94')
  1766. if preamble != '' and postamble != '':
  1767. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1768. gcode[(g_idx + 3):] + postamble + end_gcode
  1769. elif preamble == '':
  1770. g = self.gc_header + gcode[:g_idx + 3] + '\n' + \
  1771. gcode[(g_idx + 3):] + postamble + end_gcode
  1772. elif postamble == '':
  1773. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1774. gcode[(g_idx + 3):] + end_gcode
  1775. else:
  1776. g = self.gc_header + gcode[:g_idx + 3] + gcode[(g_idx + 3):] + end_gcode
  1777. except ValueError:
  1778. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1779. _("G-code does not have a G94 code.\n"
  1780. "Append Code snippet will not be used.."))
  1781. g = self.gc_header + '\n' + gcode + postamble + end_gcode
  1782. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  1783. # if self.ui.toolchange_cb.get_value() is True:
  1784. # # match = self.re_toolchange.search(g)
  1785. # if 'M6' in g:
  1786. # m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  1787. # if m6_code is None or m6_code == '':
  1788. # self.app.inform.emit(
  1789. # '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  1790. # )
  1791. # return 'fail'
  1792. #
  1793. # g = g.replace('M6', m6_code)
  1794. # self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  1795. lines = StringIO(g)
  1796. # Write
  1797. if filename is not None:
  1798. try:
  1799. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1800. if force_windows_line_endings and sys.platform != 'win32':
  1801. with open(filename, 'w', newline='\r\n') as f:
  1802. for line in lines:
  1803. f.write(line)
  1804. else:
  1805. with open(filename, 'w') as f:
  1806. for line in lines:
  1807. f.write(line)
  1808. except FileNotFoundError:
  1809. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1810. return
  1811. except PermissionError:
  1812. self.app.inform.emit(
  1813. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1814. "Most likely another app is holding the file open and not accessible.")
  1815. )
  1816. return 'fail'
  1817. elif to_file is False:
  1818. # Just for adding it to the recent files list.
  1819. if self.app.defaults["global_open_style"] is False:
  1820. self.app.file_opened.emit("cncjob", filename)
  1821. self.app.file_saved.emit("cncjob", filename)
  1822. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  1823. else:
  1824. return lines
  1825. # def on_toolchange_custom_clicked(self, signal):
  1826. # """
  1827. # Handler for clicking toolchange custom.
  1828. #
  1829. # :param signal:
  1830. # :return:
  1831. # """
  1832. #
  1833. # try:
  1834. # if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  1835. # if self.ui.toolchange_cb.get_value():
  1836. # self.ui.toolchange_cb.set_value(False)
  1837. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1838. # _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  1839. # except KeyError:
  1840. # try:
  1841. # for key in self.cnc_tools:
  1842. # ppg = self.cnc_tools[key]['data']['ppname_g']
  1843. # if 'toolchange_custom' not in str(ppg).lower():
  1844. # if self.ui.toolchange_cb.get_value():
  1845. # self.ui.toolchange_cb.set_value(False)
  1846. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1847. # _("The used preprocessor file has to have in it's name: "
  1848. # "'toolchange_custom'"))
  1849. # except KeyError:
  1850. # self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  1851. def get_gcode(self, preamble='', postamble=''):
  1852. """
  1853. We need this to be able to get_gcode separately for shell command export_gcode
  1854. :param preamble: Extra GCode added to the beginning of the GCode
  1855. :param postamble: Extra GCode added at the end of the GCode
  1856. :return: The modified GCode
  1857. """
  1858. return preamble + '\n' + self.gcode + "\n" + postamble
  1859. def get_svg(self):
  1860. # we need this to be able get_svg separately for shell command export_svg
  1861. pass
  1862. def on_plot_cb_click(self, *args):
  1863. """
  1864. Handler for clicking on the Plot checkbox.
  1865. :param args:
  1866. :return:
  1867. """
  1868. if self.muted_ui:
  1869. return
  1870. kind = self.ui.cncplot_method_combo.get_value()
  1871. self.plot(kind=kind)
  1872. self.read_form_item('plot')
  1873. self.ui_disconnect()
  1874. cb_flag = self.ui.plot_cb.isChecked()
  1875. for row in range(self.ui.cnc_tools_table.rowCount()):
  1876. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  1877. if cb_flag:
  1878. table_cb.setChecked(True)
  1879. else:
  1880. table_cb.setChecked(False)
  1881. self.ui_connect()
  1882. def on_plot_cb_click_table(self):
  1883. """
  1884. Handler for clicking the plot checkboxes added into a Table on each row. Purpose: toggle visibility for the
  1885. tool/aperture found on that row.
  1886. :return:
  1887. """
  1888. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1889. self.ui_disconnect()
  1890. # cw = self.sender()
  1891. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  1892. # cw_row = cw_index.row()
  1893. kind = self.ui.cncplot_method_combo.get_value()
  1894. self.shapes.clear(update=True)
  1895. if self.origin_kind == "excellon":
  1896. for r in range(self.ui.exc_cnc_tools_table.rowCount()):
  1897. row_dia = float('%.*f' % (self.decimals, float(self.ui.exc_cnc_tools_table.item(r, 1).text())))
  1898. for tooluid_key in self.exc_cnc_tools:
  1899. tooldia = float('%.*f' % (self.decimals, float(tooluid_key)))
  1900. if row_dia == tooldia:
  1901. gcode_parsed = self.exc_cnc_tools[tooluid_key]['gcode_parsed']
  1902. if self.ui.exc_cnc_tools_table.cellWidget(r, 6).isChecked():
  1903. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1904. else:
  1905. for tooluid_key in self.cnc_tools:
  1906. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1907. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1908. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  1909. for r in range(self.ui.cnc_tools_table.rowCount()):
  1910. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  1911. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  1912. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1913. self.shapes.redraw()
  1914. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1915. # if all the row plot's are enabled also enable the general plot checkbox
  1916. cb_cnt = 0
  1917. total_row = self.ui.cnc_tools_table.rowCount()
  1918. for row in range(total_row):
  1919. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  1920. cb_cnt += 1
  1921. else:
  1922. cb_cnt -= 1
  1923. if cb_cnt < total_row:
  1924. self.ui.plot_cb.setChecked(False)
  1925. else:
  1926. self.ui.plot_cb.setChecked(True)
  1927. self.ui_connect()
  1928. def plot(self, visible=None, kind='all'):
  1929. """
  1930. # Does all the required setup and returns False
  1931. # if the 'ptint' option is set to False.
  1932. :param visible: Boolean to decide if the object will be plotted as visible or disabled on canvas
  1933. :param kind: String. Can be "all" or "travel" or "cut". For CNCJob plotting
  1934. :return: None
  1935. """
  1936. if not FlatCAMObj.plot(self):
  1937. return
  1938. visible = visible if visible else self.options['plot']
  1939. # Geometry shapes plotting
  1940. try:
  1941. if self.multitool is False: # single tool usage
  1942. try:
  1943. dia_plot = float(self.options["tooldia"])
  1944. except ValueError:
  1945. # we may have a tuple with only one element and a comma
  1946. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  1947. self.plot2(tooldia=dia_plot, obj=self, visible=visible, kind=kind)
  1948. else:
  1949. # I do this so the travel lines thickness will reflect the tool diameter
  1950. # may work only for objects created within the app and not Gcode imported from elsewhere for which we
  1951. # don't know the origin
  1952. if self.origin_kind == "excellon":
  1953. if self.exc_cnc_tools:
  1954. for tooldia_key in self.exc_cnc_tools:
  1955. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  1956. gcode_parsed = self.exc_cnc_tools[tooldia_key]['gcode_parsed']
  1957. if not gcode_parsed:
  1958. continue
  1959. # gcode_parsed = self.gcode_parsed
  1960. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1961. else:
  1962. # multiple tools usage
  1963. if self.cnc_tools:
  1964. for tooluid_key in self.cnc_tools:
  1965. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1966. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1967. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1968. self.shapes.redraw()
  1969. except (ObjectDeleted, AttributeError):
  1970. self.shapes.clear(update=True)
  1971. if self.app.is_legacy is False:
  1972. self.annotation.clear(update=True)
  1973. # Annotaions shapes plotting
  1974. try:
  1975. if self.app.is_legacy is False:
  1976. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  1977. self.plot_annotations(obj=self, visible=True)
  1978. else:
  1979. self.plot_annotations(obj=self, visible=False)
  1980. except (ObjectDeleted, AttributeError):
  1981. if self.app.is_legacy is False:
  1982. self.annotation.clear(update=True)
  1983. def on_annotation_change(self):
  1984. """
  1985. Handler for toggling the annotation display by clicking a checkbox.
  1986. :return:
  1987. """
  1988. if self.app.is_legacy is False:
  1989. if self.ui.annotation_cb.get_value():
  1990. self.text_col.enabled = True
  1991. else:
  1992. self.text_col.enabled = False
  1993. # kind = self.ui.cncplot_method_combo.get_value()
  1994. # self.plot(kind=kind)
  1995. self.annotation.redraw()
  1996. else:
  1997. kind = self.ui.cncplot_method_combo.get_value()
  1998. self.plot(kind=kind)
  1999. def convert_units(self, units):
  2000. """
  2001. Units conversion used by the CNCJob objects.
  2002. :param units: Can be "MM" or "IN"
  2003. :return:
  2004. """
  2005. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  2006. factor = CNCjob.convert_units(self, units)
  2007. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  2008. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  2009. 'endz', 'toolchangez']
  2010. temp_tools_dict = {}
  2011. tool_dia_copy = {}
  2012. data_copy = {}
  2013. for tooluid_key, tooluid_value in self.cnc_tools.items():
  2014. for dia_key, dia_value in tooluid_value.items():
  2015. if dia_key == 'tooldia':
  2016. dia_value *= factor
  2017. dia_value = float('%.*f' % (self.decimals, dia_value))
  2018. tool_dia_copy[dia_key] = dia_value
  2019. if dia_key == 'offset':
  2020. tool_dia_copy[dia_key] = dia_value
  2021. if dia_key == 'offset_value':
  2022. dia_value *= factor
  2023. tool_dia_copy[dia_key] = dia_value
  2024. if dia_key == 'type':
  2025. tool_dia_copy[dia_key] = dia_value
  2026. if dia_key == 'tool_type':
  2027. tool_dia_copy[dia_key] = dia_value
  2028. if dia_key == 'data':
  2029. for data_key, data_value in dia_value.items():
  2030. # convert the form fields that are convertible
  2031. for param in param_list:
  2032. if data_key == param and data_value is not None:
  2033. data_copy[data_key] = data_value * factor
  2034. # copy the other dict entries that are not convertible
  2035. if data_key not in param_list:
  2036. data_copy[data_key] = data_value
  2037. tool_dia_copy[dia_key] = deepcopy(data_copy)
  2038. data_copy.clear()
  2039. if dia_key == 'gcode':
  2040. tool_dia_copy[dia_key] = dia_value
  2041. if dia_key == 'gcode_parsed':
  2042. tool_dia_copy[dia_key] = dia_value
  2043. if dia_key == 'solid_geometry':
  2044. tool_dia_copy[dia_key] = dia_value
  2045. # if dia_key == 'solid_geometry':
  2046. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  2047. # if dia_key == 'gcode_parsed':
  2048. # for g in dia_value:
  2049. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  2050. #
  2051. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  2052. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  2053. temp_tools_dict.update({
  2054. tooluid_key: deepcopy(tool_dia_copy)
  2055. })
  2056. tool_dia_copy.clear()
  2057. self.cnc_tools.clear()
  2058. self.cnc_tools = deepcopy(temp_tools_dict)