ToolCalibration.py 56 KB

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