FlatCAMCNCJob.py 85 KB

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