ToolCalibrate.py 35 KB

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