FlatCAMCNCJob.py 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  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
  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_search_ports)
  464. self.ui.add_bd_button.clicked.connect(self.on_add_baudrate_grbl)
  465. self.ui.del_bd_button.clicked.connect(self.on_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_connect_grbl)
  468. self.ui.grbl_send_button.clicked.connect(self.on_send_grbl_command)
  469. self.ui.grbl_command_entry.returnPressed.connect(self.on_send_grbl_command)
  470. # Jog
  471. self.ui.jog_wdg.jog_up_button.clicked.connect(lambda: self.on_jog(direction='yplus'))
  472. self.ui.jog_wdg.jog_down_button.clicked.connect(lambda: self.on_jog(direction='yminus'))
  473. self.ui.jog_wdg.jog_right_button.clicked.connect(lambda: self.on_jog(direction='xplus'))
  474. self.ui.jog_wdg.jog_left_button.clicked.connect(lambda: self.on_jog(direction='xminus'))
  475. self.ui.jog_wdg.jog_z_up_button.clicked.connect(lambda: self.on_jog(direction='zplus'))
  476. self.ui.jog_wdg.jog_z_down_button.clicked.connect(lambda: self.on_jog(direction='zminus'))
  477. self.ui.jog_wdg.jog_origin_button.clicked.connect(lambda: self.on_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.get_grbl_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_y += dy
  575. new_x = xmin
  576. for y in range(cols):
  577. new_x += dx
  578. formatted_point = (
  579. self.app.dec_format(new_x, self.app.decimals),
  580. self.app.dec_format(new_y, self.app.decimals)
  581. )
  582. points.append(formatted_point)
  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. if self.app.is_legacy is False:
  601. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  602. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  603. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  604. else:
  605. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  606. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  607. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  608. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  609. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  610. self.mouse_events_connected = True
  611. self.build_al_table_sig.emit()
  612. if self.ui.voronoi_cb.get_value():
  613. self.show_voronoi_diagram(state=True, reset=True)
  614. def show_voronoi_diagram(self, state, reset=False):
  615. if reset:
  616. self.voronoi_shapes.clear(update=True)
  617. points_geo = []
  618. poly_geo = []
  619. # create the geometry
  620. radius = 0.3 if self.units == 'MM' else 0.012
  621. for pt in self.al_geometry_dict:
  622. p_geo = self.al_geometry_dict[pt]['point'].buffer(radius)
  623. s_geo = self.al_geometry_dict[pt]['geo'].buffer(0.0000001)
  624. points_geo.append(p_geo)
  625. poly_geo.append(s_geo)
  626. if not points_geo and not poly_geo:
  627. return
  628. plot_geo = points_geo + poly_geo
  629. self.plot_voronoi(geometry=plot_geo, visibility=state)
  630. def plot_voronoi(self, geometry, visibility, custom_color=None):
  631. if visibility:
  632. if self.app.is_legacy is False:
  633. def random_color():
  634. r_color = np.random.rand(4)
  635. r_color[3] = 0.5
  636. return r_color
  637. else:
  638. def random_color():
  639. while True:
  640. r_color = np.random.rand(4)
  641. r_color[3] = 0.5
  642. new_color = '#'
  643. for idx in range(len(r_color)):
  644. new_color += '%x' % int(r_color[idx] * 255)
  645. # do it until a valid color is generated
  646. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  647. # for a total of 9 chars
  648. if len(new_color) == 9:
  649. break
  650. return new_color
  651. try:
  652. if self.app.is_legacy is False:
  653. color = "#0000FFFE"
  654. else:
  655. color = "#0000FFFE"
  656. # for sh in points_geo:
  657. # self.add_voronoi_shape(shape=sh, color=color, face_color=color, visible=True)
  658. edge_color = "#000000FF"
  659. try:
  660. for sh in geometry:
  661. if custom_color is None:
  662. self.add_voronoi_shape(shape=sh, color=edge_color, face_color=random_color(), visible=True)
  663. else:
  664. self.add_voronoi_shape(shape=sh, color=custom_color, face_color=custom_color, visible=True)
  665. except TypeError:
  666. if custom_color is None:
  667. self.add_voronoi_shape(
  668. shape=geometry, color=edge_color, face_color=random_color(), visible=True)
  669. else:
  670. self.add_voronoi_shape(
  671. shape=geometry, color=custom_color, face_color=custom_color, visible=True)
  672. self.voronoi_shapes.redraw()
  673. except (ObjectDeleted, AttributeError):
  674. self.voronoi_shapes.clear(update=True)
  675. except Exception as e:
  676. log.debug("CNCJobObject.plot_voronoi() --> %s" % str(e))
  677. else:
  678. self.voronoi_shapes.clear(update=True)
  679. def add_voronoi_shape(self, **kwargs):
  680. if self.deleted:
  681. raise ObjectDeleted()
  682. else:
  683. key = self.voronoi_shapes.add(tolerance=self.drawing_tolerance, layer=0, **kwargs)
  684. return key
  685. def calculate_voronoi_diagram(self, pts):
  686. env = self.solid_geo.envelope
  687. # fact = 1 if self.units == 'MM' else 0.039
  688. # env = env.buffer(fact).exterior
  689. new_pts = deepcopy(pts)
  690. for pt_index in range(len(pts)):
  691. try:
  692. pts_union = MultiPoint(pts)
  693. voronoi_union = voronoi_diagram(geom=pts_union, envelope=env)
  694. break
  695. except Exception as e:
  696. log.debug("CNCJobObject.calculate_voronoi_diagram() --> %s" % str(e))
  697. new_pts[pt_index] = affinity.translate(
  698. new_pts[pt_index], random.random() * 1e-07, random.random() * 1e-07)
  699. pts_union = MultiPoint(new_pts)
  700. voronoi_union = voronoi_diagram(geom=pts_union, envelope=env)
  701. for pt_key in list(self.al_geometry_dict.keys()):
  702. for poly in voronoi_union:
  703. if self.al_geometry_dict[pt_key]['point'].within(poly):
  704. self.al_geometry_dict[pt_key]['geo'] = poly
  705. # To be called after clicking on the plot.
  706. def on_mouse_click_release(self, event):
  707. if self.app.is_legacy is False:
  708. event_pos = event.pos
  709. # event_is_dragging = event.is_dragging
  710. right_button = 2
  711. else:
  712. event_pos = (event.xdata, event.ydata)
  713. # event_is_dragging = self.app.plotcanvas.is_dragging
  714. right_button = 3
  715. try:
  716. x = float(event_pos[0])
  717. y = float(event_pos[1])
  718. except TypeError:
  719. return
  720. event_pos = (x, y)
  721. # do paint single only for left mouse clicks
  722. if event.button == 1:
  723. pos = self.app.plotcanvas.translate_coords(event_pos)
  724. # use the snapped position as reference
  725. snapped_pos = self.app.geo_editor.snap(pos[0], pos[1])
  726. probe_pt = Point(snapped_pos)
  727. if not self.al_geometry_dict:
  728. new_dict = {
  729. 'point': probe_pt,
  730. 'geo': None,
  731. 'height': 0.0
  732. }
  733. self.al_geometry_dict[1] = deepcopy(new_dict)
  734. else:
  735. int_keys = [int(k) for k in self.al_geometry_dict.keys()]
  736. new_id = max(int_keys) + 1
  737. new_dict = {
  738. 'point': probe_pt,
  739. 'geo': None,
  740. 'height': 0.0
  741. }
  742. self.al_geometry_dict[new_id] = deepcopy(new_dict)
  743. # rebuild the al table
  744. self.build_al_table_sig.emit()
  745. radius = 0.3 if self.units == 'MM' else 0.012
  746. probe_pt_buff = probe_pt.buffer(radius)
  747. self.plot_voronoi(geometry=probe_pt_buff, visibility=True, custom_color="#0000FFFA")
  748. self.app.inform.emit(_("Added a Probe Point... Click again to add another or right click to finish ..."))
  749. # if RMB then we exit
  750. elif event.button == right_button and self.mouse_is_dragging is False:
  751. if self.app.is_legacy is False:
  752. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  753. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  754. else:
  755. self.app.plotcanvas.graph_event_disconnect(self.kp)
  756. self.app.plotcanvas.graph_event_disconnect(self.mr)
  757. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  758. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  759. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  760. self.app.on_mouse_click_release_over_plot)
  761. # signal that the mouse events are disconnected from local methods
  762. self.mouse_events_connected = False
  763. # restore selection
  764. self.app.defaults['global_selection_shape'] = self.old_selection_state
  765. self.app.inform.emit(_("Finished adding Probe Points..."))
  766. pts_list = []
  767. for k in self.al_geometry_dict:
  768. pts_list.append(self.al_geometry_dict[k]['point'])
  769. self.calculate_voronoi_diagram(pts=pts_list)
  770. self.probing_gcode_text = self.probing_gcode()
  771. # rebuild the al table
  772. self.build_al_table_sig.emit()
  773. # clear probe shapes
  774. self.plot_voronoi(None, False)
  775. def on_key_press(self, event):
  776. # events out of the self.app.collection view (it's about Project Tab) are of type int
  777. if type(event) is int:
  778. key = event
  779. # events from the GUI are of type QKeyEvent
  780. elif type(event) == QtGui.QKeyEvent:
  781. key = event.key()
  782. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  783. key = event.key
  784. key = QtGui.QKeySequence(key)
  785. # check for modifiers
  786. key_string = key.toString().lower()
  787. if '+' in key_string:
  788. mod, __, key_text = key_string.rpartition('+')
  789. if mod.lower() == 'ctrl':
  790. # modifiers = QtCore.Qt.ControlModifier
  791. pass
  792. elif mod.lower() == 'alt':
  793. # modifiers = QtCore.Qt.AltModifier
  794. pass
  795. elif mod.lower() == 'shift':
  796. # modifiers = QtCore.Qt.ShiftModifier
  797. pass
  798. else:
  799. # modifiers = QtCore.Qt.NoModifier
  800. pass
  801. key = QtGui.QKeySequence(key_text)
  802. # events from Vispy are of type KeyEvent
  803. else:
  804. key = event.key
  805. # Escape = Deselect All
  806. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  807. if self.mouse_events_connected is True:
  808. self.mouse_events_connected = False
  809. if self.app.is_legacy is False:
  810. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  811. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  812. else:
  813. self.app.plotcanvas.graph_event_disconnect(self.kp)
  814. self.app.plotcanvas.graph_event_disconnect(self.mr)
  815. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  816. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  817. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  818. self.app.on_mouse_click_release_over_plot)
  819. if self.ui.big_cursor_cb.get_value():
  820. # restore cursor
  821. self.app.on_cursor_type(val=self.old_cursor_type)
  822. # restore selection
  823. self.app.defaults['global_selection_shape'] = self.old_selection_state
  824. # Grid toggle
  825. if key == QtCore.Qt.Key_G or key == 'G':
  826. self.app.ui.grid_snap_btn.trigger()
  827. # Jump to coords
  828. if key == QtCore.Qt.Key_J or key == 'J':
  829. l_x, l_y = self.app.on_jump_to()
  830. def on_autolevelling(self, state):
  831. self.ui.al_frame.show() if state else self.ui.al_frame.hide()
  832. self.app.defaults["cncjob_al_status"] = True if state else False
  833. def on_show_al_table(self, state):
  834. self.ui.al_probe_points_table.show() if state else self.ui.al_probe_points_table.hide()
  835. def on_mode_radio(self, val):
  836. # reset al table
  837. self.ui.al_probe_points_table.setRowCount(0)
  838. # reset the al dict
  839. self.al_geometry_dict.clear()
  840. # reset Voronoi Shapes
  841. self.voronoi_shapes.clear(update=True)
  842. # build AL table
  843. self.build_al_table()
  844. if val == "manual":
  845. self.ui.al_rows_entry.setDisabled(True)
  846. self.ui.al_rows_label.setDisabled(True)
  847. self.ui.al_columns_entry.setDisabled(True)
  848. self.ui.al_columns_label.setDisabled(True)
  849. else:
  850. self.ui.al_rows_entry.setDisabled(False)
  851. self.ui.al_rows_label.setDisabled(False)
  852. self.ui.al_columns_entry.setDisabled(False)
  853. self.ui.al_columns_label.setDisabled(False)
  854. def on_controller_change(self):
  855. if self.ui.al_controller_combo.get_value() == 'GRBL':
  856. self.ui.h_gcode_button.hide()
  857. self.ui.view_h_gcode_button.hide()
  858. self.ui.import_heights_button.hide()
  859. self.ui.grbl_frame.show()
  860. self.on_search_ports(muted=True)
  861. else:
  862. self.ui.h_gcode_button.show()
  863. self.ui.view_h_gcode_button.show()
  864. self.ui.import_heights_button.show()
  865. self.ui.grbl_frame.hide()
  866. # if the is empty then there is a chance that we've added probe points but the GRBL controller was selected
  867. # therefore no Probing GCode was genrated (it is different for GRBL on how it gets it's Probing GCode
  868. if not self.probing_gcode_text or self.probing_gcode_text == '':
  869. # generate Probing GCode
  870. self.probing_gcode_text = self.probing_gcode()
  871. def list_serial_ports(self):
  872. """
  873. Lists serial port names.
  874. From here: https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
  875. :raises EnvironmentError: On unsupported or unknown platforms
  876. :returns: A list of the serial ports available on the system
  877. """
  878. if sys.platform.startswith('win'):
  879. ports = ['COM%s' % (i + 1) for i in range(256)]
  880. elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
  881. # this excludes your current terminal "/dev/tty"
  882. ports = glob.glob('/dev/tty[A-Za-z]*')
  883. elif sys.platform.startswith('darwin'):
  884. ports = glob.glob('/dev/tty.*')
  885. else:
  886. raise EnvironmentError('Unsupported platform')
  887. result = []
  888. s = serial.Serial()
  889. for port in ports:
  890. s.port = port
  891. try:
  892. s.open()
  893. s.close()
  894. result.append(port)
  895. except (OSError, serial.SerialException):
  896. # result.append(port + " (in use)")
  897. pass
  898. return result
  899. def on_search_ports(self, muted=None):
  900. port_list = self.list_serial_ports()
  901. self.ui.com_list_combo.clear()
  902. self.ui.com_list_combo.addItems(port_list)
  903. if muted is not True:
  904. self.app.inform.emit('[WARNING_NOTCL] %s' % _("COM list updated ..."))
  905. def on_connect_grbl(self):
  906. port_name = self.ui.com_list_combo.currentText()
  907. if " (" in port_name:
  908. port_name = port_name.rpartition(" (")[0]
  909. baudrate = int(self.ui.baudrates_list_combo.currentText())
  910. try:
  911. self.grbl_ser_port = serial.serial_for_url(port_name, baudrate,
  912. bytesize=serial.EIGHTBITS,
  913. parity=serial.PARITY_NONE,
  914. stopbits=serial.STOPBITS_ONE,
  915. timeout=0.1,
  916. xonxoff=False,
  917. rtscts=False)
  918. # Toggle DTR to reset the controller loaded with GRBL (Arduino, ESP32, etc)
  919. try:
  920. self.grbl_ser_port.dtr = False
  921. except IOError:
  922. pass
  923. self.grbl_ser_port.reset_input_buffer()
  924. try:
  925. self.grbl_ser_port.dtr = True
  926. except IOError:
  927. pass
  928. answer = self.wake_grbl()
  929. answer = ['ok'] # hack for development without a GRBL controller connected
  930. for line in answer:
  931. if 'ok' in line.lower():
  932. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: seagreen;}")
  933. self.ui.com_connect_button.setText(_("Connected"))
  934. self.ui.controller_reset_button.setDisabled(False)
  935. for idx in range(self.ui.al_toolbar.count()):
  936. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  937. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('seagreen'))
  938. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  939. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  940. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  941. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  942. self.app.inform.emit("%s: %s" % (_("Port connected"), port_name))
  943. return
  944. self.grbl_ser_port.close()
  945. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to GRBL on port"), port_name))
  946. except serial.SerialException:
  947. self.grbl_ser_port = serial.Serial()
  948. self.grbl_ser_port.port = port_name
  949. self.grbl_ser_port.close()
  950. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: red;}")
  951. self.ui.com_connect_button.setText(_("Disconnected"))
  952. self.ui.controller_reset_button.setDisabled(True)
  953. for idx in range(self.ui.al_toolbar.count()):
  954. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  955. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  956. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  957. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  958. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  959. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  960. self.app.inform.emit("%s: %s" % (_("Port is connected. Disconnecting"), port_name))
  961. except Exception:
  962. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to port"), port_name))
  963. def on_add_baudrate_grbl(self):
  964. new_bd = str(self.ui.new_baudrate_entry.get_value())
  965. if int(new_bd) >= 40 and new_bd not in self.ui.baudrates_list_combo.model().stringList():
  966. self.ui.baudrates_list_combo.addItem(new_bd)
  967. self.ui.baudrates_list_combo.setCurrentText(new_bd)
  968. def on_delete_baudrate_grbl(self):
  969. current_idx = self.ui.baudrates_list_combo.currentIndex()
  970. self.ui.baudrates_list_combo.removeItem(current_idx)
  971. def wake_grbl(self):
  972. # Wake up grbl
  973. self.grbl_ser_port.write("\r\n\r\n".encode('utf-8'))
  974. # Wait for GRBL controller to initialize
  975. time.sleep(1)
  976. grbl_out = deepcopy(self.grbl_ser_port.readlines())
  977. self.grbl_ser_port.reset_input_buffer()
  978. return grbl_out
  979. def on_send_grbl_command(self):
  980. cmd = self.ui.grbl_command_entry.get_value()
  981. # show the Shell Dock
  982. self.app.ui.shell_dock.show()
  983. def worker_task():
  984. with self.app.proc_container.new(_("Sending GCode...")):
  985. self.send_grbl_command(command=cmd)
  986. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  987. def send_grbl_command(self, command, echo=True):
  988. """
  989. :param command: GCode command
  990. :type command: str
  991. :param echo: if to send a '\n' char after
  992. :type echo: bool
  993. :return: the text returned by the GRBL controller after each command
  994. :rtype: str
  995. """
  996. cmd = command.strip()
  997. if echo:
  998. self.app.inform_shell[str, bool].emit(cmd, False)
  999. # Send Gcode command to GRBL
  1000. snd = cmd + '\n'
  1001. self.grbl_ser_port.write(snd.encode('utf-8'))
  1002. grbl_out = self.grbl_ser_port.readlines()
  1003. if not grbl_out:
  1004. self.app.inform_shell[str, bool].emit('\t\t\t: No answer\n', False)
  1005. result = ''
  1006. for line in grbl_out:
  1007. if echo:
  1008. try:
  1009. self.app.inform_shell.emit('\t\t\t: ' + line.decode('utf-8').strip().upper())
  1010. except Exception as e:
  1011. log.debug("CNCJobObject.send_grbl_command() --> %s" % str(e))
  1012. if 'ok' in line:
  1013. result = grbl_out
  1014. return result
  1015. def send_grbl_block(self, command, echo=True):
  1016. stripped_cmd = command.strip()
  1017. for l in stripped_cmd.split('\n'):
  1018. if echo:
  1019. self.app.inform_shell[str, bool].emit(l, False)
  1020. # Send Gcode block to GRBL
  1021. snd = l + '\n'
  1022. self.grbl_ser_port.write(snd.encode('utf-8'))
  1023. grbl_out = self.grbl_ser_port.readlines()
  1024. for line in grbl_out:
  1025. if echo:
  1026. try:
  1027. self.app.inform_shell.emit(' : ' + line.decode('utf-8').strip().upper())
  1028. except Exception as e:
  1029. log.debug("CNCJobObject.send_grbl_block() --> %s" % str(e))
  1030. def get_grbl_parameter(self, param):
  1031. if '$' in param:
  1032. param = param.replace('$','')
  1033. snd = '$$\n'
  1034. self.grbl_ser_port.write(snd.encode('utf-8'))
  1035. grbl_out = self.grbl_ser_port.readlines()
  1036. for line in grbl_out:
  1037. decoded_line = line.decode('utf-8')
  1038. par = '$%s' % str(param)
  1039. if par in decoded_line:
  1040. result = float(decoded_line.rpartition('=')[2])
  1041. self.app.shell_message("GRBL Parameter: %s = %s" % (str(param), str(result)), show=True)
  1042. return result
  1043. def on_jog(self, direction=None):
  1044. if direction is None:
  1045. return
  1046. cmd = ''
  1047. step = self.ui.jog_step_entry.get_value(),
  1048. feedrate = self.ui.jog_fr_entry.get_value()
  1049. travelz = float(self.app.defaults["cncjob_al_grbl_travelz"])
  1050. if direction == 'xplus':
  1051. cmd = "$J=G91 %s X%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1052. if direction == 'xminus':
  1053. cmd = "$J=G91 %s X-%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1054. if direction == 'yplus':
  1055. cmd = "$J=G91 %s Y%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1056. if direction == 'yminus':
  1057. cmd = "$J=G91 %s Y-%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1058. if direction == 'zplus':
  1059. cmd = "$J=G91 %s Z%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1060. if direction == 'zminus':
  1061. cmd = "$J=G91 %s Z-%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  1062. if direction == 'origin':
  1063. cmd = "$J=G90 %s Z%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(travelz), str(feedrate))
  1064. self.send_grbl_command(command=cmd, echo=False)
  1065. cmd = "$J=G90 %s X0.0 Y0.0 F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(feedrate))
  1066. self.send_grbl_command(command=cmd, echo=False)
  1067. return
  1068. self.send_grbl_command(command=cmd, echo=False)
  1069. def on_grbl_zero(self, axis):
  1070. current_mode = self.get_grbl_parameter('10')
  1071. if current_mode is None:
  1072. return
  1073. cmd = '$10=0'
  1074. self.send_grbl_command(command=cmd, echo=False)
  1075. if axis == 'x':
  1076. cmd = 'G10 L2 P1 X0'
  1077. elif axis == 'y':
  1078. cmd = 'G10 L2 P1 Y0'
  1079. elif axis == 'z':
  1080. cmd = 'G10 L2 P1 Z0'
  1081. else:
  1082. # all
  1083. cmd = 'G10 L2 P1 X0 Y0 Z0'
  1084. self.send_grbl_command(command=cmd, echo=False)
  1085. # restore previous mode
  1086. cmd = '$10=%d' % int(current_mode)
  1087. self.send_grbl_command(command=cmd, echo=False)
  1088. def on_grbl_homing(self):
  1089. cmd = '$H'
  1090. self.app.inform.emit("%s" % _("GRBL is doing a home cycle."))
  1091. self.wake_grbl()
  1092. self.send_grbl_command(command=cmd)
  1093. def on_grbl_reset(self):
  1094. cmd = '\x18'
  1095. self.app.inform.emit("%s" % _("GRBL software reset was sent."))
  1096. self.wake_grbl()
  1097. self.send_grbl_command(command=cmd)
  1098. def on_grbl_pause_resume(self, checked):
  1099. if checked is False:
  1100. cmd = '~'
  1101. self.send_grbl_command(command=cmd)
  1102. self.app.inform.emit("%s" % _("GRBL resumed."))
  1103. else:
  1104. cmd = '!'
  1105. self.send_grbl_command(command=cmd)
  1106. self.app.inform.emit("%s" % _("GRBL paused."))
  1107. def probing_gcode(self):
  1108. """
  1109. :return: Probing GCode
  1110. :rtype: str
  1111. """
  1112. p_gcode = ''
  1113. header = ''
  1114. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1115. coords = []
  1116. for id_key, value in self.al_geometry_dict.items():
  1117. x = value['point'].x
  1118. y = value['point'].y
  1119. coords.append(
  1120. (
  1121. self.app.dec_format(x, dec=self.app.decimals),
  1122. self.app.dec_format(y, dec=self.app.decimals)
  1123. )
  1124. )
  1125. pr_travel = self.ui.ptravelz_entry.get_value()
  1126. probe_fr = self.ui.feedrate_probe_entry.get_value()
  1127. pr_depth = self.ui.pdepth_entry.get_value()
  1128. controller = self.ui.al_controller_combo.get_value()
  1129. header += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1130. (str(self.app.version), str(self.app.version_date)) + '\n'
  1131. header += '(This is a autolevelling probing GCode.)\n' \
  1132. '(Make sure that before you start the job you first do a zero for all axis.)\n\n'
  1133. header += '(Name: ' + str(self.options['name']) + ')\n'
  1134. header += '(Type: ' + "Autolevelling Probing GCode " + ')\n'
  1135. header += '(Units: ' + self.units.upper() + ')\n'
  1136. header += '(Created on ' + time_str + ')\n'
  1137. # commands
  1138. if controller == 'MACH3':
  1139. probing_command = 'G31'
  1140. # probing_var = '#2002'
  1141. openfile_command = 'M40'
  1142. closefile_command = 'M41'
  1143. elif controller == 'MACH4':
  1144. probing_command = 'G31'
  1145. # probing_var = '#5063'
  1146. openfile_command = 'M40'
  1147. closefile_command = 'M41'
  1148. elif controller == 'LinuxCNC':
  1149. probing_command = 'G38.2'
  1150. # probing_var = '#5422'
  1151. openfile_command = '(PROBEOPEN a_probing_points_file.txt)'
  1152. closefile_command = '(PROBECLOSE)'
  1153. elif controller == 'GRBL':
  1154. # do nothing here because the Probing GCode for GRBL is obtained differently
  1155. return
  1156. else:
  1157. log.debug("CNCJobObject.probing_gcode() -> controller not supported")
  1158. return
  1159. # #############################################################################################################
  1160. # ########################### GCODE construction ##############################################################
  1161. # #############################################################################################################
  1162. # header
  1163. p_gcode += header + '\n'
  1164. # supplementary message for LinuxCNC
  1165. if controller == 'LinuxCNC':
  1166. p_gcode += "The file with the stored probing points can be found\n" \
  1167. "in the configuration folder for LinuxCNC.\n" \
  1168. "The name of the file is: a_probing_points_file.txt.\n"
  1169. # units
  1170. p_gcode += 'G21\n' if self.units == 'MM' else 'G20\n'
  1171. # reference mode = absolute
  1172. p_gcode += 'G90\n'
  1173. # open a new file
  1174. p_gcode += openfile_command + '\n'
  1175. # move to safe height (probe travel Z)
  1176. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1177. # probing points
  1178. for idx, xy_tuple in enumerate(coords, 1): # index starts from 1
  1179. x = xy_tuple[0]
  1180. y = xy_tuple[1]
  1181. # move to probing point
  1182. p_gcode += "G0 X%sY%s\n" % (
  1183. str(self.app.dec_format(x, self.coords_decimals)),
  1184. str(self.app.dec_format(y, self.coords_decimals))
  1185. )
  1186. # do the probing
  1187. p_gcode += "%s Z%s F%s\n" % (
  1188. probing_command,
  1189. str(self.app.dec_format(pr_depth, self.coords_decimals)),
  1190. str(self.app.dec_format(probe_fr, self.fr_decimals)),
  1191. )
  1192. # store in a global numeric variable the value of the detected probe Z
  1193. # I offset the global numeric variable by 500 so it does not conflict with something else
  1194. # temp_var = int(idx + 500)
  1195. # p_gcode += "#%d = %s\n" % (temp_var, probing_var)
  1196. # move to safe height (probe travel Z)
  1197. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1198. # close the file
  1199. p_gcode += closefile_command + '\n'
  1200. # finish the GCode
  1201. p_gcode += 'M2'
  1202. return p_gcode
  1203. def on_save_probing_gcode(self):
  1204. lines = StringIO(self.probing_gcode_text)
  1205. _filter_ = self.app.defaults['cncjob_save_filters']
  1206. name = "probing_gcode"
  1207. try:
  1208. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1209. filename, _f = FCFileSaveDialog.get_saved_filename(
  1210. caption=_("Export Code ..."),
  1211. directory=dir_file_to_save,
  1212. ext_filter=_filter_
  1213. )
  1214. except TypeError:
  1215. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1216. if filename == '':
  1217. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1218. return
  1219. else:
  1220. try:
  1221. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1222. if force_windows_line_endings and sys.platform != 'win32':
  1223. with open(filename, 'w', newline='\r\n') as f:
  1224. for line in lines:
  1225. f.write(line)
  1226. else:
  1227. with open(filename, 'w') as f:
  1228. for line in lines:
  1229. f.write(line)
  1230. except FileNotFoundError:
  1231. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1232. return
  1233. except PermissionError:
  1234. self.app.inform.emit(
  1235. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1236. "Most likely another app is holding the file open and not accessible.")
  1237. )
  1238. return 'fail'
  1239. def on_edit_probing_gcode(self):
  1240. self.app.proc_container.view.set_busy(_("Loading..."))
  1241. gco = self.probing_gcode_text
  1242. if gco is None or gco == '':
  1243. self.app.inform.emit('[WARNING_NOTCL] %s...' % _('There is nothing to view'))
  1244. return
  1245. self.gcode_viewer_tab = AppTextEditor(app=self.app, plain_text=True)
  1246. # add the tab if it was closed
  1247. self.app.ui.plot_tab_area.addTab(self.gcode_viewer_tab, '%s' % _("Code Viewer"))
  1248. self.gcode_viewer_tab.setObjectName('code_viewer_tab')
  1249. # delete the absolute and relative position and messages in the infobar
  1250. self.app.ui.position_label.setText("")
  1251. self.app.ui.rel_position_label.setText("")
  1252. self.gcode_viewer_tab.code_editor.completer_enable = False
  1253. self.gcode_viewer_tab.buttonRun.hide()
  1254. # Switch plot_area to CNCJob tab
  1255. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_viewer_tab)
  1256. self.gcode_viewer_tab.t_frame.hide()
  1257. # then append the text from GCode to the text editor
  1258. try:
  1259. self.gcode_viewer_tab.load_text(gco, move_to_start=True, clear_text=True)
  1260. except Exception as e:
  1261. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1262. return
  1263. self.gcode_viewer_tab.t_frame.show()
  1264. self.app.proc_container.view.set_idle()
  1265. self.gcode_viewer_tab.buttonSave.hide()
  1266. self.gcode_viewer_tab.buttonOpen.hide()
  1267. self.gcode_viewer_tab.buttonPrint.hide()
  1268. self.gcode_viewer_tab.buttonPreview.hide()
  1269. self.gcode_viewer_tab.buttonReplace.hide()
  1270. self.gcode_viewer_tab.sel_all_cb.hide()
  1271. self.gcode_viewer_tab.entryReplace.hide()
  1272. self.gcode_viewer_tab.button_update_code.show()
  1273. # self.gcode_viewer_tab.code_editor.setReadOnly(True)
  1274. self.gcode_viewer_tab.button_update_code.clicked.connect(self.on_update_probing_gcode)
  1275. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Viewer'))
  1276. def on_update_probing_gcode(self):
  1277. self.probing_gcode_text = self.gcode_viewer_tab.code_editor.toPlainText()
  1278. def on_import_height_map(self):
  1279. """
  1280. Import the height map file into the app
  1281. :return:
  1282. :rtype:
  1283. """
  1284. _filter_ = "Text File .txt (*.txt);;All Files (*.*)"
  1285. try:
  1286. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1287. directory=self.app.get_last_folder(),
  1288. filter=_filter_)
  1289. except TypeError:
  1290. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1291. filter=_filter_)
  1292. filename = str(filename)
  1293. if filename == '':
  1294. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1295. else:
  1296. self.app.worker_task.emit({'fcn': self.import_height_map, 'params': [filename]})
  1297. def import_height_map(self, filename):
  1298. """
  1299. :param filename:
  1300. :type filename:
  1301. :return:
  1302. :rtype:
  1303. """
  1304. stream = ''
  1305. try:
  1306. if filename:
  1307. with open(filename, 'r') as f:
  1308. stream = f.readlines()
  1309. else:
  1310. return
  1311. except IOError:
  1312. log.error("Failed to open height map file: %s" % filename)
  1313. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open height map file"), filename))
  1314. return
  1315. idx = 0
  1316. for line in stream:
  1317. if line != '':
  1318. idx += 1
  1319. line = line.replace(' ', ',').replace('\n', '').split(',')
  1320. if idx not in self.al_geometry_dict:
  1321. self.al_geometry_dict[idx] = {}
  1322. self.al_geometry_dict[idx]['height'] = float(line[2])
  1323. if 'point' not in self.al_geometry_dict[idx]:
  1324. x = float(line[0])
  1325. y = float(line[1])
  1326. self.al_geometry_dict[idx]['point'] = Point((x, y))
  1327. self.build_al_table_sig.emit()
  1328. def on_grbl_autolevel(self):
  1329. # show the Shell Dock
  1330. self.app.ui.shell_dock.show()
  1331. def worker_task():
  1332. with self.app.proc_container.new(_("Sending GCode...")):
  1333. probe_result = ''
  1334. pr_travelz = str(self.ui.ptravelz_entry.get_value())
  1335. probe_fr = str(self.ui.feedrate_probe_entry.get_value())
  1336. pr_depth = str(self.ui.pdepth_entry.get_value())
  1337. cmd = 'G21\n'
  1338. self.send_grbl_command(command=cmd)
  1339. cmd = 'G90\n'
  1340. self.send_grbl_command(command=cmd)
  1341. for pt_key in self.al_geometry_dict:
  1342. x = str(self.al_geometry_dict[pt_key]['point'].x)
  1343. y = str(self.al_geometry_dict[pt_key]['point'].y)
  1344. cmd = 'G0 Z%s\n' % pr_travelz
  1345. self.send_grbl_command(command=cmd)
  1346. cmd = 'G0 X%s Y%s\n' % (x, y)
  1347. self.send_grbl_command(command=cmd)
  1348. cmd = 'G38.2 Z%s F%s' % (pr_depth, probe_fr)
  1349. output = self.send_grbl_command(command=cmd)
  1350. probe_result += output + '\n'
  1351. cmd = 'M2\n'
  1352. self.send_grbl_command(command=cmd)
  1353. self.app.inform.emit('%s' % _("Finished probing. Doing the autolevelling."))
  1354. # apply autolevel here
  1355. self.do_grbl_autolevel()
  1356. self.app.inform.emit('%s' % _("Sending probing GCode to the GRBL controller."))
  1357. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  1358. def do_grbl_autolevel(self):
  1359. # TODO here we call the autovell method
  1360. self.app.inform.emit('%s' % _("Finished autolevelling."))
  1361. def on_updateplot_button_click(self, *args):
  1362. """
  1363. Callback for the "Updata Plot" button. Reads the form for updates
  1364. and plots the object.
  1365. """
  1366. self.read_form()
  1367. self.on_plot_kind_change()
  1368. def on_plot_kind_change(self):
  1369. kind = self.ui.cncplot_method_combo.get_value()
  1370. def worker_task():
  1371. with self.app.proc_container.new(_("Plotting...")):
  1372. self.plot(kind=kind)
  1373. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  1374. def on_exportgcode_button_click(self):
  1375. """
  1376. Handler activated by a button clicked when exporting GCode.
  1377. :param args:
  1378. :return:
  1379. """
  1380. self.app.defaults.report_usage("cncjob_on_exportgcode_button")
  1381. self.read_form()
  1382. name = self.app.collection.get_active().options['name']
  1383. save_gcode = False
  1384. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  1385. _filter_ = "RML1 Files .rol (*.rol);;All Files (*.*)"
  1386. elif 'hpgl' in self.pp_geometry_name:
  1387. _filter_ = "HPGL Files .plt (*.plt);;All Files (*.*)"
  1388. else:
  1389. save_gcode = True
  1390. _filter_ = self.app.defaults['cncjob_save_filters']
  1391. try:
  1392. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1393. filename, _f = FCFileSaveDialog.get_saved_filename(
  1394. caption=_("Export Code ..."),
  1395. directory=dir_file_to_save,
  1396. ext_filter=_filter_
  1397. )
  1398. except TypeError:
  1399. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1400. self.export_gcode_handler(filename, is_gcode=save_gcode)
  1401. def export_gcode_handler(self, filename, is_gcode=True):
  1402. preamble = ''
  1403. postamble = ''
  1404. filename = str(filename)
  1405. if filename == '':
  1406. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1407. return
  1408. else:
  1409. if is_gcode is True:
  1410. used_extension = filename.rpartition('.')[2]
  1411. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  1412. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  1413. self.ui.name_entry.set_value(new_name)
  1414. self.on_name_activate(silent=True)
  1415. try:
  1416. if self.ui.snippets_cb.get_value():
  1417. preamble = self.append_snippet
  1418. postamble = self.prepend_snippet
  1419. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  1420. except Exception as err:
  1421. log.debug("CNCJobObject.export_gcode_handler() --> %s" % str(err))
  1422. gc = self.export_gcode(filename)
  1423. if gc == 'fail':
  1424. return
  1425. if self.app.defaults["global_open_style"] is False:
  1426. self.app.file_opened.emit("gcode", filename)
  1427. self.app.file_saved.emit("gcode", filename)
  1428. self.app.inform.emit('[success] %s: %s' % (_("File saved to"), filename))
  1429. def on_edit_code_click(self, *args):
  1430. """
  1431. Handler activated by a button clicked when reviewing GCode.
  1432. :param args:
  1433. :return:
  1434. """
  1435. self.app.proc_container.view.set_busy(_("Loading..."))
  1436. preamble = self.append_snippet
  1437. postamble = self.prepend_snippet
  1438. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  1439. if gco == 'fail':
  1440. return
  1441. else:
  1442. self.app.gcode_edited = gco
  1443. self.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  1444. # add the tab if it was closed
  1445. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Review"))
  1446. self.gcode_editor_tab.setObjectName('code_editor_tab')
  1447. # delete the absolute and relative position and messages in the infobar
  1448. self.app.ui.position_label.setText("")
  1449. self.app.ui.rel_position_label.setText("")
  1450. self.gcode_editor_tab.code_editor.completer_enable = False
  1451. self.gcode_editor_tab.buttonRun.hide()
  1452. # Switch plot_area to CNCJob tab
  1453. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  1454. self.gcode_editor_tab.t_frame.hide()
  1455. # then append the text from GCode to the text editor
  1456. try:
  1457. self.gcode_editor_tab.load_text(self.app.gcode_edited.getvalue(), move_to_start=True, clear_text=True)
  1458. except Exception as e:
  1459. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1460. return
  1461. self.gcode_editor_tab.t_frame.show()
  1462. self.app.proc_container.view.set_idle()
  1463. self.gcode_editor_tab.buttonSave.hide()
  1464. self.gcode_editor_tab.buttonOpen.hide()
  1465. self.gcode_editor_tab.buttonPrint.hide()
  1466. self.gcode_editor_tab.buttonPreview.hide()
  1467. self.gcode_editor_tab.buttonReplace.hide()
  1468. self.gcode_editor_tab.sel_all_cb.hide()
  1469. self.gcode_editor_tab.entryReplace.hide()
  1470. self.gcode_editor_tab.code_editor.setReadOnly(True)
  1471. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  1472. def on_update_source_file(self):
  1473. self.source_file = self.gcode_editor_tab.code_editor.toPlainText()
  1474. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  1475. """
  1476. Will create a header to be added to all GCode files generated by FlatCAM
  1477. :param comment_start_symbol: A symbol to be used as the first symbol in a comment
  1478. :param comment_stop_symbol: A symbol to be used as the last symbol in a comment
  1479. :return: A string with a GCode header
  1480. """
  1481. log.debug("FlatCAMCNCJob.gcode_header()")
  1482. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1483. marlin = False
  1484. hpgl = False
  1485. probe_pp = False
  1486. gcode = ''
  1487. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  1488. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  1489. try:
  1490. for key in self.cnc_tools:
  1491. ppg = self.cnc_tools[key]['data']['ppname_g']
  1492. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  1493. marlin = True
  1494. break
  1495. if ppg == 'hpgl':
  1496. hpgl = True
  1497. break
  1498. if "toolchange_probe" in ppg.lower():
  1499. probe_pp = True
  1500. break
  1501. except KeyError:
  1502. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  1503. pass
  1504. try:
  1505. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  1506. marlin = True
  1507. except KeyError:
  1508. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1509. pass
  1510. try:
  1511. if "toolchange_probe" in self.options['ppname_e'].lower():
  1512. probe_pp = True
  1513. except KeyError:
  1514. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1515. pass
  1516. if marlin is True:
  1517. gcode += ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  1518. (str(self.app.version), str(self.app.version_date)) + '\n'
  1519. gcode += ';Name: ' + str(self.options['name']) + '\n'
  1520. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  1521. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1522. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1523. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  1524. gcode += ';Created on ' + time_str + '\n' + '\n'
  1525. elif hpgl is True:
  1526. gcode += 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  1527. (str(self.app.version), str(self.app.version_date)) + '";\n'
  1528. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  1529. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  1530. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1531. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1532. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  1533. gcode += 'CO "Created on ' + time_str + '";\n'
  1534. elif probe_pp is True:
  1535. gcode += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1536. (str(self.app.version), str(self.app.version_date)) + '\n'
  1537. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  1538. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  1539. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  1540. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  1541. 'Then zero the Z axis.)\n' + '\n'
  1542. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  1543. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  1544. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1545. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1546. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1547. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1548. else:
  1549. gcode += '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  1550. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  1551. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  1552. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  1553. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1554. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1555. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  1556. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  1557. return gcode
  1558. @staticmethod
  1559. def gcode_footer(end_command=None):
  1560. """
  1561. Will add the M02 to the end of GCode, if requested.
  1562. :param end_command: 'M02' or 'M30' - String
  1563. :return:
  1564. """
  1565. if end_command:
  1566. return end_command
  1567. else:
  1568. return 'M02'
  1569. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False, from_tcl=False):
  1570. """
  1571. This will save the GCode from the Gcode object to a file on the OS filesystem
  1572. :param filename: filename for the GCode file
  1573. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  1574. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  1575. :param to_file: if False then no actual file is saved but the app will know that a file was created
  1576. :param from_tcl: True if run from Tcl Shell
  1577. :return: None
  1578. """
  1579. # gcode = ''
  1580. # roland = False
  1581. # hpgl = False
  1582. # isel_icp = False
  1583. include_header = True
  1584. if preamble == '':
  1585. preamble = self.app.defaults["cncjob_prepend"]
  1586. if postamble == '':
  1587. preamble = self.app.defaults["cncjob_append"]
  1588. try:
  1589. if self.special_group:
  1590. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  1591. (_("This CNCJob object can't be processed because it is a"),
  1592. str(self.special_group),
  1593. _("CNCJob object")))
  1594. return 'fail'
  1595. except AttributeError:
  1596. pass
  1597. # if this dict is not empty then the object is a Geometry object
  1598. if self.cnc_tools:
  1599. first_key = next(iter(self.cnc_tools))
  1600. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  1601. # if this dict is not empty then the object is an Excellon object
  1602. if self.exc_cnc_tools:
  1603. first_key = next(iter(self.exc_cnc_tools))
  1604. include_header = self.app.preprocessors[
  1605. self.exc_cnc_tools[first_key]['data']['tools_drill_ppname_e']
  1606. ].include_header
  1607. gcode = ''
  1608. if include_header is False:
  1609. g = preamble
  1610. # detect if using multi-tool and make the Gcode summation correctly for each case
  1611. if self.multitool is True:
  1612. for tooluid_key in self.cnc_tools:
  1613. for key, value in self.cnc_tools[tooluid_key].items():
  1614. if key == 'gcode':
  1615. gcode += value
  1616. break
  1617. else:
  1618. gcode += self.gcode
  1619. g = g + gcode + postamble
  1620. else:
  1621. # search for the GCode beginning which is usually a G20 or G21
  1622. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  1623. # g_idx = gcode.rfind('G20')
  1624. #
  1625. # # if it did not find 'G20' then search for 'G21'
  1626. # if g_idx == -1:
  1627. # g_idx = gcode.rfind('G21')
  1628. #
  1629. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  1630. # if g_idx == -1:
  1631. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  1632. # return
  1633. # detect if using multi-tool and make the Gcode summation correctly for each case
  1634. if self.multitool is True:
  1635. if self.origin_kind == 'excellon':
  1636. for tooluid_key in self.exc_cnc_tools:
  1637. for key, value in self.exc_cnc_tools[tooluid_key].items():
  1638. if key == 'gcode' and value:
  1639. gcode += value
  1640. break
  1641. else:
  1642. for tooluid_key in self.cnc_tools:
  1643. for key, value in self.cnc_tools[tooluid_key].items():
  1644. if key == 'gcode' and value:
  1645. gcode += value
  1646. break
  1647. else:
  1648. gcode += self.gcode
  1649. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  1650. # detect if using a HPGL preprocessor
  1651. hpgl = False
  1652. if self.cnc_tools:
  1653. for key in self.cnc_tools:
  1654. if 'ppname_g' in self.cnc_tools[key]['data']:
  1655. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  1656. hpgl = True
  1657. break
  1658. elif self.exc_cnc_tools:
  1659. for key in self.cnc_tools:
  1660. if 'ppname_e' in self.cnc_tools[key]['data']:
  1661. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  1662. hpgl = True
  1663. break
  1664. if hpgl:
  1665. processed_gcode = ''
  1666. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  1667. for gline in gcode.splitlines():
  1668. match = pa_re.search(gline)
  1669. if match:
  1670. x_int = int(float(match.group(1)))
  1671. y_int = int(float(match.group(2)))
  1672. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  1673. processed_gcode += new_line
  1674. else:
  1675. processed_gcode += gline + '\n'
  1676. gcode = processed_gcode
  1677. g = self.gc_header + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  1678. else:
  1679. try:
  1680. g_idx = gcode.index('G94')
  1681. if preamble != '' and postamble != '':
  1682. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1683. gcode[(g_idx + 3):] + postamble + end_gcode
  1684. elif preamble == '':
  1685. g = self.gc_header + gcode[:g_idx + 3] + '\n' + \
  1686. gcode[(g_idx + 3):] + postamble + end_gcode
  1687. elif postamble == '':
  1688. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1689. gcode[(g_idx + 3):] + end_gcode
  1690. else:
  1691. g = self.gc_header + gcode[:g_idx + 3] + gcode[(g_idx + 3):] + end_gcode
  1692. except ValueError:
  1693. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1694. _("G-code does not have a G94 code.\n"
  1695. "Append Code snippet will not be used.."))
  1696. g = self.gc_header + '\n' + gcode + postamble + end_gcode
  1697. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  1698. # if self.ui.toolchange_cb.get_value() is True:
  1699. # # match = self.re_toolchange.search(g)
  1700. # if 'M6' in g:
  1701. # m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  1702. # if m6_code is None or m6_code == '':
  1703. # self.app.inform.emit(
  1704. # '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  1705. # )
  1706. # return 'fail'
  1707. #
  1708. # g = g.replace('M6', m6_code)
  1709. # self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  1710. lines = StringIO(g)
  1711. # Write
  1712. if filename is not None:
  1713. try:
  1714. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1715. if force_windows_line_endings and sys.platform != 'win32':
  1716. with open(filename, 'w', newline='\r\n') as f:
  1717. for line in lines:
  1718. f.write(line)
  1719. else:
  1720. with open(filename, 'w') as f:
  1721. for line in lines:
  1722. f.write(line)
  1723. except FileNotFoundError:
  1724. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1725. return
  1726. except PermissionError:
  1727. self.app.inform.emit(
  1728. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1729. "Most likely another app is holding the file open and not accessible.")
  1730. )
  1731. return 'fail'
  1732. elif to_file is False:
  1733. # Just for adding it to the recent files list.
  1734. if self.app.defaults["global_open_style"] is False:
  1735. self.app.file_opened.emit("cncjob", filename)
  1736. self.app.file_saved.emit("cncjob", filename)
  1737. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  1738. else:
  1739. return lines
  1740. # def on_toolchange_custom_clicked(self, signal):
  1741. # """
  1742. # Handler for clicking toolchange custom.
  1743. #
  1744. # :param signal:
  1745. # :return:
  1746. # """
  1747. #
  1748. # try:
  1749. # if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  1750. # if self.ui.toolchange_cb.get_value():
  1751. # self.ui.toolchange_cb.set_value(False)
  1752. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1753. # _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  1754. # except KeyError:
  1755. # try:
  1756. # for key in self.cnc_tools:
  1757. # ppg = self.cnc_tools[key]['data']['ppname_g']
  1758. # if 'toolchange_custom' not in str(ppg).lower():
  1759. # if self.ui.toolchange_cb.get_value():
  1760. # self.ui.toolchange_cb.set_value(False)
  1761. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1762. # _("The used preprocessor file has to have in it's name: "
  1763. # "'toolchange_custom'"))
  1764. # except KeyError:
  1765. # self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  1766. def get_gcode(self, preamble='', postamble=''):
  1767. """
  1768. We need this to be able to get_gcode separately for shell command export_gcode
  1769. :param preamble: Extra GCode added to the beginning of the GCode
  1770. :param postamble: Extra GCode added at the end of the GCode
  1771. :return: The modified GCode
  1772. """
  1773. return preamble + '\n' + self.gcode + "\n" + postamble
  1774. def get_svg(self):
  1775. # we need this to be able get_svg separately for shell command export_svg
  1776. pass
  1777. def on_plot_cb_click(self, *args):
  1778. """
  1779. Handler for clicking on the Plot checkbox.
  1780. :param args:
  1781. :return:
  1782. """
  1783. if self.muted_ui:
  1784. return
  1785. kind = self.ui.cncplot_method_combo.get_value()
  1786. self.plot(kind=kind)
  1787. self.read_form_item('plot')
  1788. self.ui_disconnect()
  1789. cb_flag = self.ui.plot_cb.isChecked()
  1790. for row in range(self.ui.cnc_tools_table.rowCount()):
  1791. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  1792. if cb_flag:
  1793. table_cb.setChecked(True)
  1794. else:
  1795. table_cb.setChecked(False)
  1796. self.ui_connect()
  1797. def on_plot_cb_click_table(self):
  1798. """
  1799. Handler for clicking the plot checkboxes added into a Table on each row. Purpose: toggle visibility for the
  1800. tool/aperture found on that row.
  1801. :return:
  1802. """
  1803. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1804. self.ui_disconnect()
  1805. # cw = self.sender()
  1806. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  1807. # cw_row = cw_index.row()
  1808. kind = self.ui.cncplot_method_combo.get_value()
  1809. self.shapes.clear(update=True)
  1810. if self.origin_kind == "excellon":
  1811. for r in range(self.ui.exc_cnc_tools_table.rowCount()):
  1812. row_dia = float('%.*f' % (self.decimals, float(self.ui.exc_cnc_tools_table.item(r, 1).text())))
  1813. for tooluid_key in self.exc_cnc_tools:
  1814. tooldia = float('%.*f' % (self.decimals, float(tooluid_key)))
  1815. if row_dia == tooldia:
  1816. gcode_parsed = self.exc_cnc_tools[tooluid_key]['gcode_parsed']
  1817. if self.ui.exc_cnc_tools_table.cellWidget(r, 6).isChecked():
  1818. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1819. else:
  1820. for tooluid_key in self.cnc_tools:
  1821. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1822. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1823. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  1824. for r in range(self.ui.cnc_tools_table.rowCount()):
  1825. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  1826. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  1827. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1828. self.shapes.redraw()
  1829. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1830. # if all the row plot's are enabled also enable the general plot checkbox
  1831. cb_cnt = 0
  1832. total_row = self.ui.cnc_tools_table.rowCount()
  1833. for row in range(total_row):
  1834. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  1835. cb_cnt += 1
  1836. else:
  1837. cb_cnt -= 1
  1838. if cb_cnt < total_row:
  1839. self.ui.plot_cb.setChecked(False)
  1840. else:
  1841. self.ui.plot_cb.setChecked(True)
  1842. self.ui_connect()
  1843. def plot(self, visible=None, kind='all'):
  1844. """
  1845. # Does all the required setup and returns False
  1846. # if the 'ptint' option is set to False.
  1847. :param visible: Boolean to decide if the object will be plotted as visible or disabled on canvas
  1848. :param kind: String. Can be "all" or "travel" or "cut". For CNCJob plotting
  1849. :return: None
  1850. """
  1851. if not FlatCAMObj.plot(self):
  1852. return
  1853. visible = visible if visible else self.options['plot']
  1854. # Geometry shapes plotting
  1855. try:
  1856. if self.multitool is False: # single tool usage
  1857. try:
  1858. dia_plot = float(self.options["tooldia"])
  1859. except ValueError:
  1860. # we may have a tuple with only one element and a comma
  1861. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  1862. self.plot2(tooldia=dia_plot, obj=self, visible=visible, kind=kind)
  1863. else:
  1864. # I do this so the travel lines thickness will reflect the tool diameter
  1865. # may work only for objects created within the app and not Gcode imported from elsewhere for which we
  1866. # don't know the origin
  1867. if self.origin_kind == "excellon":
  1868. if self.exc_cnc_tools:
  1869. for tooldia_key in self.exc_cnc_tools:
  1870. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  1871. gcode_parsed = self.exc_cnc_tools[tooldia_key]['gcode_parsed']
  1872. if not gcode_parsed:
  1873. continue
  1874. # gcode_parsed = self.gcode_parsed
  1875. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1876. else:
  1877. # multiple tools usage
  1878. if self.cnc_tools:
  1879. for tooluid_key in self.cnc_tools:
  1880. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1881. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1882. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1883. self.shapes.redraw()
  1884. except (ObjectDeleted, AttributeError):
  1885. self.shapes.clear(update=True)
  1886. if self.app.is_legacy is False:
  1887. self.annotation.clear(update=True)
  1888. # Annotaions shapes plotting
  1889. try:
  1890. if self.app.is_legacy is False:
  1891. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  1892. self.plot_annotations(obj=self, visible=True)
  1893. else:
  1894. self.plot_annotations(obj=self, visible=False)
  1895. except (ObjectDeleted, AttributeError):
  1896. if self.app.is_legacy is False:
  1897. self.annotation.clear(update=True)
  1898. def on_annotation_change(self):
  1899. """
  1900. Handler for toggling the annotation display by clicking a checkbox.
  1901. :return:
  1902. """
  1903. if self.app.is_legacy is False:
  1904. if self.ui.annotation_cb.get_value():
  1905. self.text_col.enabled = True
  1906. else:
  1907. self.text_col.enabled = False
  1908. # kind = self.ui.cncplot_method_combo.get_value()
  1909. # self.plot(kind=kind)
  1910. self.annotation.redraw()
  1911. else:
  1912. kind = self.ui.cncplot_method_combo.get_value()
  1913. self.plot(kind=kind)
  1914. def convert_units(self, units):
  1915. """
  1916. Units conversion used by the CNCJob objects.
  1917. :param units: Can be "MM" or "IN"
  1918. :return:
  1919. """
  1920. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  1921. factor = CNCjob.convert_units(self, units)
  1922. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  1923. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  1924. 'endz', 'toolchangez']
  1925. temp_tools_dict = {}
  1926. tool_dia_copy = {}
  1927. data_copy = {}
  1928. for tooluid_key, tooluid_value in self.cnc_tools.items():
  1929. for dia_key, dia_value in tooluid_value.items():
  1930. if dia_key == 'tooldia':
  1931. dia_value *= factor
  1932. dia_value = float('%.*f' % (self.decimals, dia_value))
  1933. tool_dia_copy[dia_key] = dia_value
  1934. if dia_key == 'offset':
  1935. tool_dia_copy[dia_key] = dia_value
  1936. if dia_key == 'offset_value':
  1937. dia_value *= factor
  1938. tool_dia_copy[dia_key] = dia_value
  1939. if dia_key == 'type':
  1940. tool_dia_copy[dia_key] = dia_value
  1941. if dia_key == 'tool_type':
  1942. tool_dia_copy[dia_key] = dia_value
  1943. if dia_key == 'data':
  1944. for data_key, data_value in dia_value.items():
  1945. # convert the form fields that are convertible
  1946. for param in param_list:
  1947. if data_key == param and data_value is not None:
  1948. data_copy[data_key] = data_value * factor
  1949. # copy the other dict entries that are not convertible
  1950. if data_key not in param_list:
  1951. data_copy[data_key] = data_value
  1952. tool_dia_copy[dia_key] = deepcopy(data_copy)
  1953. data_copy.clear()
  1954. if dia_key == 'gcode':
  1955. tool_dia_copy[dia_key] = dia_value
  1956. if dia_key == 'gcode_parsed':
  1957. tool_dia_copy[dia_key] = dia_value
  1958. if dia_key == 'solid_geometry':
  1959. tool_dia_copy[dia_key] = dia_value
  1960. # if dia_key == 'solid_geometry':
  1961. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  1962. # if dia_key == 'gcode_parsed':
  1963. # for g in dia_value:
  1964. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1965. #
  1966. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  1967. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  1968. temp_tools_dict.update({
  1969. tooluid_key: deepcopy(tool_dia_copy)
  1970. })
  1971. tool_dia_copy.clear()
  1972. self.cnc_tools.clear()
  1973. self.cnc_tools = deepcopy(temp_tools_dict)