FlatCAMCNCJob.py 109 KB

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