FlatCAMCNCJob.py 107 KB

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