FlatCAMCNCJob.py 104 KB

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