FlatCAMCNCJob.py 109 KB

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