FlatCAMCNCJob.py 102 KB

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