ToolCalibration.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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, FCEntry
  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. from shapely.affinity import scale, skew
  15. import math
  16. from datetime import datetime
  17. import logging
  18. from copy import deepcopy
  19. import gettext
  20. import FlatCAMTranslation as fcTranslate
  21. import builtins
  22. fcTranslate.apply_language('strings')
  23. if '_' not in builtins.__dict__:
  24. _ = gettext.gettext
  25. log = logging.getLogger('base')
  26. class ToolCalibration(FlatCAMTool):
  27. toolName = _("Calibration Tool")
  28. def __init__(self, app):
  29. FlatCAMTool.__init__(self, app)
  30. self.app = app
  31. self.canvas = self.app.plotcanvas
  32. self.decimals = self.app.decimals
  33. # ## Title
  34. title_label = QtWidgets.QLabel("%s" % self.toolName)
  35. title_label.setStyleSheet("""
  36. QLabel
  37. {
  38. font-size: 16px;
  39. font-weight: bold;
  40. }
  41. """)
  42. self.layout.addWidget(title_label)
  43. self.layout.addWidget(QtWidgets.QLabel(''))
  44. # ## Grid Layout
  45. grid_lay = QtWidgets.QGridLayout()
  46. self.layout.addLayout(grid_lay)
  47. grid_lay.setColumnStretch(0, 0)
  48. grid_lay.setColumnStretch(1, 1)
  49. grid_lay.setColumnStretch(2, 0)
  50. self.gcode_title_label = QtWidgets.QLabel('<b>%s</b>' % _('GCode Parameters'))
  51. self.gcode_title_label.setToolTip(
  52. _("Parameters used when creating the GCode in this tool.")
  53. )
  54. grid_lay.addWidget(self.gcode_title_label, 0, 0, 1, 3)
  55. # Travel Z entry
  56. travelz_lbl = QtWidgets.QLabel('%s:' % _("Travel Z"))
  57. travelz_lbl.setToolTip(
  58. _("Height (Z) for travelling between the points.")
  59. )
  60. self.travelz_entry = FCDoubleSpinner()
  61. self.travelz_entry.set_range(-9999.9999, 9999.9999)
  62. self.travelz_entry.set_precision(self.decimals)
  63. self.travelz_entry.setSingleStep(0.1)
  64. grid_lay.addWidget(travelz_lbl, 1, 0)
  65. grid_lay.addWidget(self.travelz_entry, 1, 1, 1, 2)
  66. # Verification Z entry
  67. verz_lbl = QtWidgets.QLabel('%s:' % _("Verification Z"))
  68. verz_lbl.setToolTip(
  69. _("Height (Z) for checking the point.")
  70. )
  71. self.verz_entry = FCDoubleSpinner()
  72. self.verz_entry.set_range(-9999.9999, 9999.9999)
  73. self.verz_entry.set_precision(self.decimals)
  74. self.verz_entry.setSingleStep(0.1)
  75. grid_lay.addWidget(verz_lbl, 2, 0)
  76. grid_lay.addWidget(self.verz_entry, 2, 1, 1, 2)
  77. # Zero the Z of the verification tool
  78. self.zeroz_cb = FCCheckBox('%s' % _("Zero Z tool"))
  79. self.zeroz_cb.setToolTip(
  80. _("Include a sequence to zero the height (Z)\n"
  81. "of the verification tool.")
  82. )
  83. grid_lay.addWidget(self.zeroz_cb, 3, 0, 1, 3)
  84. # Toolchange Z entry
  85. toolchangez_lbl = QtWidgets.QLabel('%s:' % _("Toolchange Z"))
  86. toolchangez_lbl.setToolTip(
  87. _("Height (Z) for mounting the verification probe.")
  88. )
  89. self.toolchangez_entry = FCDoubleSpinner()
  90. self.toolchangez_entry.set_range(0.0000, 9999.9999)
  91. self.toolchangez_entry.set_precision(self.decimals)
  92. self.toolchangez_entry.setSingleStep(0.1)
  93. grid_lay.addWidget(toolchangez_lbl, 4, 0)
  94. grid_lay.addWidget(self.toolchangez_entry, 4, 1, 1, 2)
  95. # Toolchange X-Y entry
  96. toolchangexy_lbl = QtWidgets.QLabel('%s:' % _('Toolchange X-Y'))
  97. toolchangexy_lbl.setToolTip(
  98. _("Toolchange X,Y position.\n"
  99. "If no value is entered then the current\n"
  100. "(x, y) point will be used,")
  101. )
  102. self.toolchange_xy_entry = FCEntry()
  103. grid_lay.addWidget(toolchangexy_lbl, 5, 0)
  104. grid_lay.addWidget(self.toolchange_xy_entry, 5, 1, 1, 2)
  105. self.z_ois = OptionalInputSection(
  106. self.zeroz_cb,
  107. [
  108. toolchangez_lbl,
  109. self.toolchangez_entry,
  110. toolchangexy_lbl,
  111. self.toolchange_xy_entry
  112. ]
  113. )
  114. separator_line1 = QtWidgets.QFrame()
  115. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  116. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  117. grid_lay.addWidget(separator_line1, 6, 0, 1, 3)
  118. # Second point choice
  119. second_point_lbl = QtWidgets.QLabel('%s:' % _("Second point"))
  120. second_point_lbl.setToolTip(
  121. _("Second point in the Gcode verification can be:\n"
  122. "- top-left -> the user will align the PCB vertically\n"
  123. "- bottom-right -> the user will align the PCB horizontally")
  124. )
  125. self.second_point_radio = RadioSet([{'label': _('Top-Left'), 'value': 'tl'},
  126. {'label': _('Bottom-Right'), 'value': 'br'}],
  127. orientation='vertical')
  128. grid_lay.addWidget(second_point_lbl, 7, 0)
  129. grid_lay.addWidget(self.second_point_radio, 7, 1, 1, 2)
  130. separator_line1 = QtWidgets.QFrame()
  131. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  132. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  133. grid_lay.addWidget(separator_line1, 8, 0, 1, 3)
  134. grid_lay.addWidget(QtWidgets.QLabel(''), 9, 0, 1, 3)
  135. step_1 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 1: Acquire Calibration Points"))
  136. step_1.setToolTip(
  137. _("Pick four points by clicking inside the drill holes.\n"
  138. "Those four points should be in the four\n"
  139. "(as much as possible) corners of the Excellon object.")
  140. )
  141. grid_lay.addWidget(step_1, 10, 0, 1, 3)
  142. self.cal_source_lbl = QtWidgets.QLabel("<b>%s:</b>" % _("Source Type"))
  143. self.cal_source_lbl.setToolTip(_("The source of calibration points.\n"
  144. "It can be:\n"
  145. "- Object -> click a hole geo for Excellon or a pad for Gerber\n"
  146. "- Free -> click freely on canvas to acquire the calibration points"))
  147. self.cal_source_radio = RadioSet([{'label': _('Object'), 'value': 'object'},
  148. {'label': _('Free'), 'value': 'free'}],
  149. stretch=False)
  150. grid_lay.addWidget(self.cal_source_lbl, 11, 0)
  151. grid_lay.addWidget(self.cal_source_radio, 11, 1, 1, 2)
  152. self.obj_type_label = QtWidgets.QLabel("%s:" % _("Object Type"))
  153. self.obj_type_combo = FCComboBox()
  154. self.obj_type_combo.addItem(_("Gerber"))
  155. self.obj_type_combo.addItem(_("Excellon"))
  156. self.obj_type_combo.setCurrentIndex(1)
  157. self.obj_type_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  158. self.obj_type_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  159. grid_lay.addWidget(self.obj_type_label, 12, 0)
  160. grid_lay.addWidget(self.obj_type_combo, 12, 1, 1, 2)
  161. self.object_combo = FCComboBox()
  162. self.object_combo.setModel(self.app.collection)
  163. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  164. self.object_combo.setCurrentIndex(1)
  165. self.object_label = QtWidgets.QLabel("%s:" % _("Source object selection"))
  166. self.object_label.setToolTip(
  167. _("FlatCAM Object to be used as a source for reference points.")
  168. )
  169. grid_lay.addWidget(self.object_label, 13, 0, 1, 3)
  170. grid_lay.addWidget(self.object_combo, 14, 0, 1, 3)
  171. self.points_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Calibration Points'))
  172. self.points_table_label.setToolTip(
  173. _("Contain the expected calibration points and the\n"
  174. "ones measured.")
  175. )
  176. grid_lay.addWidget(self.points_table_label, 15, 0, 1, 3)
  177. self.points_table = FCTable()
  178. self.points_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  179. # self.points_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  180. grid_lay.addWidget(self.points_table, 16, 0, 1, 3)
  181. self.points_table.setColumnCount(4)
  182. self.points_table.setHorizontalHeaderLabels(
  183. [
  184. '#',
  185. _("Name"),
  186. _("Target"),
  187. _("Found Delta")
  188. ]
  189. )
  190. self.points_table.setRowCount(8)
  191. row = 0
  192. # BOTTOM LEFT
  193. id_item_1 = QtWidgets.QTableWidgetItem('%d' % 1)
  194. flags = QtCore.Qt.ItemIsEnabled
  195. id_item_1.setFlags(flags)
  196. self.points_table.setItem(row, 0, id_item_1) # Tool name/id
  197. self.bottom_left_coordx_lbl = QtWidgets.QLabel('%s' % _('Bot Left X'))
  198. self.points_table.setCellWidget(row, 1, self.bottom_left_coordx_lbl)
  199. self.bottom_left_coordx_tgt = EvalEntry()
  200. self.points_table.setCellWidget(row, 2, self.bottom_left_coordx_tgt)
  201. self.bottom_left_coordx_tgt.setReadOnly(True)
  202. self.bottom_left_coordx_found = EvalEntry()
  203. self.points_table.setCellWidget(row, 3, self.bottom_left_coordx_found)
  204. row += 1
  205. self.bottom_left_coordy_lbl = QtWidgets.QLabel('%s' % _('Bot Left Y'))
  206. self.points_table.setCellWidget(row, 1, self.bottom_left_coordy_lbl)
  207. self.bottom_left_coordy_tgt = EvalEntry()
  208. self.points_table.setCellWidget(row, 2, self.bottom_left_coordy_tgt)
  209. self.bottom_left_coordy_tgt.setReadOnly(True)
  210. self.bottom_left_coordy_found = EvalEntry()
  211. self.points_table.setCellWidget(row, 3, self.bottom_left_coordy_found)
  212. self.bottom_left_coordx_found.set_value(_("Origin"))
  213. self.bottom_left_coordy_found.set_value(_("Origin"))
  214. self.bottom_left_coordx_found.setDisabled(True)
  215. self.bottom_left_coordy_found.setDisabled(True)
  216. row += 1
  217. # BOTTOM RIGHT
  218. id_item_2 = QtWidgets.QTableWidgetItem('%d' % 2)
  219. flags = QtCore.Qt.ItemIsEnabled
  220. id_item_2.setFlags(flags)
  221. self.points_table.setItem(row, 0, id_item_2) # Tool name/id
  222. self.bottom_right_coordx_lbl = QtWidgets.QLabel('%s' % _('Bot Right X'))
  223. self.points_table.setCellWidget(row, 1, self.bottom_right_coordx_lbl)
  224. self.bottom_right_coordx_tgt = EvalEntry()
  225. self.points_table.setCellWidget(row, 2, self.bottom_right_coordx_tgt)
  226. self.bottom_right_coordx_tgt.setReadOnly(True)
  227. self.bottom_right_coordx_found = EvalEntry()
  228. self.points_table.setCellWidget(row, 3, self.bottom_right_coordx_found)
  229. row += 1
  230. self.bottom_right_coordy_lbl = QtWidgets.QLabel('%s' % _('Bot Right Y'))
  231. self.points_table.setCellWidget(row, 1, self.bottom_right_coordy_lbl)
  232. self.bottom_right_coordy_tgt = EvalEntry()
  233. self.points_table.setCellWidget(row, 2, self.bottom_right_coordy_tgt)
  234. self.bottom_right_coordy_tgt.setReadOnly(True)
  235. self.bottom_right_coordy_found = EvalEntry()
  236. self.points_table.setCellWidget(row, 3, self.bottom_right_coordy_found)
  237. row += 1
  238. # TOP LEFT
  239. id_item_3 = QtWidgets.QTableWidgetItem('%d' % 3)
  240. flags = QtCore.Qt.ItemIsEnabled
  241. id_item_3.setFlags(flags)
  242. self.points_table.setItem(row, 0, id_item_3) # Tool name/id
  243. self.top_left_coordx_lbl = QtWidgets.QLabel('%s' % _('Top Left X'))
  244. self.points_table.setCellWidget(row, 1, self.top_left_coordx_lbl)
  245. self.top_left_coordx_tgt = EvalEntry()
  246. self.points_table.setCellWidget(row, 2, self.top_left_coordx_tgt)
  247. self.top_left_coordx_tgt.setReadOnly(True)
  248. self.top_left_coordx_found = EvalEntry()
  249. self.points_table.setCellWidget(row, 3, self.top_left_coordx_found)
  250. row += 1
  251. self.top_left_coordy_lbl = QtWidgets.QLabel('%s' % _('Top Left Y'))
  252. self.points_table.setCellWidget(row, 1, self.top_left_coordy_lbl)
  253. self.top_left_coordy_tgt = EvalEntry()
  254. self.points_table.setCellWidget(row, 2, self.top_left_coordy_tgt)
  255. self.top_left_coordy_tgt.setReadOnly(True)
  256. self.top_left_coordy_found = EvalEntry()
  257. self.points_table.setCellWidget(row, 3, self.top_left_coordy_found)
  258. row += 1
  259. # TOP RIGHT
  260. id_item_4 = QtWidgets.QTableWidgetItem('%d' % 4)
  261. flags = QtCore.Qt.ItemIsEnabled
  262. id_item_4.setFlags(flags)
  263. self.points_table.setItem(row, 0, id_item_4) # Tool name/id
  264. self.top_right_coordx_lbl = QtWidgets.QLabel('%s' % _('Top Right X'))
  265. self.points_table.setCellWidget(row, 1, self.top_right_coordx_lbl)
  266. self.top_right_coordx_tgt = EvalEntry()
  267. self.points_table.setCellWidget(row, 2, self.top_right_coordx_tgt)
  268. self.top_right_coordx_tgt.setReadOnly(True)
  269. self.top_right_coordx_found = EvalEntry()
  270. self.top_right_coordx_found.setDisabled(True)
  271. self.points_table.setCellWidget(row, 3, self.top_right_coordx_found)
  272. row += 1
  273. self.top_right_coordy_lbl = QtWidgets.QLabel('%s' % _('Top Right Y'))
  274. self.points_table.setCellWidget(row, 1, self.top_right_coordy_lbl)
  275. self.top_right_coordy_tgt = EvalEntry()
  276. self.points_table.setCellWidget(row, 2, self.top_right_coordy_tgt)
  277. self.top_right_coordy_tgt.setReadOnly(True)
  278. self.top_right_coordy_found = EvalEntry()
  279. self.top_right_coordy_found.setDisabled(True)
  280. self.points_table.setCellWidget(row, 3, self.top_right_coordy_found)
  281. vertical_header = self.points_table.verticalHeader()
  282. vertical_header.hide()
  283. self.points_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  284. horizontal_header = self.points_table.horizontalHeader()
  285. horizontal_header.setMinimumSectionSize(10)
  286. horizontal_header.setDefaultSectionSize(70)
  287. self.points_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  288. # for x in range(4):
  289. # self.points_table.resizeColumnToContents(x)
  290. self.points_table.resizeColumnsToContents()
  291. self.points_table.resizeRowsToContents()
  292. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  293. horizontal_header.resizeSection(0, 20)
  294. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Fixed)
  295. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
  296. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
  297. self.points_table.setMinimumHeight(self.points_table.getHeight() + 2)
  298. self.points_table.setMaximumHeight(self.points_table.getHeight() + 3)
  299. # ## Get Points Button
  300. self.start_button = QtWidgets.QPushButton(_("Get Points"))
  301. self.start_button.setToolTip(
  302. _("Pick four points by clicking on canvas if the source choice\n"
  303. "is 'free' or inside the object geometry if the source is 'object'.\n"
  304. "Those four points should be in the four squares of\n"
  305. "the object.")
  306. )
  307. self.start_button.setStyleSheet("""
  308. QPushButton
  309. {
  310. font-weight: bold;
  311. }
  312. """)
  313. grid_lay.addWidget(self.start_button, 17, 0, 1, 3)
  314. separator_line = QtWidgets.QFrame()
  315. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  316. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  317. grid_lay.addWidget(separator_line, 18, 0, 1, 3)
  318. grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  319. # STEP 2 #
  320. step_2 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 2: Verification GCode"))
  321. step_2.setToolTip(
  322. _("Generate GCode file to locate and align the PCB by using\n"
  323. "the four points acquired above.\n"
  324. "The points sequence is:\n"
  325. "- first point -> set the origin\n"
  326. "- second point -> alignment point. Can be: top-left or bottom-right.\n"
  327. "- third point -> check point. Can be: top-left or bottom-right.\n"
  328. "- forth point -> final verification point. Just for evaluation.")
  329. )
  330. grid_lay.addWidget(step_2, 20, 0, 1, 3)
  331. # ## GCode Button
  332. self.gcode_button = QtWidgets.QPushButton(_("Generate GCode"))
  333. self.gcode_button.setToolTip(
  334. _("Generate GCode file to locate and align the PCB by using\n"
  335. "the four points acquired above.\n"
  336. "The points sequence is:\n"
  337. "- first point -> set the origin\n"
  338. "- second point -> alignment point. Can be: top-left or bottom-right.\n"
  339. "- third point -> check point. Can be: top-left or bottom-right.\n"
  340. "- forth point -> final verification point. Just for evaluation.")
  341. )
  342. self.gcode_button.setStyleSheet("""
  343. QPushButton
  344. {
  345. font-weight: bold;
  346. }
  347. """)
  348. grid_lay.addWidget(self.gcode_button, 21, 0, 1, 3)
  349. separator_line1 = QtWidgets.QFrame()
  350. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  351. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  352. grid_lay.addWidget(separator_line1, 22, 0, 1, 3)
  353. grid_lay.addWidget(QtWidgets.QLabel(''), 23, 0, 1, 3)
  354. # STEP 3 #
  355. step_3 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 3: Adjustments"))
  356. step_3.setToolTip(
  357. _("Calculate Scale and Skew factors based on the differences (delta)\n"
  358. "found when checking the PCB pattern. The differences must be filled\n"
  359. "in the fields Found (Delta).")
  360. )
  361. grid_lay.addWidget(step_3, 24, 0, 1, 3)
  362. # ## Factors Button
  363. self.generate_factors_button = QtWidgets.QPushButton(_("Calculate Factors"))
  364. self.generate_factors_button.setToolTip(
  365. _("Calculate Scale and Skew factors based on the differences (delta)\n"
  366. "found when checking the PCB pattern. The differences must be filled\n"
  367. "in the fields Found (Delta).")
  368. )
  369. self.generate_factors_button.setStyleSheet("""
  370. QPushButton
  371. {
  372. font-weight: bold;
  373. }
  374. """)
  375. grid_lay.addWidget(self.generate_factors_button, 25, 0, 1, 3)
  376. separator_line1 = QtWidgets.QFrame()
  377. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  378. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  379. grid_lay.addWidget(separator_line1, 26, 0, 1, 3)
  380. grid_lay.addWidget(QtWidgets.QLabel(''), 27, 0, 1, 3)
  381. # STEP 4 #
  382. step_4 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 4: Adjusted GCode"))
  383. step_4.setToolTip(
  384. _("Generate verification GCode file adjusted with\n"
  385. "the factors above.")
  386. )
  387. grid_lay.addWidget(step_4, 28, 0, 1, 3)
  388. self.scalex_label = QtWidgets.QLabel(_("Scale Factor X:"))
  389. self.scalex_label.setToolTip(
  390. _("Factor for Scale action over X axis.")
  391. )
  392. self.scalex_entry = FCDoubleSpinner()
  393. self.scalex_entry.set_range(0, 9999.9999)
  394. self.scalex_entry.set_precision(self.decimals)
  395. self.scalex_entry.setSingleStep(0.1)
  396. grid_lay.addWidget(self.scalex_label, 29, 0)
  397. grid_lay.addWidget(self.scalex_entry, 29, 1, 1, 2)
  398. self.scaley_label = QtWidgets.QLabel(_("Scale Factor Y:"))
  399. self.scaley_label.setToolTip(
  400. _("Factor for Scale action over Y axis.")
  401. )
  402. self.scaley_entry = FCDoubleSpinner()
  403. self.scaley_entry.set_range(0, 9999.9999)
  404. self.scaley_entry.set_precision(self.decimals)
  405. self.scaley_entry.setSingleStep(0.1)
  406. grid_lay.addWidget(self.scaley_label, 30, 0)
  407. grid_lay.addWidget(self.scaley_entry, 30, 1, 1, 2)
  408. self.scale_button = QtWidgets.QPushButton(_("Apply Scale Factors"))
  409. self.scale_button.setToolTip(
  410. _("Apply Scale factors on the calibration points.")
  411. )
  412. self.scale_button.setStyleSheet("""
  413. QPushButton
  414. {
  415. font-weight: bold;
  416. }
  417. """)
  418. grid_lay.addWidget(self.scale_button, 31, 0, 1, 3)
  419. self.skewx_label = QtWidgets.QLabel(_("Skew Angle X:"))
  420. self.skewx_label.setToolTip(
  421. _("Angle for Skew action, in degrees.\n"
  422. "Float number between -360 and 359.")
  423. )
  424. self.skewx_entry = FCDoubleSpinner()
  425. self.skewx_entry.set_range(-360, 360)
  426. self.skewx_entry.set_precision(self.decimals)
  427. self.skewx_entry.setSingleStep(0.1)
  428. grid_lay.addWidget(self.skewx_label, 32, 0)
  429. grid_lay.addWidget(self.skewx_entry, 32, 1, 1, 2)
  430. self.skewy_label = QtWidgets.QLabel(_("Skew Angle Y:"))
  431. self.skewy_label.setToolTip(
  432. _("Angle for Skew action, in degrees.\n"
  433. "Float number between -360 and 359.")
  434. )
  435. self.skewy_entry = FCDoubleSpinner()
  436. self.skewy_entry.set_range(-360, 360)
  437. self.skewy_entry.set_precision(self.decimals)
  438. self.skewy_entry.setSingleStep(0.1)
  439. grid_lay.addWidget(self.skewy_label, 33, 0)
  440. grid_lay.addWidget(self.skewy_entry, 33, 1, 1, 2)
  441. self.skew_button = QtWidgets.QPushButton(_("Apply Skew Factors"))
  442. self.skew_button.setToolTip(
  443. _("Apply Skew factors on the calibration points.")
  444. )
  445. self.skew_button.setStyleSheet("""
  446. QPushButton
  447. {
  448. font-weight: bold;
  449. }
  450. """)
  451. grid_lay.addWidget(self.skew_button, 34, 0, 1, 3)
  452. # final_factors_lbl = QtWidgets.QLabel('<b>%s</b>' % _("Final Factors"))
  453. # final_factors_lbl.setToolTip(
  454. # _("Generate verification GCode file adjusted with\n"
  455. # "the factors above.")
  456. # )
  457. # grid_lay.addWidget(final_factors_lbl, 27, 0, 1, 3)
  458. #
  459. # self.fin_scalex_label = QtWidgets.QLabel(_("Scale Factor X:"))
  460. # self.fin_scalex_label.setToolTip(
  461. # _("Final factor for Scale action over X axis.")
  462. # )
  463. # self.fin_scalex_entry = FCDoubleSpinner()
  464. # self.fin_scalex_entry.set_range(0, 9999.9999)
  465. # self.fin_scalex_entry.set_precision(self.decimals)
  466. # self.fin_scalex_entry.setSingleStep(0.1)
  467. #
  468. # grid_lay.addWidget(self.fin_scalex_label, 28, 0)
  469. # grid_lay.addWidget(self.fin_scalex_entry, 28, 1, 1, 2)
  470. #
  471. # self.fin_scaley_label = QtWidgets.QLabel(_("Scale Factor Y:"))
  472. # self.fin_scaley_label.setToolTip(
  473. # _("Final factor for Scale action over Y axis.")
  474. # )
  475. # self.fin_scaley_entry = FCDoubleSpinner()
  476. # self.fin_scaley_entry.set_range(0, 9999.9999)
  477. # self.fin_scaley_entry.set_precision(self.decimals)
  478. # self.fin_scaley_entry.setSingleStep(0.1)
  479. #
  480. # grid_lay.addWidget(self.fin_scaley_label, 29, 0)
  481. # grid_lay.addWidget(self.fin_scaley_entry, 29, 1, 1, 2)
  482. #
  483. # self.fin_skewx_label = QtWidgets.QLabel(_("Skew Angle X:"))
  484. # self.fin_skewx_label.setToolTip(
  485. # _("Final value for angle for Skew action, in degrees.\n"
  486. # "Float number between -360 and 359.")
  487. # )
  488. # self.fin_skewx_entry = FCDoubleSpinner()
  489. # self.fin_skewx_entry.set_range(-360, 360)
  490. # self.fin_skewx_entry.set_precision(self.decimals)
  491. # self.fin_skewx_entry.setSingleStep(0.1)
  492. #
  493. # grid_lay.addWidget(self.fin_skewx_label, 30, 0)
  494. # grid_lay.addWidget(self.fin_skewx_entry, 30, 1, 1, 2)
  495. #
  496. # self.fin_skewy_label = QtWidgets.QLabel(_("Skew Angle Y:"))
  497. # self.fin_skewy_label.setToolTip(
  498. # _("Final value for angle for Skew action, in degrees.\n"
  499. # "Float number between -360 and 359.")
  500. # )
  501. # self.fin_skewy_entry = FCDoubleSpinner()
  502. # self.fin_skewy_entry.set_range(-360, 360)
  503. # self.fin_skewy_entry.set_precision(self.decimals)
  504. # self.fin_skewy_entry.setSingleStep(0.1)
  505. #
  506. # grid_lay.addWidget(self.fin_skewy_label, 31, 0)
  507. # grid_lay.addWidget(self.fin_skewy_entry, 31, 1, 1, 2)
  508. # ## Adjusted GCode Button
  509. self.adj_gcode_button = QtWidgets.QPushButton(_("Generate Adjusted GCode"))
  510. self.adj_gcode_button.setToolTip(
  511. _("Generate verification GCode file adjusted with\n"
  512. "the factors set above.\n"
  513. "The GCode parameters can be readjusted\n"
  514. "before clicking this button.")
  515. )
  516. self.adj_gcode_button.setStyleSheet("""
  517. QPushButton
  518. {
  519. font-weight: bold;
  520. }
  521. """)
  522. grid_lay.addWidget(self.adj_gcode_button, 42, 0, 1, 3)
  523. separator_line1 = QtWidgets.QFrame()
  524. separator_line1.setFrameShape(QtWidgets.QFrame.HLine)
  525. separator_line1.setFrameShadow(QtWidgets.QFrame.Sunken)
  526. grid_lay.addWidget(separator_line1, 43, 0, 1, 3)
  527. grid_lay.addWidget(QtWidgets.QLabel(''), 44, 0, 1, 3)
  528. # STEP 5 #
  529. step_5 = QtWidgets.QLabel('<b>%s</b>' % _("STEP 5: Calibrate FlatCAM Objects"))
  530. step_5.setToolTip(
  531. _("Adjust the FlatCAM objects\n"
  532. "with the factors determined and verified above.")
  533. )
  534. grid_lay.addWidget(step_5, 45, 0, 1, 3)
  535. self.adj_object_type_combo = QtWidgets.QComboBox()
  536. self.adj_object_type_combo.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  537. self.adj_object_type_combo.setCurrentIndex(0)
  538. self.adj_object_type_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  539. self.adj_object_type_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  540. self.adj_object_type_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  541. self.adj_object_type_label = QtWidgets.QLabel("%s:" % _("Adjusted object type"))
  542. self.adj_object_type_label.setToolTip(
  543. _("Type of the FlatCAM Object to be adjusted.")
  544. )
  545. grid_lay.addWidget(self.adj_object_type_label, 46, 0, 1, 3)
  546. grid_lay.addWidget(self.adj_object_type_combo, 47, 0, 1, 3)
  547. self.adj_object_combo = FCComboBox()
  548. self.adj_object_combo.setModel(self.app.collection)
  549. self.adj_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  550. self.adj_object_combo.setCurrentIndex(0)
  551. self.adj_object_label = QtWidgets.QLabel("%s:" % _("Adjusted object selection"))
  552. self.adj_object_label.setToolTip(
  553. _("The FlatCAM Object to be adjusted.")
  554. )
  555. grid_lay.addWidget(self.adj_object_label, 48, 0, 1, 3)
  556. grid_lay.addWidget(self.adj_object_combo, 49, 0, 1, 3)
  557. # ## Adjust Objects Button
  558. self.cal_button = QtWidgets.QPushButton(_("Calibrate"))
  559. self.cal_button.setToolTip(
  560. _("Adjust (scale and/or skew) the objects\n"
  561. "with the factors determined above.")
  562. )
  563. self.cal_button.setStyleSheet("""
  564. QPushButton
  565. {
  566. font-weight: bold;
  567. }
  568. """)
  569. grid_lay.addWidget(self.cal_button, 50, 0, 1, 3)
  570. separator_line2 = QtWidgets.QFrame()
  571. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  572. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  573. grid_lay.addWidget(separator_line2, 51, 0, 1, 3)
  574. grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0, 1, 3)
  575. self.layout.addStretch()
  576. # ## Reset Tool
  577. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  578. self.reset_button.setToolTip(
  579. _("Will reset the tool parameters.")
  580. )
  581. self.reset_button.setStyleSheet("""
  582. QPushButton
  583. {
  584. font-weight: bold;
  585. }
  586. """)
  587. self.layout.addWidget(self.reset_button)
  588. self.mr = None
  589. self.units = ''
  590. # here store 4 points to be used for calibration
  591. self.click_points = [[], [], [], []]
  592. # store the status of the grid
  593. self.grid_status_memory = None
  594. self.target_obj = None
  595. # if the mouse events are connected to a local method set this True
  596. self.local_connected = False
  597. # reference for the tab where to open and view the verification GCode
  598. self.gcode_editor_tab = None
  599. # calibrated object
  600. self.cal_object = None
  601. # ## Signals
  602. self.cal_source_radio.activated_custom.connect(self.on_cal_source_radio)
  603. self.obj_type_combo.currentIndexChanged.connect(self.on_obj_type_combo)
  604. self.adj_object_type_combo.currentIndexChanged.connect(self.on_adj_obj_type_combo)
  605. self.start_button.clicked.connect(self.on_start_collect_points)
  606. self.gcode_button.clicked.connect(self.generate_verification_gcode)
  607. self.adj_gcode_button.clicked.connect(self.generate_verification_gcode)
  608. self.generate_factors_button.clicked.connect(self.calculate_factors)
  609. self.scale_button.clicked.connect(self.on_scale_button)
  610. self.skew_button.clicked.connect(self.on_skew_button)
  611. self.cal_button.clicked.connect(self.on_cal_button_click)
  612. self.reset_button.clicked.connect(self.set_tool_ui)
  613. def run(self, toggle=True):
  614. self.app.report_usage("ToolCalibration()")
  615. if toggle:
  616. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  617. if self.app.ui.splitter.sizes()[0] == 0:
  618. self.app.ui.splitter.setSizes([1, 1])
  619. else:
  620. try:
  621. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  622. # if tab is populated with the tool but it does not have the focus, focus on it
  623. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  624. # focus on Tool Tab
  625. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  626. else:
  627. self.app.ui.splitter.setSizes([0, 1])
  628. except AttributeError:
  629. pass
  630. else:
  631. if self.app.ui.splitter.sizes()[0] == 0:
  632. self.app.ui.splitter.setSizes([1, 1])
  633. FlatCAMTool.run(self)
  634. self.set_tool_ui()
  635. self.app.ui.notebook.setTabText(2, _("Calibrate Tool"))
  636. def install(self, icon=None, separator=None, **kwargs):
  637. FlatCAMTool.install(self, icon, separator, shortcut='ALT+E', **kwargs)
  638. def set_tool_ui(self):
  639. self.units = self.app.defaults['units'].upper()
  640. if self.local_connected is True:
  641. self.disconnect_cal_events()
  642. self.reset_calibration_points()
  643. self.cal_source_radio.set_value(self.app.defaults['tools_cal_calsource'])
  644. self.travelz_entry.set_value(self.app.defaults['tools_cal_travelz'])
  645. self.verz_entry.set_value(self.app.defaults['tools_cal_verz'])
  646. self.zeroz_cb.set_value(self.app.defaults['tools_cal_zeroz'])
  647. self.toolchangez_entry.set_value(self.app.defaults['tools_cal_toolchangez'])
  648. self.toolchange_xy_entry.set_value(self.app.defaults['tools_cal_toolchange_xy'])
  649. self.second_point_radio.set_value(self.app.defaults['tools_cal_sec_point'])
  650. self.scalex_entry.set_value(1.0)
  651. self.scaley_entry.set_value(1.0)
  652. self.skewx_entry.set_value(0.0)
  653. self.skewy_entry.set_value(0.0)
  654. # calibrated object
  655. self.cal_object = None
  656. self.app.inform.emit('%s...' % _("Tool initialized"))
  657. def on_obj_type_combo(self):
  658. obj_type = self.obj_type_combo.currentIndex()
  659. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  660. self.object_combo.setCurrentIndex(0)
  661. def on_adj_obj_type_combo(self):
  662. obj_type = self.adj_object_type_combo.currentIndex()
  663. self.adj_object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  664. self.adj_object_combo.setCurrentIndex(0)
  665. def on_cal_source_radio(self, val):
  666. if val == 'object':
  667. self.obj_type_label.setDisabled(False)
  668. self.obj_type_combo.setDisabled(False)
  669. self.object_label.setDisabled(False)
  670. self.object_combo.setDisabled(False)
  671. else:
  672. self.obj_type_label.setDisabled(True)
  673. self.obj_type_combo.setDisabled(True)
  674. self.object_label.setDisabled(True)
  675. self.object_combo.setDisabled(True)
  676. def on_start_collect_points(self):
  677. if self.cal_source_radio.get_value() == 'object':
  678. selection_index = self.object_combo.currentIndex()
  679. model_index = self.app.collection.index(selection_index, 0, self.object_combo.rootModelIndex())
  680. try:
  681. self.target_obj = model_index.internalPointer().obj
  682. except AttributeError:
  683. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no source FlatCAM object selected..."))
  684. return
  685. # disengage the grid snapping since it will be hard to find the drills on grid
  686. if self.app.ui.grid_snap_btn.isChecked():
  687. self.grid_status_memory = True
  688. self.app.ui.grid_snap_btn.trigger()
  689. else:
  690. self.grid_status_memory = False
  691. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  692. if self.app.is_legacy is False:
  693. self.canvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  694. else:
  695. self.canvas.graph_event_disconnect(self.app.mr)
  696. self.local_connected = True
  697. self.reset_calibration_points()
  698. self.app.inform.emit(_("Get First calibration point. Bottom Left..."))
  699. def on_mouse_click_release(self, event):
  700. if self.app.is_legacy is False:
  701. event_pos = event.pos
  702. right_button = 2
  703. self.app.event_is_dragging = self.app.event_is_dragging
  704. else:
  705. event_pos = (event.xdata, event.ydata)
  706. right_button = 3
  707. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  708. pos_canvas = self.canvas.translate_coords(event_pos)
  709. if event.button == 1:
  710. click_pt = Point([pos_canvas[0], pos_canvas[1]])
  711. if self.app.selection_type is not None:
  712. # delete previous selection shape
  713. self.app.delete_selection_shape()
  714. self.app.selection_type = None
  715. else:
  716. if self.cal_source_radio.get_value() == 'object':
  717. if self.target_obj.kind.lower() == 'excellon':
  718. for tool, tool_dict in self.target_obj.tools.items():
  719. for geo in tool_dict['solid_geometry']:
  720. if click_pt.within(geo):
  721. center_pt = geo.centroid
  722. self.click_points.append(
  723. [
  724. float('%.*f' % (self.decimals, center_pt.x)),
  725. float('%.*f' % (self.decimals, center_pt.y))
  726. ]
  727. )
  728. self.check_points()
  729. else:
  730. for apid, apid_val in self.target_obj.apertures.items():
  731. for geo_el in apid_val['geometry']:
  732. if 'solid' in geo_el:
  733. if click_pt.within(geo_el['solid']):
  734. if isinstance(geo_el['follow'], Point):
  735. center_pt = geo_el['solid'].centroid
  736. self.click_points.append(
  737. [
  738. float('%.*f' % (self.decimals, center_pt.x)),
  739. float('%.*f' % (self.decimals, center_pt.y))
  740. ]
  741. )
  742. self.check_points()
  743. else:
  744. self.click_points.append(
  745. [
  746. float('%.*f' % (self.decimals, click_pt.x)),
  747. float('%.*f' % (self.decimals, click_pt.y))
  748. ]
  749. )
  750. self.check_points()
  751. elif event.button == right_button and self.app.event_is_dragging is False:
  752. if len(self.click_points) != 4:
  753. self.reset_calibration_points()
  754. self.disconnect_cal_events()
  755. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled by user request."))
  756. def check_points(self):
  757. if len(self.click_points) == 1:
  758. self.bottom_left_coordx_tgt.set_value(self.click_points[0][0])
  759. self.bottom_left_coordy_tgt.set_value(self.click_points[0][1])
  760. self.app.inform.emit(_("Get Second calibration point. Bottom Right..."))
  761. elif len(self.click_points) == 2:
  762. self.bottom_right_coordx_tgt.set_value(self.click_points[1][0])
  763. self.bottom_right_coordy_tgt.set_value(self.click_points[1][1])
  764. self.app.inform.emit(_("Get Third calibration point. Top Left..."))
  765. elif len(self.click_points) == 3:
  766. self.top_left_coordx_tgt.set_value(self.click_points[2][0])
  767. self.top_left_coordy_tgt.set_value(self.click_points[2][1])
  768. self.app.inform.emit(_("Get Forth calibration point. Top Right..."))
  769. elif len(self.click_points) == 4:
  770. self.top_right_coordx_tgt.set_value(self.click_points[3][0])
  771. self.top_right_coordy_tgt.set_value(self.click_points[3][1])
  772. self.app.inform.emit('[success] %s' % _("Done. All four points have been acquired."))
  773. self.disconnect_cal_events()
  774. def reset_calibration_points(self):
  775. self.click_points = list()
  776. self.bottom_left_coordx_tgt.set_value('')
  777. self.bottom_left_coordy_tgt.set_value('')
  778. self.bottom_right_coordx_tgt.set_value('')
  779. self.bottom_right_coordy_tgt.set_value('')
  780. self.top_left_coordx_tgt.set_value('')
  781. self.top_left_coordy_tgt.set_value('')
  782. self.top_right_coordx_tgt.set_value('')
  783. self.top_right_coordy_tgt.set_value('')
  784. self.bottom_right_coordx_found.set_value('')
  785. self.bottom_right_coordy_found.set_value('')
  786. self.top_left_coordx_found.set_value('')
  787. self.top_left_coordy_found.set_value('')
  788. def gcode_header(self):
  789. log.debug("ToolCalibration.gcode_header()")
  790. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  791. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  792. (str(self.app.version), str(self.app.version_date)) + '\n'
  793. gcode += '(Name: ' + _('Verification GCode for FlatCAM Calibrate Tool') + ')\n'
  794. gcode += '(Units: ' + self.units.upper() + ')\n\n'
  795. gcode += '(Created on ' + time_str + ')\n\n'
  796. gcode += 'G20\n' if self.units.upper() == 'IN' else 'G21\n'
  797. gcode += 'G90\n'
  798. gcode += 'G17\n'
  799. gcode += 'G94\n\n'
  800. return gcode
  801. def close_tab(self):
  802. for idx in range(self.app.ui.plot_tab_area.count()):
  803. if self.app.ui.plot_tab_area.tabText(idx) == _("Gcode Viewer"):
  804. wdg = self.app.ui.plot_tab_area.widget(idx)
  805. wdg.deleteLater()
  806. self.app.ui.plot_tab_area.removeTab(idx)
  807. def generate_verification_gcode(self):
  808. sec_point = self.second_point_radio.get_value()
  809. travel_z = '%.*f' % (self.decimals, self.travelz_entry.get_value())
  810. toolchange_z = '%.*f' % (self.decimals, self.toolchangez_entry.get_value())
  811. toolchange_xy_temp = self.toolchange_xy_entry.get_value().split(",")
  812. toolchange_xy = [float(eval(a)) for a in toolchange_xy_temp if a != '']
  813. verification_z = '%.*f' % (self.decimals, self.verz_entry.get_value())
  814. if len(self.click_points) != 4:
  815. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Four points are needed for GCode generation."))
  816. return 'fail'
  817. gcode = self.gcode_header()
  818. if self.zeroz_cb.get_value():
  819. gcode += 'M5\n'
  820. gcode += 'G00 Z%s\n' % toolchange_z
  821. if toolchange_xy:
  822. gcode += 'G00 X%s Y%s\n' % (toolchange_xy[0], toolchange_xy[1])
  823. gcode += 'M0\n'
  824. gcode += 'G01 Z0\n'
  825. gcode += 'M0\n'
  826. gcode += 'G00 Z%s\n' % toolchange_z
  827. gcode += 'M0\n'
  828. # first point: bottom - left -> ORIGIN set
  829. gcode += 'G00 Z%s\n' % travel_z
  830. gcode += 'G00 X%s Y%s\n' % (self.click_points[0][0], self.click_points[0][1])
  831. gcode += 'G01 Z%s\n' % verification_z
  832. gcode += 'M0\n'
  833. if sec_point == 'tl':
  834. # second point: top - left -> align the PCB to this point
  835. gcode += 'G00 Z%s\n' % travel_z
  836. gcode += 'G00 X%s Y%s\n' % (self.click_points[2][0], self.click_points[2][1])
  837. gcode += 'G01 Z%s\n' % verification_z
  838. gcode += 'M0\n'
  839. # third point: bottom - right -> check for scale on X axis or for skew on Y axis
  840. gcode += 'G00 Z%s\n' % travel_z
  841. gcode += 'G00 X%s Y%s\n' % (self.click_points[1][0], self.click_points[1][1])
  842. gcode += 'G01 Z%s\n' % verification_z
  843. gcode += 'M0\n'
  844. # forth point: top - right -> verification point
  845. gcode += 'G00 Z%s\n' % travel_z
  846. gcode += 'G00 X%s Y%s\n' % (self.click_points[3][0], self.click_points[3][1])
  847. gcode += 'G01 Z%s\n' % verification_z
  848. gcode += 'M0\n'
  849. else:
  850. # second point: bottom - right -> align the PCB to this point
  851. gcode += 'G00 Z%s\n' % travel_z
  852. gcode += 'G00 X%s Y%s\n' % (self.click_points[1][0], self.click_points[1][1])
  853. gcode += 'G01 Z%s\n' % verification_z
  854. gcode += 'M0\n'
  855. # third point: top - left -> check for scale on Y axis or for skew on X axis
  856. gcode += 'G00 Z%s\n' % travel_z
  857. gcode += 'G00 X%s Y%s\n' % (self.click_points[2][0], self.click_points[2][1])
  858. gcode += 'G01 Z%s\n' % verification_z
  859. gcode += 'M0\n'
  860. # forth point: top - right -> verification point
  861. gcode += 'G00 Z%s\n' % travel_z
  862. gcode += 'G00 X%s Y%s\n' % (self.click_points[3][0], self.click_points[3][1])
  863. gcode += 'G01 Z%s\n' % verification_z
  864. gcode += 'M0\n'
  865. # return to (toolchange_xy[0], toolchange_xy[1], toolchange_z) point for toolchange event
  866. gcode += 'G00 Z%s\n' % travel_z
  867. gcode += 'G00 X0 Y0\n'
  868. gcode += 'G00 Z%s\n' % toolchange_z
  869. if toolchange_xy:
  870. gcode += 'G00 X%s Y%s\n' % (toolchange_xy[0], toolchange_xy[1])
  871. gcode += 'M2'
  872. self.gcode_editor_tab = TextEditor(app=self.app, plain_text=True)
  873. # add the tab if it was closed
  874. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Gcode Viewer"))
  875. self.gcode_editor_tab.setObjectName('gcode_viewer_tab')
  876. # delete the absolute and relative position and messages in the infobar
  877. self.app.ui.position_label.setText("")
  878. self.app.ui.rel_position_label.setText("")
  879. # first clear previous text in text editor (if any)
  880. self.gcode_editor_tab.code_editor.clear()
  881. self.gcode_editor_tab.code_editor.setReadOnly(False)
  882. self.gcode_editor_tab.code_editor.completer_enable = False
  883. self.gcode_editor_tab.buttonRun.hide()
  884. # Switch plot_area to CNCJob tab
  885. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  886. self.gcode_editor_tab.t_frame.hide()
  887. # then append the text from GCode to the text editor
  888. try:
  889. self.gcode_editor_tab.code_editor.setPlainText(gcode)
  890. except Exception as e:
  891. self.app.inform.emit('[ERROR] %s %s' % ('ERROR -->', str(e)))
  892. return
  893. self.gcode_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  894. self.gcode_editor_tab.t_frame.show()
  895. self.app.proc_container.view.set_idle()
  896. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  897. _filter_ = "G-Code Files (*.nc);;All Files (*.*)"
  898. self.gcode_editor_tab.buttonSave.clicked.disconnect()
  899. self.gcode_editor_tab.buttonSave.clicked.connect(
  900. lambda: self.gcode_editor_tab.handleSaveGCode(name='fc_ver_gcode', filt=_filter_, callback=self.close_tab))
  901. def calculate_factors(self):
  902. origin_x = self.click_points[0][0]
  903. origin_y = self.click_points[0][1]
  904. top_left_x = self.click_points[2][0]
  905. top_left_y = self.click_points[2][1]
  906. bot_right_x = self.click_points[1][0]
  907. bot_right_y = self.click_points[1][1]
  908. try:
  909. top_left_dx = float(self.top_left_coordx_found.get_value())
  910. except TypeError:
  911. top_left_dx = top_left_x
  912. try:
  913. top_left_dy = float(self.top_left_coordy_found.get_value())
  914. except TypeError:
  915. top_left_dy = top_left_y
  916. try:
  917. bot_right_dx = float(self.bottom_right_coordx_found.get_value())
  918. except TypeError:
  919. bot_right_dx = bot_right_x
  920. try:
  921. bot_right_dy = float(self.bottom_right_coordy_found.get_value())
  922. except TypeError:
  923. bot_right_dy = bot_right_y
  924. # ------------------------------------------------------------------------------- #
  925. # --------------------------- FACTORS CALCULUS ---------------------------------- #
  926. # ------------------------------------------------------------------------------- #
  927. if bot_right_dx != float('%.*f' % (self.decimals, bot_right_x)):
  928. # we have scale on X
  929. scale_x = (bot_right_dx / (bot_right_x - origin_x)) + 1
  930. self.scalex_entry.set_value(scale_x)
  931. if top_left_dy != float('%.*f' % (self.decimals, top_left_y)):
  932. # we have scale on Y
  933. scale_y = (top_left_dy / (top_left_y - origin_y)) + 1
  934. self.scaley_entry.set_value(scale_y)
  935. if top_left_dx != float('%.*f' % (self.decimals, top_left_x)):
  936. # we have skew on X
  937. dx = top_left_dx
  938. dy = top_left_y - origin_y
  939. skew_angle_x = math.degrees(math.atan(dx / dy))
  940. self.skewx_entry.set_value(skew_angle_x)
  941. if bot_right_dy != float('%.*f' % (self.decimals, bot_right_y)):
  942. # we have skew on Y
  943. dx = bot_right_x - origin_x
  944. dy = bot_right_dy + origin_y
  945. skew_angle_y = math.degrees(math.atan(dy / dx))
  946. self.skewy_entry.set_value(skew_angle_y)
  947. @property
  948. def target_values_in_table(self):
  949. self.click_points[0][0] = self.bottom_left_coordx_tgt.get_value()
  950. self.click_points[0][1] = self.bottom_left_coordy_tgt.get_value()
  951. self.click_points[1][0] = self.bottom_right_coordx_tgt.get_value()
  952. self.click_points[1][1] = self.bottom_right_coordy_tgt.get_value()
  953. self.click_points[2][0] = self.top_left_coordx_tgt.get_value()
  954. self.click_points[2][1] = self.top_left_coordy_tgt.get_value()
  955. self.click_points[3][0] = self.top_right_coordx_tgt.get_value()
  956. self.click_points[3][1] = self.top_right_coordy_tgt.get_value()
  957. return self.click_points
  958. @target_values_in_table.setter
  959. def target_values_in_table(self, param):
  960. bl_pt, br_pt, tl_pt, tr_pt = param
  961. self.click_points[0] = [bl_pt[0], bl_pt[1]]
  962. self.click_points[1] = [br_pt[0], br_pt[1]]
  963. self.click_points[2] = [tl_pt[0], tl_pt[1]]
  964. self.click_points[3] = [tr_pt[0], tr_pt[1]]
  965. self.bottom_left_coordx_tgt.set_value(float('%.*f' % (self.decimals, bl_pt[0])))
  966. self.bottom_left_coordy_tgt.set_value(float('%.*f' % (self.decimals, bl_pt[1])))
  967. self.bottom_right_coordx_tgt.set_value(float('%.*f' % (self.decimals, br_pt[0])))
  968. self.bottom_right_coordy_tgt.set_value(float('%.*f' % (self.decimals, br_pt[1])))
  969. self.top_left_coordx_tgt.set_value(float('%.*f' % (self.decimals, tl_pt[0])))
  970. self.top_left_coordy_tgt.set_value(float('%.*f' % (self.decimals, tl_pt[1])))
  971. self.top_right_coordx_tgt.set_value(float('%.*f' % (self.decimals, tr_pt[0])))
  972. self.top_right_coordy_tgt.set_value(float('%.*f' % (self.decimals, tr_pt[1])))
  973. def on_scale_button(self):
  974. scalex_fact = self.scalex_entry.get_value()
  975. scaley_fact = self.scaley_entry.get_value()
  976. bl, br, tl, tr = self.target_values_in_table
  977. bl_geo = Point(bl[0], bl[1])
  978. br_geo = Point(br[0], br[1])
  979. tl_geo = Point(tl[0], tl[1])
  980. tr_geo = Point(tr[0], tr[1])
  981. bl_scaled = scale(bl_geo, xfact=scalex_fact, yfact=scaley_fact, origin=(bl[0], bl[1]))
  982. br_scaled = scale(br_geo, xfact=scalex_fact, yfact=scaley_fact, origin=(bl[0], bl[1]))
  983. tl_scaled = scale(tl_geo, xfact=scalex_fact, yfact=scaley_fact, origin=(bl[0], bl[1]))
  984. tr_scaled = scale(tr_geo, xfact=scalex_fact, yfact=scaley_fact, origin=(bl[0], bl[1]))
  985. scaled_values = [
  986. [bl_scaled.x, bl_scaled.y],
  987. [br_scaled.x, br_scaled.y],
  988. [tl_scaled.x, tl_scaled.y],
  989. [tr_scaled.x, tr_scaled.y]
  990. ]
  991. self.target_values_in_table = scaled_values
  992. def on_skew_button(self):
  993. skewx_angle = self.skewx_entry.get_value()
  994. skewy_angle = self.skewy_entry.get_value()
  995. bl, br, tl, tr = self.target_values_in_table
  996. bl_geo = Point(bl[0], bl[1])
  997. br_geo = Point(br[0], br[1])
  998. tl_geo = Point(tl[0], tl[1])
  999. tr_geo = Point(tr[0], tr[1])
  1000. bl_skewed = skew(bl_geo, xs=skewx_angle, ys=skewy_angle, origin=(bl[0], bl[1]))
  1001. br_skewed = skew(br_geo, xs=skewx_angle, ys=skewy_angle, origin=(bl[0], bl[1]))
  1002. tl_skewed = skew(tl_geo, xs=skewx_angle, ys=skewy_angle, origin=(bl[0], bl[1]))
  1003. tr_skewed = skew(tr_geo, xs=skewx_angle, ys=skewy_angle, origin=(bl[0], bl[1]))
  1004. skewed_values = [
  1005. [bl_skewed.x, bl_skewed.y],
  1006. [br_skewed.x, br_skewed.y],
  1007. [tl_skewed.x, tl_skewed.y],
  1008. [tr_skewed.x, tr_skewed.y]
  1009. ]
  1010. self.target_values_in_table = skewed_values
  1011. def on_cal_button_click(self):
  1012. # get the FlatCAM object to calibrate
  1013. selection_index = self.adj_object_combo.currentIndex()
  1014. model_index = self.app.collection.index(selection_index, 0, self.adj_object_combo.rootModelIndex())
  1015. try:
  1016. self.cal_object = model_index.internalPointer().obj
  1017. except Exception as e:
  1018. log.debug("ToolCalibration.on_cal_button_click() --> %s" % str(e))
  1019. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no FlatCAM object selected..."))
  1020. return 'fail'
  1021. obj_name = self.cal_object.options["name"] + "_calibrated"
  1022. self.app.worker_task.emit({'fcn': self.new_calibrated_object, 'params': [obj_name]})
  1023. def new_calibrated_object(self, obj_name):
  1024. try:
  1025. origin_x = self.click_points[0][0]
  1026. origin_y = self.click_points[0][1]
  1027. except IndexError as e:
  1028. log.debug("ToolCalibration.new_calibrated_object() --> %s" % str(e))
  1029. return 'fail'
  1030. scalex = self.scalex_entry.get_value()
  1031. scaley = self.scaley_entry.get_value()
  1032. skewx = self.skewx_entry.get_value()
  1033. skewy = self.skewy_entry.get_value()
  1034. # create a new object adjusted (calibrated)
  1035. def initialize_geometry(obj_init, app):
  1036. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  1037. try:
  1038. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  1039. except AttributeError:
  1040. pass
  1041. try:
  1042. obj_init.apertures = deepcopy(obj.apertures)
  1043. except AttributeError:
  1044. pass
  1045. try:
  1046. if obj.tools:
  1047. obj_init.tools = deepcopy(obj.tools)
  1048. except Exception as ee:
  1049. log.debug("App.on_copy_object() --> %s" % str(ee))
  1050. obj_init.scale(xfactor=scalex, yfactor=scaley, point=(origin_x, origin_y))
  1051. obj_init.skew(angle_x=skewx, angle_y=skewy, point=(origin_x, origin_y))
  1052. try:
  1053. obj_init.source_file = deepcopy(obj.source_file)
  1054. except (AttributeError, TypeError):
  1055. pass
  1056. def initialize_gerber(obj_init, app):
  1057. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  1058. try:
  1059. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  1060. except AttributeError:
  1061. pass
  1062. try:
  1063. obj_init.apertures = deepcopy(obj.apertures)
  1064. except AttributeError:
  1065. pass
  1066. try:
  1067. if obj.tools:
  1068. obj_init.tools = deepcopy(obj.tools)
  1069. except Exception as err:
  1070. log.debug("App.on_copy_object() --> %s" % str(err))
  1071. obj_init.scale(xfactor=scalex, yfactor=scaley, point=(origin_x, origin_y))
  1072. obj_init.skew(angle_x=skewx, angle_y=skewy, point=(origin_x, origin_y))
  1073. try:
  1074. obj_init.source_file = self.export_gerber(obj_name=obj_name, filename=None, local_use=obj_init,
  1075. use_thread=False)
  1076. except (AttributeError, TypeError):
  1077. pass
  1078. def initialize_excellon(obj_init, app):
  1079. obj_init.tools = deepcopy(obj.tools)
  1080. # drills are offset, so they need to be deep copied
  1081. obj_init.drills = deepcopy(obj.drills)
  1082. # slots are offset, so they need to be deep copied
  1083. obj_init.slots = deepcopy(obj.slots)
  1084. obj_init.scale(xfactor=scalex, yfactor=scaley, point=(origin_x, origin_y))
  1085. obj_init.skew(angle_x=skewx, angle_y=skewy, point=(origin_x, origin_y))
  1086. obj_init.create_geometry()
  1087. obj_init.source_file = self.app.export_excellon(obj_name=obj_name, local_use=obj, filename=None,
  1088. use_thread=False)
  1089. obj = self.cal_object
  1090. obj_name = obj_name
  1091. if obj is None:
  1092. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no FlatCAM object selected..."))
  1093. log.debug("ToolCalibration.new_calibrated_object() --> No object to calibrate")
  1094. return 'fail'
  1095. try:
  1096. if obj.kind.lower() == 'excellon':
  1097. self.app.new_object("excellon", str(obj_name), initialize_excellon)
  1098. elif obj.kind.lower() == 'gerber':
  1099. self.app.new_object("gerber", str(obj_name), initialize_gerber)
  1100. elif obj.kind.lower() == 'geometry':
  1101. self.app.new_object("geometry", str(obj_name), initialize_geometry)
  1102. except Exception as e:
  1103. log.debug("ToolCalibration.new_calibrated_object() --> %s" % str(e))
  1104. return "Operation failed: %s" % str(e)
  1105. def disconnect_cal_events(self):
  1106. # restore the Grid snapping if it was active before
  1107. if self.grid_status_memory is True:
  1108. self.app.ui.grid_snap_btn.trigger()
  1109. self.app.mr = self.canvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1110. if self.app.is_legacy is False:
  1111. self.canvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1112. else:
  1113. self.canvas.graph_event_disconnect(self.mr)
  1114. self.local_connected = False
  1115. def reset_fields(self):
  1116. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  1117. self.adj_exc_object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  1118. self.adj_geo_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  1119. # end of file