ToolCalibrate.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.GUIElements import FCDoubleSpinner, EvalEntry, FCCheckBox, OptionalInputSection
  10. from flatcamGUI.GUIElements import FCTable, FCComboBox, RadioSet
  11. from flatcamEditors.FlatCAMTextEditor import TextEditor
  12. from shapely.geometry import Point
  13. from shapely.geometry.base import *
  14. import math
  15. from datetime import datetime
  16. import logging
  17. import gettext
  18. import FlatCAMTranslation as fcTranslate
  19. import builtins
  20. fcTranslate.apply_language('strings')
  21. if '_' not in builtins.__dict__:
  22. _ = gettext.gettext
  23. log = logging.getLogger('base')
  24. class ToolCalibrate(FlatCAMTool):
  25. toolName = _("Calibrate Tool")
  26. def __init__(self, app):
  27. FlatCAMTool.__init__(self, app)
  28. self.app = app
  29. self.canvas = self.app.plotcanvas
  30. self.decimals = self.app.decimals
  31. # ## Title
  32. title_label = QtWidgets.QLabel("%s" % self.toolName)
  33. title_label.setStyleSheet("""
  34. QLabel
  35. {
  36. font-size: 16px;
  37. font-weight: bold;
  38. }
  39. """)
  40. self.layout.addWidget(title_label)
  41. self.layout.addWidget(QtWidgets.QLabel(''))
  42. # ## Grid Layout
  43. grid_lay = QtWidgets.QGridLayout()
  44. self.layout.addLayout(grid_lay)
  45. grid_lay.setColumnStretch(0, 0)
  46. grid_lay.setColumnStretch(1, 1)
  47. grid_lay.setColumnStretch(2, 0)
  48. step_1 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 1: Acquire Calibration Points"))
  49. step_1.setToolTip(
  50. _("Pick four points by clicking inside the drill holes.\n"
  51. "Those four points should be in the four\n"
  52. "(as much as possible) corners of the Excellon object.")
  53. )
  54. grid_lay.addWidget(step_1, 0, 0, 1, 3)
  55. self.cal_source_lbl = QtWidgets.QLabel("<b>%s:</b>" % _("Source Type"))
  56. self.cal_source_lbl.setToolTip(_("The source of calibration points.\n"
  57. "It can be:\n"
  58. "- Object -> click a hole geo for Excellon or a pad for Gerber\n"
  59. "- Free -> click freely on canvas to acquire the calibration points"))
  60. self.cal_source_radio = RadioSet([{'label': _('Object'), 'value': 'object'},
  61. {'label': _('Free'), 'value': 'free'}],
  62. stretch=False)
  63. grid_lay.addWidget(self.cal_source_lbl, 1, 0)
  64. grid_lay.addWidget(self.cal_source_radio, 1, 1, 1, 2)
  65. self.obj_type_label = QtWidgets.QLabel("%s:" % _("Object Type"))
  66. self.obj_type_combo = FCComboBox()
  67. self.obj_type_combo.addItem(_("Gerber"))
  68. self.obj_type_combo.addItem(_("Excellon"))
  69. self.obj_type_combo.setCurrentIndex(1)
  70. grid_lay.addWidget(self.obj_type_label, 2, 0)
  71. grid_lay.addWidget(self.obj_type_combo, 2, 1, 1, 2)
  72. self.object_combo = FCComboBox()
  73. self.object_combo.setModel(self.app.collection)
  74. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  75. self.object_combo.setCurrentIndex(1)
  76. self.object_label = QtWidgets.QLabel("%s:" % _("Source object selection"))
  77. self.object_label.setToolTip(
  78. _("FlatCAM Object to be used as a source for reference points.")
  79. )
  80. grid_lay.addWidget(self.object_label, 3, 0, 1, 3)
  81. grid_lay.addWidget(self.object_combo, 4, 0, 1, 3)
  82. self.points_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Calibration Points'))
  83. self.points_table_label.setToolTip(
  84. _("Contain the expected calibration points and the\n"
  85. "ones measured.")
  86. )
  87. grid_lay.addWidget(self.points_table_label, 5, 0, 1, 3)
  88. self.points_table = FCTable()
  89. self.points_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  90. # self.points_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  91. grid_lay.addWidget(self.points_table, 6, 0, 1, 3)
  92. self.points_table.setColumnCount(4)
  93. self.points_table.setHorizontalHeaderLabels(
  94. [
  95. '#',
  96. _("Name"),
  97. _("Target"),
  98. _("Found Delta")
  99. ]
  100. )
  101. self.points_table.setRowCount(8)
  102. row = 0
  103. # BOTTOM LEFT
  104. id_item_1 = QtWidgets.QTableWidgetItem('%d' % 1)
  105. flags = QtCore.Qt.ItemIsEnabled
  106. id_item_1.setFlags(flags)
  107. self.points_table.setItem(row, 0, id_item_1) # Tool name/id
  108. self.bottom_left_coordx_lbl = QtWidgets.QLabel('%s' % _('Bot Left X'))
  109. self.points_table.setCellWidget(row, 1, self.bottom_left_coordx_lbl)
  110. self.bottom_left_coordx_tgt = EvalEntry()
  111. self.points_table.setCellWidget(row, 2, self.bottom_left_coordx_tgt)
  112. self.bottom_left_coordx_tgt.setReadOnly(True)
  113. self.bottom_left_coordx_found = EvalEntry()
  114. self.points_table.setCellWidget(row, 3, self.bottom_left_coordx_found)
  115. row += 1
  116. self.bottom_left_coordy_lbl = QtWidgets.QLabel('%s' % _('Bot Left Y'))
  117. self.points_table.setCellWidget(row, 1, self.bottom_left_coordy_lbl)
  118. self.bottom_left_coordy_tgt = EvalEntry()
  119. self.points_table.setCellWidget(row, 2, self.bottom_left_coordy_tgt)
  120. self.bottom_left_coordy_tgt.setReadOnly(True)
  121. self.bottom_left_coordy_found = EvalEntry()
  122. self.points_table.setCellWidget(row, 3, self.bottom_left_coordy_found)
  123. self.bottom_left_coordx_found.set_value(_("Origin"))
  124. self.bottom_left_coordy_found.set_value(_("Origin"))
  125. self.bottom_left_coordx_found.setDisabled(True)
  126. self.bottom_left_coordy_found.setDisabled(True)
  127. row += 1
  128. # BOTTOM RIGHT
  129. id_item_2 = QtWidgets.QTableWidgetItem('%d' % 2)
  130. flags = QtCore.Qt.ItemIsEnabled
  131. id_item_2.setFlags(flags)
  132. self.points_table.setItem(row, 0, id_item_2) # Tool name/id
  133. self.bottom_right_coordx_lbl = QtWidgets.QLabel('%s' % _('Bot Right X'))
  134. self.points_table.setCellWidget(row, 1, self.bottom_right_coordx_lbl)
  135. self.bottom_right_coordx_tgt = EvalEntry()
  136. self.points_table.setCellWidget(row, 2, self.bottom_right_coordx_tgt)
  137. self.bottom_right_coordx_tgt.setReadOnly(True)
  138. self.bottom_right_coordx_found = EvalEntry()
  139. self.points_table.setCellWidget(row, 3, self.bottom_right_coordx_found)
  140. row += 1
  141. self.bottom_right_coordy_lbl = QtWidgets.QLabel('%s' % _('Bot Right Y'))
  142. self.points_table.setCellWidget(row, 1, self.bottom_right_coordy_lbl)
  143. self.bottom_right_coordy_tgt = EvalEntry()
  144. self.points_table.setCellWidget(row, 2, self.bottom_right_coordy_tgt)
  145. self.bottom_right_coordy_tgt.setReadOnly(True)
  146. self.bottom_right_coordy_found = EvalEntry()
  147. self.points_table.setCellWidget(row, 3, self.bottom_right_coordy_found)
  148. row += 1
  149. # TOP LEFT
  150. id_item_3 = QtWidgets.QTableWidgetItem('%d' % 3)
  151. flags = QtCore.Qt.ItemIsEnabled
  152. id_item_3.setFlags(flags)
  153. self.points_table.setItem(row, 0, id_item_3) # Tool name/id
  154. self.top_left_coordx_lbl = QtWidgets.QLabel('%s' % _('Top Left X'))
  155. self.points_table.setCellWidget(row, 1, self.top_left_coordx_lbl)
  156. self.top_left_coordx_tgt = EvalEntry()
  157. self.points_table.setCellWidget(row, 2, self.top_left_coordx_tgt)
  158. self.top_left_coordx_tgt.setReadOnly(True)
  159. self.top_left_coordx_found = EvalEntry()
  160. self.points_table.setCellWidget(row, 3, self.top_left_coordx_found)
  161. row += 1
  162. self.top_left_coordy_lbl = QtWidgets.QLabel('%s' % _('Top Left Y'))
  163. self.points_table.setCellWidget(row, 1, self.top_left_coordy_lbl)
  164. self.top_left_coordy_tgt = EvalEntry()
  165. self.points_table.setCellWidget(row, 2, self.top_left_coordy_tgt)
  166. self.top_left_coordy_tgt.setReadOnly(True)
  167. self.top_left_coordy_found = EvalEntry()
  168. self.points_table.setCellWidget(row, 3, self.top_left_coordy_found)
  169. row += 1
  170. # TOP RIGHT
  171. id_item_4 = QtWidgets.QTableWidgetItem('%d' % 4)
  172. flags = QtCore.Qt.ItemIsEnabled
  173. id_item_4.setFlags(flags)
  174. self.points_table.setItem(row, 0, id_item_4) # Tool name/id
  175. self.top_right_coordx_lbl = QtWidgets.QLabel('%s' % _('Top Right X'))
  176. self.points_table.setCellWidget(row, 1, self.top_right_coordx_lbl)
  177. self.top_right_coordx_tgt = EvalEntry()
  178. self.points_table.setCellWidget(row, 2, self.top_right_coordx_tgt)
  179. self.top_right_coordx_tgt.setReadOnly(True)
  180. self.top_right_coordx_found = EvalEntry()
  181. self.points_table.setCellWidget(row, 3, self.top_right_coordx_found)
  182. row += 1
  183. self.top_right_coordy_lbl = QtWidgets.QLabel('%s' % _('Top Right Y'))
  184. self.points_table.setCellWidget(row, 1, self.top_right_coordy_lbl)
  185. self.top_right_coordy_tgt = EvalEntry()
  186. self.points_table.setCellWidget(row, 2, self.top_right_coordy_tgt)
  187. self.top_right_coordy_tgt.setReadOnly(True)
  188. self.top_right_coordy_found = EvalEntry()
  189. self.points_table.setCellWidget(row, 3, self.top_right_coordy_found)
  190. vertical_header = self.points_table.verticalHeader()
  191. vertical_header.hide()
  192. self.points_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  193. horizontal_header = self.points_table.horizontalHeader()
  194. horizontal_header.setMinimumSectionSize(10)
  195. horizontal_header.setDefaultSectionSize(70)
  196. self.points_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  197. # for x in range(4):
  198. # self.points_table.resizeColumnToContents(x)
  199. self.points_table.resizeColumnsToContents()
  200. self.points_table.resizeRowsToContents()
  201. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  202. horizontal_header.resizeSection(0, 20)
  203. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Fixed)
  204. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
  205. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
  206. self.points_table.setMinimumHeight(self.points_table.getHeight() + 2)
  207. self.points_table.setMaximumHeight(self.points_table.getHeight() + 3)
  208. # ## Get Points Button
  209. self.start_button = QtWidgets.QPushButton(_("Get Points"))
  210. self.start_button.setToolTip(
  211. _("Pick four points by clicking on canvas if the source choice\n"
  212. "is 'free' or inside the object geometry if the source is 'object'.\n"
  213. "Those four points should be in the four squares of\n"
  214. "the object.")
  215. )
  216. self.start_button.setStyleSheet("""
  217. QPushButton
  218. {
  219. font-weight: bold;
  220. }
  221. """)
  222. grid_lay.addWidget(self.start_button, 7, 0, 1, 3)
  223. separator_line = QtWidgets.QFrame()
  224. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  225. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  226. grid_lay.addWidget(separator_line, 8, 0, 1, 3)
  227. grid_lay.addWidget(QtWidgets.QLabel(''), 9, 0)
  228. # STEP 2 #
  229. step_2 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 2: Verification GCode"))
  230. step_2.setToolTip(
  231. _("Generate GCode file to locate and align the PCB by using\n"
  232. "the four points acquired above.")
  233. )
  234. grid_lay.addWidget(step_2, 10, 0, 1, 3)
  235. self.gcode_title_label = QtWidgets.QLabel('<b>%s</b>' % _('GCode Parameters'))
  236. self.gcode_title_label.setToolTip(
  237. _("Parameters used when creating the GCode in this tool.")
  238. )
  239. grid_lay.addWidget(self.gcode_title_label, 11, 0, 1, 3)
  240. # Travel Z entry
  241. travelz_lbl = QtWidgets.QLabel('%s:' % _("Travel Z"))
  242. travelz_lbl.setToolTip(
  243. _("Height (Z) for travelling between the points.")
  244. )
  245. self.travelz_entry = FCDoubleSpinner()
  246. self.travelz_entry.set_range(-9999.9999, 9999.9999)
  247. self.travelz_entry.set_precision(self.decimals)
  248. self.travelz_entry.setSingleStep(0.1)
  249. grid_lay.addWidget(travelz_lbl, 12, 0)
  250. grid_lay.addWidget(self.travelz_entry, 12, 1, 1, 2)
  251. # Verification Z entry
  252. verz_lbl = QtWidgets.QLabel('%s:' % _("Verification Z"))
  253. verz_lbl.setToolTip(
  254. _("Height (Z) for checking the point.")
  255. )
  256. self.verz_entry = FCDoubleSpinner()
  257. self.verz_entry.set_range(-9999.9999, 9999.9999)
  258. self.verz_entry.set_precision(self.decimals)
  259. self.verz_entry.setSingleStep(0.1)
  260. grid_lay.addWidget(verz_lbl, 13, 0)
  261. grid_lay.addWidget(self.verz_entry, 13, 1, 1, 2)
  262. # Zero the Z of the verification tool
  263. self.zeroz_cb = FCCheckBox('%s' % _("Zero Z tool"))
  264. self.zeroz_cb.setToolTip(
  265. _("Include a sequence to zero the height (Z)\n"
  266. "of the verification tool.")
  267. )
  268. grid_lay.addWidget(self.zeroz_cb, 14, 0, 1, 3)
  269. # Toochange Z entry
  270. toolchangez_lbl = QtWidgets.QLabel('%s:' % _("Toolchange Z"))
  271. toolchangez_lbl.setToolTip(
  272. _("Height (Z) for mounting the verification probe.")
  273. )
  274. self.toolchangez_entry = FCDoubleSpinner()
  275. self.toolchangez_entry.set_range(0.0000, 9999.9999)
  276. self.toolchangez_entry.set_precision(self.decimals)
  277. self.toolchangez_entry.setSingleStep(0.1)
  278. grid_lay.addWidget(toolchangez_lbl, 15, 0)
  279. grid_lay.addWidget(self.toolchangez_entry, 15, 1, 1, 2)
  280. self.z_ois = OptionalInputSection(self.zeroz_cb, [toolchangez_lbl, self.toolchangez_entry])
  281. # ## GCode Button
  282. self.gcode_button = QtWidgets.QPushButton(_("Generate GCode"))
  283. self.gcode_button.setToolTip(
  284. _("Generate GCode file to locate and align the PCB by using\n"
  285. "the four points acquired above.")
  286. )
  287. self.gcode_button.setStyleSheet("""
  288. QPushButton
  289. {
  290. font-weight: bold;
  291. }
  292. """)
  293. grid_lay.addWidget(self.gcode_button, 16, 0, 1, 3)
  294. separator_line1 = QtWidgets.QFrame()
  295. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  296. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  297. grid_lay.addWidget(separator_line1, 17, 0, 1, 3)
  298. grid_lay.addWidget(QtWidgets.QLabel(''), 18, 0, 1, 3)
  299. # STEP 3 #
  300. step_3 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 3: Adjustments"))
  301. step_3.setToolTip(
  302. _("Calculate Scale and Skew factors based on the differences (delta)\n"
  303. "found when checking the PCB pattern. The differences must be filled\n"
  304. "in the fields Found (Delta).")
  305. )
  306. grid_lay.addWidget(step_3, 19, 0, 1, 3)
  307. # ## Factors Button
  308. self.generate_factors_button = QtWidgets.QPushButton(_("Calculate Factors"))
  309. self.generate_factors_button.setToolTip(
  310. _("Calculate Scale and Skew factors based on the differences (delta)\n"
  311. "found when checking the PCB pattern. The differences must be filled\n"
  312. "in the fields Found (Delta).")
  313. )
  314. self.generate_factors_button.setStyleSheet("""
  315. QPushButton
  316. {
  317. font-weight: bold;
  318. }
  319. """)
  320. grid_lay.addWidget(self.generate_factors_button, 20, 0, 1, 3)
  321. scale_lbl = QtWidgets.QLabel('<b>%s</b>' % _("Scale Factors"))
  322. grid_lay.addWidget(scale_lbl, 21, 0, 1, 3)
  323. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  324. self.scalex_label.setToolTip(
  325. _("Factor for Scale action over X axis.")
  326. )
  327. self.scalex_entry = FCDoubleSpinner()
  328. self.scalex_entry.set_range(0, 9999.9999)
  329. self.scalex_entry.set_precision(self.decimals)
  330. self.scalex_entry.setSingleStep(0.1)
  331. grid_lay.addWidget(self.scalex_label, 22, 0)
  332. grid_lay.addWidget(self.scalex_entry, 22, 1, 1, 2)
  333. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  334. self.scaley_label.setToolTip(
  335. _("Factor for Scale action over Y axis.")
  336. )
  337. self.scaley_entry = FCDoubleSpinner()
  338. self.scaley_entry.set_range(0, 9999.9999)
  339. self.scaley_entry.set_precision(self.decimals)
  340. self.scaley_entry.setSingleStep(0.1)
  341. grid_lay.addWidget(self.scaley_label, 23, 0)
  342. grid_lay.addWidget(self.scaley_entry, 23, 1, 1, 2)
  343. self.scale_button = QtWidgets.QPushButton(_("Apply Scale Factors"))
  344. self.scale_button.setToolTip(
  345. _("Apply Scale factors on the calibration points.")
  346. )
  347. self.scale_button.setStyleSheet("""
  348. QPushButton
  349. {
  350. font-weight: bold;
  351. }
  352. """)
  353. grid_lay.addWidget(self.scale_button, 24, 0, 1, 3)
  354. skew_lbl = QtWidgets.QLabel('<b>%s</b>' % _("Skew Factors"))
  355. grid_lay.addWidget(skew_lbl, 25, 0, 1, 3)
  356. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  357. self.skewx_label.setToolTip(
  358. _("Angle for Skew action, in degrees.\n"
  359. "Float number between -360 and 359.")
  360. )
  361. self.skewx_entry = FCDoubleSpinner()
  362. self.skewx_entry.set_range(-360, 360)
  363. self.skewx_entry.set_precision(self.decimals)
  364. self.skewx_entry.setSingleStep(0.1)
  365. grid_lay.addWidget(self.skewx_label, 26, 0)
  366. grid_lay.addWidget(self.skewx_entry, 26, 1, 1, 2)
  367. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  368. self.skewy_label.setToolTip(
  369. _("Angle for Skew action, in degrees.\n"
  370. "Float number between -360 and 359.")
  371. )
  372. self.skewy_entry = FCDoubleSpinner()
  373. self.skewy_entry.set_range(-360, 360)
  374. self.skewy_entry.set_precision(self.decimals)
  375. self.skewy_entry.setSingleStep(0.1)
  376. grid_lay.addWidget(self.skewy_label, 27, 0)
  377. grid_lay.addWidget(self.skewy_entry, 27, 1, 1, 2)
  378. self.skew_button = QtWidgets.QPushButton(_("Apply Skew Factors"))
  379. self.skew_button.setToolTip(
  380. _("Apply Skew factors on the calibration points.")
  381. )
  382. self.skew_button.setStyleSheet("""
  383. QPushButton
  384. {
  385. font-weight: bold;
  386. }
  387. """)
  388. grid_lay.addWidget(self.skew_button, 28, 0, 1, 3)
  389. separator_line1 = QtWidgets.QFrame()
  390. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  391. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  392. grid_lay.addWidget(separator_line1, 29, 0, 1, 3)
  393. grid_lay.addWidget(QtWidgets.QLabel(''), 30, 0, 1, 3)
  394. # STEP 4 #
  395. step_4 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 4: Adjusted GCode"))
  396. step_4.setToolTip(
  397. _("Generate verification GCode file adjusted with\n"
  398. "the factors above.")
  399. )
  400. grid_lay.addWidget(step_4, 31, 0, 1, 3)
  401. # ## Adjusted GCode Button
  402. self.adj_gcode_button = QtWidgets.QPushButton(_("Generate Adjusted GCode"))
  403. self.adj_gcode_button.setToolTip(
  404. _("Generate verification GCode file adjusted with\n"
  405. "the factors above.")
  406. )
  407. self.adj_gcode_button.setStyleSheet("""
  408. QPushButton
  409. {
  410. font-weight: bold;
  411. }
  412. """)
  413. grid_lay.addWidget(self.adj_gcode_button, 32, 0, 1, 3)
  414. separator_line1 = QtWidgets.QFrame()
  415. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  416. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  417. grid_lay.addWidget(separator_line1, 33, 0, 1, 3)
  418. grid_lay.addWidget(QtWidgets.QLabel(''), 34, 0, 1, 3)
  419. # STEP 5 #
  420. step_5 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 5: Calibrate FlatCAM Objects"))
  421. step_5.setToolTip(
  422. _("Adjust the Excellon and Cutout Geometry objects\n"
  423. "with the factors determined, and verified, above.")
  424. )
  425. grid_lay.addWidget(step_5, 35, 0, 1, 3)
  426. self.adj_exc_object_combo = QtWidgets.QComboBox()
  427. self.adj_exc_object_combo.setModel(self.app.collection)
  428. self.adj_exc_object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  429. self.adj_exc_object_combo.setCurrentIndex(1)
  430. self.adj_excobj_label = QtWidgets.QLabel("%s:" % _("EXCELLON"))
  431. self.adj_excobj_label.setToolTip(
  432. _("Excellon Object to be adjusted.")
  433. )
  434. grid_lay.addWidget(self.adj_excobj_label, 36, 0, 1, 3)
  435. grid_lay.addWidget(self.adj_exc_object_combo, 37, 0, 1, 3)
  436. self.adj_geo_object_combo = QtWidgets.QComboBox()
  437. self.adj_geo_object_combo.setModel(self.app.collection)
  438. self.adj_geo_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  439. self.adj_geo_object_combo.setCurrentIndex(1)
  440. self.adj_geoobj_label = QtWidgets.QLabel("%s:" % _("GEOMETRY"))
  441. self.adj_geoobj_label.setToolTip(
  442. _("Geometry Object to be adjusted.")
  443. )
  444. grid_lay.addWidget(self.adj_geoobj_label, 38, 0, 1, 3)
  445. grid_lay.addWidget(self.adj_geo_object_combo, 39, 0, 1, 3)
  446. # ## Adjust Objects Button
  447. self.adj_obj_button = QtWidgets.QPushButton(_("Calibrate"))
  448. self.adj_obj_button.setToolTip(
  449. _("Adjust (scale and/or skew) the objects\n"
  450. "with the factors determined above.")
  451. )
  452. self.adj_obj_button.setStyleSheet("""
  453. QPushButton
  454. {
  455. font-weight: bold;
  456. }
  457. """)
  458. grid_lay.addWidget(self.adj_obj_button, 40, 0, 1, 3)
  459. separator_line2 = QtWidgets.QFrame()
  460. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  461. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  462. grid_lay.addWidget(separator_line2, 41, 0, 1, 3)
  463. grid_lay.addWidget(QtWidgets.QLabel(''), 42, 0, 1, 3)
  464. self.layout.addStretch()
  465. # ## Reset Tool
  466. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  467. self.reset_button.setToolTip(
  468. _("Will reset the tool parameters.")
  469. )
  470. self.reset_button.setStyleSheet("""
  471. QPushButton
  472. {
  473. font-weight: bold;
  474. }
  475. """)
  476. self.layout.addWidget(self.reset_button)
  477. self.mr = None
  478. self.units = ''
  479. # here store 4 points to be used for calibration
  480. self.click_points = list()
  481. # store the status of the grid
  482. self.grid_status_memory = None
  483. self.target_obj = None
  484. # ## Signals
  485. self.start_button.clicked.connect(self.on_start_collect_points)
  486. self.gcode_button.clicked.connect(self.generate_verification_gcode)
  487. self.generate_factors_button.clicked.connect(self.calculate_factors)
  488. self.reset_button.clicked.connect(self.set_tool_ui)
  489. self.cal_source_radio.activated_custom.connect(self.on_cal_source_radio)
  490. self.obj_type_combo.currentIndexChanged.connect(self.on_obj_type_combo)
  491. def run(self, toggle=True):
  492. self.app.report_usage("ToolCalibrate()")
  493. if toggle:
  494. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  495. if self.app.ui.splitter.sizes()[0] == 0:
  496. self.app.ui.splitter.setSizes([1, 1])
  497. else:
  498. try:
  499. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  500. # if tab is populated with the tool but it does not have the focus, focus on it
  501. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  502. # focus on Tool Tab
  503. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  504. else:
  505. self.app.ui.splitter.setSizes([0, 1])
  506. except AttributeError:
  507. pass
  508. else:
  509. if self.app.ui.splitter.sizes()[0] == 0:
  510. self.app.ui.splitter.setSizes([1, 1])
  511. FlatCAMTool.run(self)
  512. self.set_tool_ui()
  513. self.app.ui.notebook.setTabText(2, _("Calibrate Tool"))
  514. def install(self, icon=None, separator=None, **kwargs):
  515. FlatCAMTool.install(self, icon, separator, shortcut='ALT+E', **kwargs)
  516. def set_tool_ui(self):
  517. self.units = self.app.defaults['units'].upper()
  518. # ## Initialize form
  519. # self.mm_entry.set_value('%.*f' % (self.decimals, 0))
  520. def on_obj_type_combo(self):
  521. obj_type = self.obj_type_combo.currentIndex()
  522. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  523. self.object_combo.setCurrentIndex(0)
  524. def on_cal_source_radio(self, val):
  525. if val == 'object':
  526. self.obj_type_label.setDisabled(False)
  527. self.obj_type_combo.setDisabled(False)
  528. self.object_label.setDisabled(False)
  529. self.object_combo.setDisabled(False)
  530. else:
  531. self.obj_type_label.setDisabled(True)
  532. self.obj_type_combo.setDisabled(True)
  533. self.object_label.setDisabled(True)
  534. self.object_combo.setDisabled(True)
  535. def on_start_collect_points(self):
  536. # disengage the grid snapping since it will be hard to find the drills on grid
  537. if self.app.ui.grid_snap_btn.isChecked():
  538. self.grid_status_memory = True
  539. self.app.ui.grid_snap_btn.trigger()
  540. else:
  541. self.grid_status_memory = False
  542. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  543. if self.app.is_legacy is False:
  544. self.canvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  545. else:
  546. self.canvas.graph_event_disconnect(self.app.mr)
  547. if self.cal_source_radio.get_value() == 'object':
  548. selection_index = self.object_combo.currentIndex()
  549. model_index = self.app.collection.index(selection_index, 0, self.object_combo.rootModelIndex())
  550. try:
  551. self.target_obj = model_index.internalPointer().obj
  552. except Exception:
  553. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no target object loaded ..."))
  554. return
  555. self.reset_calibration_points()
  556. self.app.inform.emit(_("Click inside the First drill point. Bottom Left..."))
  557. def on_mouse_click_release(self, event):
  558. if event.button == 1:
  559. if self.app.is_legacy is False:
  560. event_pos = event.pos
  561. else:
  562. event_pos = (event.xdata, event.ydata)
  563. pos_canvas = self.canvas.translate_coords(event_pos)
  564. click_pt = Point([pos_canvas[0], pos_canvas[1]])
  565. if self.cal_source_radio.get_value() == 'object':
  566. if self.target_obj.kind.lower() == 'excellon':
  567. for tool, tool_dict in self.target_obj.tools.items():
  568. for geo in tool_dict['solid_geometry']:
  569. if click_pt.within(geo):
  570. center_pt = geo.centroid
  571. self.click_points.append(
  572. (
  573. float('%.*f' % (self.decimals, center_pt.x)),
  574. float('%.*f' % (self.decimals, center_pt.y))
  575. )
  576. )
  577. self.check_points()
  578. else:
  579. for apid, apid_val in self.target_obj.apertures.items():
  580. for geo_el in apid_val['geometry']:
  581. if 'solid' in geo_el:
  582. if click_pt.within(geo_el['solid']):
  583. print(type(geo_el['follow']))
  584. if isinstance(geo_el['follow'], Point):
  585. center_pt = geo_el['solid'].centroid
  586. self.click_points.append(
  587. (
  588. float('%.*f' % (self.decimals, center_pt.x)),
  589. float('%.*f' % (self.decimals, center_pt.y))
  590. )
  591. )
  592. self.check_points()
  593. else:
  594. self.click_points.append(
  595. (
  596. float('%.*f' % (self.decimals, click_pt.x)),
  597. float('%.*f' % (self.decimals, click_pt.y))
  598. )
  599. )
  600. self.check_points()
  601. def check_points(self):
  602. if len(self.click_points) == 1:
  603. self.bottom_left_coordx_tgt.set_value(self.click_points[0][0])
  604. self.bottom_left_coordy_tgt.set_value(self.click_points[0][1])
  605. self.app.inform.emit(_("Click inside the Second drill point. Bottom Right..."))
  606. elif len(self.click_points) == 2:
  607. self.bottom_right_coordx_tgt.set_value(self.click_points[1][0])
  608. self.bottom_right_coordy_tgt.set_value(self.click_points[1][1])
  609. self.app.inform.emit(_("Click inside the Third drill point. Top Left..."))
  610. elif len(self.click_points) == 3:
  611. self.top_left_coordx_tgt.set_value(self.click_points[2][0])
  612. self.top_left_coordy_tgt.set_value(self.click_points[2][1])
  613. self.app.inform.emit(_("Click inside the Fourth drill point. Top Right..."))
  614. elif len(self.click_points) == 4:
  615. self.top_right_coordx_tgt.set_value(self.click_points[3][0])
  616. self.top_right_coordy_tgt.set_value(self.click_points[3][1])
  617. self.app.inform.emit('[success] %s' % _("Done. All four points have been acquired."))
  618. self.disconnect_cal_events()
  619. # restore the Grid snapping if it was active before
  620. if self.grid_status_memory is True:
  621. self.app.ui.grid_snap_btn.trigger()
  622. def reset_calibration_points(self):
  623. self.click_points = list()
  624. self.bottom_left_coordx_tgt.set_value('')
  625. self.bottom_left_coordy_tgt.set_value('')
  626. self.bottom_right_coordx_tgt.set_value('')
  627. self.bottom_right_coordy_tgt.set_value('')
  628. self.top_left_coordx_tgt.set_value('')
  629. self.top_left_coordy_tgt.set_value('')
  630. self.top_right_coordx_tgt.set_value('')
  631. self.top_right_coordy_tgt.set_value('')
  632. def gcode_header(self):
  633. log.debug("ToolCalibrate.gcode_header()")
  634. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  635. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  636. (str(self.app.version), str(self.app.version_date)) + '\n'
  637. gcode += '(Name: ' + _('Verification GCode for FlatCAM Calibrate Tool') + ')\n'
  638. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  639. gcode += '(Created on ' + time_str + ')\n' + '\n'
  640. gcode += 'G20\n' if self.units.upper() == 'IN' else 'G21\n'
  641. gcode += 'G90\n'
  642. gcode += 'G17\n'
  643. gcode += 'G94\n\n'
  644. return gcode
  645. def close_tab(self):
  646. for idx in range(self.app.ui.plot_tab_area.count()):
  647. if self.app.ui.plot_tab_area.tabText(idx) == _("Gcode Viewer"):
  648. wdg = self.app.ui.plot_tab_area.widget(idx)
  649. wdg.deleteLater()
  650. self.app.ui.plot_tab_area.removeTab(idx)
  651. def generate_verification_gcode(self):
  652. travel_z = '%.*f' % (self.decimals, self.travelz_entry.get_value())
  653. toolchange_z = '%.*f' % (self.decimals, self.toolchangez_entry.get_value())
  654. verification_z = '%.*f' % (self.decimals, self.verz_entry.get_value())
  655. if len(self.click_points) != 4:
  656. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Four points are needed for GCode generation."))
  657. return 'fail'
  658. gcode = self.gcode_header()
  659. if self.zeroz_cb.get_value():
  660. gcode += 'M5\n'
  661. gcode += f'G00 Z{toolchange_z}\n'
  662. gcode += 'M0\n'
  663. gcode += 'G01 Z0\n'
  664. gcode += 'M0\n'
  665. gcode += f'G00 Z{toolchange_z}\n'
  666. gcode += 'M0\n'
  667. gcode += f'G00 Z{travel_z}\n'
  668. gcode += f'G00 X{self.click_points[0][0]} Y{self.click_points[0][1]}\n'
  669. gcode += f'G01 Z{verification_z}\n'
  670. gcode += 'M0\n'
  671. gcode += f'G00 Z{travel_z}\n'
  672. gcode += f'G00 X{self.click_points[2][0]} Y{self.click_points[2][1]}\n'
  673. gcode += f'G01 Z{verification_z}\n'
  674. gcode += 'M0\n'
  675. gcode += f'G00 Z{travel_z}\n'
  676. gcode += f'G00 X{self.click_points[3][0]} Y{self.click_points[3][1]}\n'
  677. gcode += f'G01 Z{verification_z}\n'
  678. gcode += 'M0\n'
  679. gcode += f'G00 Z{travel_z}\n'
  680. gcode += f'G00 X{self.click_points[1][0]} Y{self.click_points[1][1]}\n'
  681. gcode += f'G01 Z{verification_z}\n'
  682. gcode += 'M0\n'
  683. gcode += f'G00 Z{travel_z}\n'
  684. gcode += f'G00 X0 Y0\n'
  685. gcode += f'G00 Z{toolchange_z}\n'
  686. gcode += 'M2'
  687. self.gcode_editor_tab = TextEditor(app=self.app, plain_text=True)
  688. # add the tab if it was closed
  689. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Gcode Viewer"))
  690. self.gcode_editor_tab.setObjectName('gcode_viewer_tab')
  691. # delete the absolute and relative position and messages in the infobar
  692. self.app.ui.position_label.setText("")
  693. self.app.ui.rel_position_label.setText("")
  694. # first clear previous text in text editor (if any)
  695. self.gcode_editor_tab.code_editor.clear()
  696. self.gcode_editor_tab.code_editor.setReadOnly(False)
  697. self.gcode_editor_tab.code_editor.completer_enable = False
  698. self.gcode_editor_tab.buttonRun.hide()
  699. # Switch plot_area to CNCJob tab
  700. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  701. self.gcode_editor_tab.t_frame.hide()
  702. # then append the text from GCode to the text editor
  703. try:
  704. self.gcode_editor_tab.code_editor.setPlainText(gcode)
  705. except Exception as e:
  706. self.app.inform.emit('[ERROR] %s %s' % ('ERROR -->', str(e)))
  707. return
  708. self.gcode_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  709. self.gcode_editor_tab.t_frame.show()
  710. self.app.proc_container.view.set_idle()
  711. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  712. _filter_ = "G-Code Files (*.nc);;All Files (*.*)"
  713. self.gcode_editor_tab.buttonSave.clicked.disconnect()
  714. self.gcode_editor_tab.buttonSave.clicked.connect(
  715. lambda: self.gcode_editor_tab.handleSaveGCode(name='fc_ver_gcode', filt=_filter_, callback=self.close_tab))
  716. #
  717. # try:
  718. # dir_file_to_save = self.app.get_last_save_folder() + '/' + 'ver_gcode'
  719. # filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  720. # caption=_("Export Machine Code ..."),
  721. # directory=dir_file_to_save,
  722. # filter=_filter_
  723. # )
  724. # except TypeError:
  725. # filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  726. #
  727. # filename = str(filename)
  728. #
  729. # if filename == '':
  730. # self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export Machine Code cancelled ..."))
  731. # return
  732. #
  733. # with open(filename, 'w') as f:
  734. # f.write(gcode)
  735. def calculate_factors(self):
  736. origin_x = self.click_points[0][0]
  737. origin_y = self.click_points[0][1]
  738. top_left_x = float('%.*f' % (self.decimals, self.click_points[2][0]))
  739. top_left_y = float('%.*f' % (self.decimals, self.click_points[2][1]))
  740. try:
  741. top_left_dx = float('%.*f' % (self.decimals, self.top_left_coordx_found.get_value()))
  742. except TypeError:
  743. top_left_dx = top_left_x
  744. try:
  745. top_left_dy = float('%.*f' % (self.decimals, self.top_left_coordy_found.get_value()))
  746. except TypeError:
  747. top_left_dy = top_left_y
  748. top_right_x = float('%.*f' % (self.decimals, self.click_points[3][0]))
  749. top_right_y = float('%.*f' % (self.decimals, self.click_points[3][1]))
  750. try:
  751. top_right_dx = float('%.*f' % (self.decimals, self.top_right_coordx_found.get_value()))
  752. except TypeError:
  753. top_right_dx = top_right_x
  754. try:
  755. top_right_dy = float('%.*f' % (self.decimals, self.top_right_coordy_found.get_value()))
  756. except TypeError:
  757. top_right_dy = top_right_y
  758. bot_right_x = float('%.*f' % (self.decimals, self.click_points[1][0]))
  759. bot_right_y = float('%.*f' % (self.decimals, self.click_points[1][1]))
  760. try:
  761. bot_right_dx = float('%.*f' % (self.decimals, self.bottom_right_coordx_found.get_value()))
  762. except TypeError:
  763. bot_right_dx = bot_right_x
  764. try:
  765. bot_right_dy = float('%.*f' % (self.decimals, self.bottom_right_coordy_found.get_value()))
  766. except TypeError:
  767. bot_right_dy = bot_right_y
  768. # ------------------------------------------------------------------------------- #
  769. # --------------------------- FACTORS CALCULUS ---------------------------------- #
  770. # ------------------------------------------------------------------------------- #
  771. if top_left_dy != float('%.*f' % (self.decimals, 0.0)):
  772. # we have scale on Y
  773. scale_y = (top_left_dy + top_left_y - origin_y) / (top_left_y - origin_y)
  774. self.scaley_entry.set_value(scale_y)
  775. if top_left_dx != float('%.*f' % (self.decimals, 0.0)):
  776. # we have skew on X
  777. dx = top_left_dx
  778. dy = top_left_y - origin_y
  779. skew_angle_x = math.degrees(math.atan(dx / dy))
  780. self.skewx_entry.set_value(skew_angle_x)
  781. if bot_right_dx != float('%.*f' % (self.decimals, 0.0)):
  782. # we have scale on X
  783. scale_x = (bot_right_dx + bot_right_x - origin_x) / (bot_right_x - origin_x)
  784. self.scalex_entry.set_value(scale_x)
  785. if bot_right_dy != float('%.*f' % (self.decimals, 0.0)):
  786. # we have skew on Y
  787. dx = bot_right_x - origin_x
  788. dy = bot_right_dy + origin_y
  789. skew_angle_y = math.degrees(math.atan(dy / dx))
  790. self.skewy_entry.set_value(skew_angle_y)
  791. def disconnect_cal_events(self):
  792. self.app.mr = self.canvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  793. if self.app.is_legacy is False:
  794. self.canvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  795. else:
  796. self.canvas.graph_event_disconnect(self.mr)
  797. def reset_fields(self):
  798. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  799. # end of file