FlatCAMCNCJob.py 104 KB

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