FlatCAMCNCJob.py 86 KB

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