FlatCAMCNCJob.py 108 KB

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