FlatCAMCNCJob.py 95 KB

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