TclCommandDrillcncjob.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. from tclCommands.TclCommand import TclCommandSignaled
  2. import collections
  3. import math
  4. import gettext
  5. import appTranslation as fcTranslate
  6. import builtins
  7. fcTranslate.apply_language('strings')
  8. if '_' not in builtins.__dict__:
  9. _ = gettext.gettext
  10. class TclCommandDrillcncjob(TclCommandSignaled):
  11. """
  12. Tcl shell command to Generates a Drill CNC Job from a Excellon Object.
  13. """
  14. # array of all command aliases, to be able use old names for backward compatibility (add_poly, add_polygon)
  15. aliases = ['drillcncjob']
  16. description = '%s %s' % ("--", "Generates a Drill CNC Job object from a Excellon Object.")
  17. # dictionary of types from Tcl command, needs to be ordered
  18. arg_names = collections.OrderedDict([
  19. ('name', str)
  20. ])
  21. # dictionary of types from Tcl command, needs to be ordered , this is for options like -optionname value
  22. option_types = collections.OrderedDict([
  23. ('drilled_dias', str),
  24. ('drillz', float),
  25. ('dpp', float),
  26. ('travelz', float),
  27. ('feedrate_z', float),
  28. ('feedrate_rapid', float),
  29. ('spindlespeed', int),
  30. ('toolchangez', float),
  31. ('toolchangexy', str),
  32. ('startz', float),
  33. ('endz', float),
  34. ('endxy', str),
  35. ('dwelltime', float),
  36. ('pp', str),
  37. ('opt_type', str),
  38. ('diatol', float),
  39. ('muted', str),
  40. ('outname', str)
  41. ])
  42. # array of mandatory options for current Tcl command: required = {'name','outname'}
  43. required = ['name']
  44. # structured help for current command, args needs to be ordered
  45. help = {
  46. 'main': "Generates a Drill CNC Job from a Excellon Object.",
  47. 'args': collections.OrderedDict([
  48. ('name', 'Name of the source object.'),
  49. ('drilled_dias',
  50. 'Comma separated tool diameters of the drills to be drilled (example: 0.6,1.0 or 3.125). '
  51. 'WARNING: No space allowed'),
  52. ('drillz', 'Drill depth into material (example: -2.0). Negative value.'),
  53. ('dpp', 'Progressive drilling into material with a specified step (example: 0.7). Positive value.'),
  54. ('travelz', 'Travel distance above material (example: 2.0).'),
  55. ('feedrate_z', 'Drilling feed rate. It is the speed on the Z axis.'),
  56. ('feedrate_rapid', 'Rapid drilling feed rate.'),
  57. ('spindlespeed', 'Speed of the spindle in rpm (example: 4000).'),
  58. ('toolchangez', 'Z distance for toolchange (example: 30.0).\n'
  59. 'If used in the command then a toolchange event will be included in gcode'),
  60. ('toolchangexy', 'The X,Y coordinates at Toolchange event in format (x, y) (example: (30.0, 15.2) or '
  61. 'without parenthesis like: 0.3,1.0). WARNING: no spaces allowed in the value.'),
  62. ('startz', 'The Z coordinate at job start (example: 30.0).'),
  63. ('endz', 'The Z coordinate at job end (example: 30.0).'),
  64. ('endxy', 'The X,Y coordinates at job end in format (x, y) (example: (2.0, 1.2) or without parenthesis'
  65. 'like: 0.3,1.0). WARNING: no spaces allowed in the value.'),
  66. ('dwelltime', 'Time to pause to allow the spindle to reach the full speed.\n'
  67. 'If it is not used in command then it will not be included'),
  68. ('pp', 'This is the Excellon preprocessor name: case_sensitive, no_quotes'),
  69. ('opt_type', 'Name of move optimization type. B by default for Basic OR-Tools, M for Metaheuristic OR-Tools'
  70. 'T from Travelling Salesman Algorithm. B and M works only for 64bit version of FlatCAM and '
  71. 'T works only for 32bit version of FlatCAM'),
  72. ('diatol', 'Tolerance. Percentange (0.0 ... 100.0) within which dias in drilled_dias will be judged to be '
  73. 'the same as the ones in the tools from the Excellon object. E.g: if in drill_dias we have a '
  74. 'diameter with value 1.0, in the Excellon we have a tool with dia = 1.05 and we set a tolerance '
  75. 'diatol = 5.0 then the drills with the dia = (0.95 ... 1.05) '
  76. 'in Excellon will be processed. Float number.'),
  77. ('muted', 'It will not put errors in the Shell or status bar. Can be True (1) or False (0).'),
  78. ('outname', 'Name of the resulting Geometry object.')
  79. ]),
  80. 'examples': ['drillcncjob test.TXT -drillz -1.5 -travelz 14 -feedrate_z 222 -feedrate_rapid 456 '
  81. '-spindlespeed 777 -toolchangez 33 -endz 22 -pp default\n'
  82. 'Usage of -feedrate_rapid matter only when the preprocessor is using it, like -marlin-.',
  83. 'drillcncjob test.DRL -drillz -1.7 -dpp 0.5 -travelz 2 -feedrate_z 800 -endxy 3,3']
  84. }
  85. def execute(self, args, unnamed_args):
  86. """
  87. execute current TCL shell command
  88. :param args: array of known named arguments and options
  89. :param unnamed_args: array of other values which were passed into command
  90. without -somename and we do not have them in known arg_names
  91. :return: None or exception
  92. """
  93. name = args['name']
  94. obj = self.app.collection.get_by_name(name)
  95. if 'outname' not in args:
  96. args['outname'] = name + "_cnc"
  97. if 'muted' in args:
  98. try:
  99. par = args['muted'].capitalize()
  100. except AttributeError:
  101. par = args['muted']
  102. muted = bool(eval(par))
  103. else:
  104. muted = False
  105. if obj is None:
  106. if muted is False:
  107. self.raise_tcl_error("Object not found: %s" % name)
  108. else:
  109. return "fail"
  110. if obj.kind != 'excellon':
  111. if muted is False:
  112. self.raise_tcl_error('Expected ExcellonObject, got %s %s.' % (name, type(obj)))
  113. else:
  114. return "fail"
  115. xmin = obj.options['xmin']
  116. ymin = obj.options['ymin']
  117. xmax = obj.options['xmax']
  118. ymax = obj.options['ymax']
  119. def job_init(job_obj, app_obj):
  120. # tools = args["tools"] if "tools" in args else 'all'
  121. try:
  122. if 'drilled_dias' in args and args['drilled_dias'] != 'all':
  123. diameters = [x.strip() for x in args['drilled_dias'].split(",") if x != '']
  124. nr_diameters = len(diameters)
  125. req_tools = set()
  126. for tool in obj.tools:
  127. for req_dia in diameters:
  128. obj_dia_form = float('%.*f' % (obj.decimals, float(obj.tools[tool]["C"])))
  129. req_dia_form = float('%.*f' % (obj.decimals, float(req_dia)))
  130. if 'diatol' in args:
  131. tolerance = args['diatol'] / 100
  132. tolerance = 0.0 if tolerance < 0.0 else tolerance
  133. tolerance = 1.0 if tolerance > 1.0 else tolerance
  134. if math.isclose(obj_dia_form, req_dia_form, rel_tol=tolerance):
  135. req_tools.add(tool)
  136. nr_diameters -= 1
  137. else:
  138. if obj_dia_form == req_dia_form:
  139. req_tools.add(tool)
  140. nr_diameters -= 1
  141. if nr_diameters > 0:
  142. if muted is False:
  143. self.raise_tcl_error("One or more tool diameters of the drills to be drilled passed to the "
  144. "TclCommand are not actual tool diameters in the Excellon object.")
  145. else:
  146. return "fail"
  147. # make a string of diameters separated by comma; this is what generate_from_excellon_by_tool() is
  148. # expecting as tools parameter
  149. tools = ','.join(req_tools)
  150. # no longer needed
  151. del args['drilled_dias']
  152. del args['diatol']
  153. # Split and put back. We are passing the whole dictionary later.
  154. # args['milled_dias'] = [x.strip() for x in args['tools'].split(",")]
  155. else:
  156. tools = 'all'
  157. except Exception as e:
  158. tools = 'all'
  159. if muted is False:
  160. self.raise_tcl_error("Bad tools: %s" % str(e))
  161. else:
  162. return "fail"
  163. used_tools_info = []
  164. used_tools_info.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  165. # populate the information's list for used tools
  166. if tools == 'all':
  167. sort = []
  168. for k, v in list(obj.tools.items()):
  169. sort.append((k, v.get('tooldia')))
  170. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  171. use_tools = [i[0] for i in sorted_tools]
  172. for tool_no in use_tools:
  173. tool_dia_used = obj.tools[tool_no]['tooldia']
  174. drill_cnt = 0 # variable to store the nr of drills per tool
  175. slot_cnt = 0 # variable to store the nr of slots per tool
  176. # Find no of drills for the current tool
  177. if 'drills' in obj.tools[tool_no] and obj.tools[tool_no]['drills']:
  178. drill_cnt = len(obj.tools[tool_no]['drills'])
  179. # Find no of slots for the current tool
  180. if 'slots' in obj.tools[tool_no] and obj.tools[tool_no]['slots']:
  181. slot_cnt = len(obj.tools[tool_no]['slots'])
  182. used_tools_info.append([str(tool_no), str(tool_dia_used), str(drill_cnt), str(slot_cnt)])
  183. drillz = args["drillz"] if "drillz" in args and args["drillz"] is not None else \
  184. obj.options["tools_drill_cutz"]
  185. if "toolchangez" in args:
  186. toolchange = True
  187. if args["toolchangez"] is not None:
  188. toolchangez = args["toolchangez"]
  189. else:
  190. toolchangez = obj.options["tools_drill_toolchangez"]
  191. else:
  192. toolchange = self.app.defaults["tools_drill_toolchange"]
  193. toolchangez = float(self.app.defaults["tools_drill_toolchangez"])
  194. if "toolchangexy" in args and args["tools_drill_toolchangexy"]:
  195. xy_toolchange = args["toolchangexy"]
  196. else:
  197. if self.app.defaults["tools_drill_toolchangexy"]:
  198. xy_toolchange = str(self.app.defaults["tools_drill_toolchangexy"])
  199. else:
  200. xy_toolchange = '0, 0'
  201. if len(eval(xy_toolchange)) != 2:
  202. self.raise_tcl_error("The entered value for 'toolchangexy' needs to have the format x,y or "
  203. "in format (x, y) - no spaces allowed. But always two comma separated values.")
  204. endz = args["endz"] if "endz" in args and args["endz"] is not None else \
  205. self.app.defaults["tools_drill_endz"]
  206. if "endxy" in args and args["endxy"]:
  207. xy_end = args["endxy"]
  208. else:
  209. if self.app.defaults["tools_drill_endxy"]:
  210. xy_end = str(self.app.defaults["tools_drill_endxy"])
  211. else:
  212. xy_end = '0, 0'
  213. if len(eval(xy_end)) != 2:
  214. self.raise_tcl_error("The entered value for 'xy_end' needs to have the format x,y or "
  215. "in format (x, y) - no spaces allowed. But always two comma separated values.")
  216. opt_type = args["opt_type"] if "opt_type" in args and args["opt_type"] else 'B'
  217. # ##########################################################################################
  218. # ################# Set parameters #########################################################
  219. # ##########################################################################################
  220. job_obj.origin_kind = 'excellon'
  221. job_obj.options['Tools_in_use'] = used_tools_info
  222. job_obj.options['type'] = 'Excellon'
  223. pp_excellon_name = args["pp"] if "pp" in args and args["pp"] else self.app.defaults["tools_drill_ppname_e"]
  224. job_obj.pp_excellon_name = pp_excellon_name
  225. job_obj.options['ppname_e'] = pp_excellon_name
  226. if 'dpp' in args:
  227. job_obj.multidepth = True
  228. if args['dpp'] is not None:
  229. job_obj.z_depthpercut = float(args['dpp'])
  230. else:
  231. job_obj.z_depthpercut = float(obj.options["dpp"])
  232. else:
  233. job_obj.multidepth = self.app.defaults["tools_drill_multidepth"]
  234. job_obj.z_depthpercut = self.app.defaults["tools_drill_depthperpass"]
  235. job_obj.z_move = float(args["travelz"]) if "travelz" in args and args["travelz"] else \
  236. self.app.defaults["tools_drill_travelz"]
  237. job_obj.feedrate = float(args["feedrate_z"]) if "feedrate_z" in args and args["feedrate_z"] else \
  238. self.app.defaults["tools_drill_feedrate_z"]
  239. job_obj.z_feedrate = float(args["feedrate_z"]) if "feedrate_z" in args and args["feedrate_z"] else \
  240. self.app.defaults["tools_drill_feedrate_z"]
  241. job_obj.feedrate_rapid = float(args["feedrate_rapid"]) \
  242. if "feedrate_rapid" in args and args["feedrate_rapid"] else \
  243. self.app.defaults["tools_drill_feedrate_rapid"]
  244. job_obj.spindlespeed = float(args["spindlespeed"]) if "spindlespeed" in args else None
  245. job_obj.spindledir = self.app.defaults['tools_drill_spindlespeed']
  246. if 'dwelltime' in args:
  247. job_obj.dwell = True
  248. if args['dwelltime'] is not None:
  249. job_obj.dwelltime = float(args['dwelltime'])
  250. else:
  251. job_obj.dwelltime = float(self.app.defaults["tools_drill_dwelltime"])
  252. else:
  253. job_obj.dwell = self.app.defaults["tools_drill_dwell"]
  254. job_obj.dwelltime = self.app.defaults["tools_drill_dwelltime"]
  255. job_obj.toolchange_xy_type = "excellon"
  256. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  257. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  258. job_obj.options['xmin'] = xmin
  259. job_obj.options['ymin'] = ymin
  260. job_obj.options['xmax'] = xmax
  261. job_obj.options['ymax'] = ymax
  262. job_obj.z_cut = float(drillz)
  263. job_obj.toolchange = toolchange
  264. job_obj.xy_toolchange = xy_toolchange
  265. job_obj.z_toolchange = float(toolchangez)
  266. if "startz" in args and args["startz"] is not None:
  267. job_obj.startz = float(args["startz"])
  268. else:
  269. if self.app.defaults["tools_drill_startz"]:
  270. job_obj.startz = self.app.defaults["tools_drill_startz"]
  271. else:
  272. job_obj.startz = self.app.defaults["tools_drill_travelz"]
  273. job_obj.endz = float(endz)
  274. job_obj.xy_end = xy_end
  275. job_obj.excellon_optimization_type = opt_type
  276. job_obj.spindledir = self.app.defaults["tools_drill_spindledir"]
  277. ret_val = job_obj.generate_from_excellon_by_tool(obj, tools, use_ui=False)
  278. job_obj.source_file = ret_val
  279. if ret_val == 'fail':
  280. return 'fail'
  281. job_obj.gc_start = ret_val[1]
  282. for t_item in job_obj.exc_cnc_tools:
  283. job_obj.exc_cnc_tools[t_item]['data']['tools_drill_offset'] = \
  284. float(job_obj.exc_cnc_tools[t_item]['offset_z']) + float(drillz)
  285. job_obj.exc_cnc_tools[t_item]['data']['tools_drill_ppname_e'] = job_obj.options['ppname_e']
  286. job_obj.gcode_parse()
  287. job_obj.create_geometry()
  288. self.app.app_obj.new_object("cncjob", args['outname'], job_init, plot=False)