meerk40t 0.9.3001__py2.py3-none-any.whl → 0.9.7010__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (445) hide show
  1. meerk40t/__init__.py +1 -1
  2. meerk40t/balormk/balor_params.py +167 -167
  3. meerk40t/balormk/clone_loader.py +457 -457
  4. meerk40t/balormk/controller.py +1566 -1512
  5. meerk40t/balormk/cylindermod.py +64 -0
  6. meerk40t/balormk/device.py +966 -1959
  7. meerk40t/balormk/driver.py +778 -591
  8. meerk40t/balormk/galvo_commands.py +1195 -0
  9. meerk40t/balormk/gui/balorconfig.py +237 -111
  10. meerk40t/balormk/gui/balorcontroller.py +191 -184
  11. meerk40t/balormk/gui/baloroperationproperties.py +116 -115
  12. meerk40t/balormk/gui/corscene.py +845 -0
  13. meerk40t/balormk/gui/gui.py +179 -147
  14. meerk40t/balormk/livelightjob.py +466 -382
  15. meerk40t/balormk/mock_connection.py +131 -109
  16. meerk40t/balormk/plugin.py +133 -135
  17. meerk40t/balormk/usb_connection.py +306 -301
  18. meerk40t/camera/__init__.py +1 -1
  19. meerk40t/camera/camera.py +514 -397
  20. meerk40t/camera/gui/camerapanel.py +1241 -1095
  21. meerk40t/camera/gui/gui.py +58 -58
  22. meerk40t/camera/plugin.py +441 -399
  23. meerk40t/ch341/__init__.py +27 -27
  24. meerk40t/ch341/ch341device.py +628 -628
  25. meerk40t/ch341/libusb.py +595 -589
  26. meerk40t/ch341/mock.py +171 -171
  27. meerk40t/ch341/windriver.py +157 -157
  28. meerk40t/constants.py +13 -0
  29. meerk40t/core/__init__.py +1 -1
  30. meerk40t/core/bindalias.py +550 -539
  31. meerk40t/core/core.py +47 -47
  32. meerk40t/core/cutcode/cubiccut.py +73 -73
  33. meerk40t/core/cutcode/cutcode.py +315 -312
  34. meerk40t/core/cutcode/cutgroup.py +141 -137
  35. meerk40t/core/cutcode/cutobject.py +192 -185
  36. meerk40t/core/cutcode/dwellcut.py +37 -37
  37. meerk40t/core/cutcode/gotocut.py +29 -29
  38. meerk40t/core/cutcode/homecut.py +29 -29
  39. meerk40t/core/cutcode/inputcut.py +34 -34
  40. meerk40t/core/cutcode/linecut.py +33 -33
  41. meerk40t/core/cutcode/outputcut.py +34 -34
  42. meerk40t/core/cutcode/plotcut.py +335 -335
  43. meerk40t/core/cutcode/quadcut.py +61 -61
  44. meerk40t/core/cutcode/rastercut.py +168 -148
  45. meerk40t/core/cutcode/waitcut.py +34 -34
  46. meerk40t/core/cutplan.py +1843 -1316
  47. meerk40t/core/drivers.py +330 -329
  48. meerk40t/core/elements/align.py +801 -669
  49. meerk40t/core/elements/branches.py +1844 -1507
  50. meerk40t/core/elements/clipboard.py +229 -219
  51. meerk40t/core/elements/element_treeops.py +4561 -2837
  52. meerk40t/core/elements/element_types.py +125 -105
  53. meerk40t/core/elements/elements.py +4329 -3617
  54. meerk40t/core/elements/files.py +117 -64
  55. meerk40t/core/elements/geometry.py +473 -224
  56. meerk40t/core/elements/grid.py +467 -316
  57. meerk40t/core/elements/materials.py +158 -94
  58. meerk40t/core/elements/notes.py +50 -38
  59. meerk40t/core/elements/offset_clpr.py +933 -912
  60. meerk40t/core/elements/offset_mk.py +963 -955
  61. meerk40t/core/elements/penbox.py +339 -267
  62. meerk40t/core/elements/placements.py +300 -83
  63. meerk40t/core/elements/render.py +785 -687
  64. meerk40t/core/elements/shapes.py +2618 -2092
  65. meerk40t/core/elements/trace.py +651 -563
  66. meerk40t/core/elements/tree_commands.py +415 -409
  67. meerk40t/core/elements/undo_redo.py +116 -58
  68. meerk40t/core/elements/wordlist.py +319 -200
  69. meerk40t/core/exceptions.py +9 -9
  70. meerk40t/core/laserjob.py +220 -220
  71. meerk40t/core/logging.py +63 -63
  72. meerk40t/core/node/blobnode.py +83 -86
  73. meerk40t/core/node/bootstrap.py +105 -103
  74. meerk40t/core/node/branch_elems.py +40 -31
  75. meerk40t/core/node/branch_ops.py +45 -38
  76. meerk40t/core/node/branch_regmark.py +48 -41
  77. meerk40t/core/node/cutnode.py +29 -32
  78. meerk40t/core/node/effect_hatch.py +375 -257
  79. meerk40t/core/node/effect_warp.py +398 -0
  80. meerk40t/core/node/effect_wobble.py +441 -309
  81. meerk40t/core/node/elem_ellipse.py +404 -309
  82. meerk40t/core/node/elem_image.py +1082 -801
  83. meerk40t/core/node/elem_line.py +358 -292
  84. meerk40t/core/node/elem_path.py +259 -201
  85. meerk40t/core/node/elem_point.py +129 -102
  86. meerk40t/core/node/elem_polyline.py +310 -246
  87. meerk40t/core/node/elem_rect.py +376 -286
  88. meerk40t/core/node/elem_text.py +445 -418
  89. meerk40t/core/node/filenode.py +59 -40
  90. meerk40t/core/node/groupnode.py +138 -74
  91. meerk40t/core/node/image_processed.py +777 -766
  92. meerk40t/core/node/image_raster.py +156 -113
  93. meerk40t/core/node/layernode.py +31 -31
  94. meerk40t/core/node/mixins.py +135 -107
  95. meerk40t/core/node/node.py +1427 -1304
  96. meerk40t/core/node/nutils.py +117 -114
  97. meerk40t/core/node/op_cut.py +462 -335
  98. meerk40t/core/node/op_dots.py +296 -251
  99. meerk40t/core/node/op_engrave.py +414 -311
  100. meerk40t/core/node/op_image.py +755 -369
  101. meerk40t/core/node/op_raster.py +787 -522
  102. meerk40t/core/node/place_current.py +37 -40
  103. meerk40t/core/node/place_point.py +329 -126
  104. meerk40t/core/node/refnode.py +58 -47
  105. meerk40t/core/node/rootnode.py +225 -219
  106. meerk40t/core/node/util_console.py +48 -48
  107. meerk40t/core/node/util_goto.py +84 -65
  108. meerk40t/core/node/util_home.py +61 -61
  109. meerk40t/core/node/util_input.py +102 -102
  110. meerk40t/core/node/util_output.py +102 -102
  111. meerk40t/core/node/util_wait.py +65 -65
  112. meerk40t/core/parameters.py +709 -707
  113. meerk40t/core/planner.py +875 -785
  114. meerk40t/core/plotplanner.py +656 -652
  115. meerk40t/core/space.py +120 -113
  116. meerk40t/core/spoolers.py +706 -705
  117. meerk40t/core/svg_io.py +1836 -1549
  118. meerk40t/core/treeop.py +534 -445
  119. meerk40t/core/undos.py +278 -124
  120. meerk40t/core/units.py +784 -680
  121. meerk40t/core/view.py +393 -322
  122. meerk40t/core/webhelp.py +62 -62
  123. meerk40t/core/wordlist.py +513 -504
  124. meerk40t/cylinder/cylinder.py +247 -0
  125. meerk40t/cylinder/gui/cylindersettings.py +41 -0
  126. meerk40t/cylinder/gui/gui.py +24 -0
  127. meerk40t/device/__init__.py +1 -1
  128. meerk40t/device/basedevice.py +322 -123
  129. meerk40t/device/devicechoices.py +50 -0
  130. meerk40t/device/dummydevice.py +163 -128
  131. meerk40t/device/gui/defaultactions.py +618 -602
  132. meerk40t/device/gui/effectspanel.py +114 -0
  133. meerk40t/device/gui/formatterpanel.py +253 -290
  134. meerk40t/device/gui/warningpanel.py +337 -260
  135. meerk40t/device/mixins.py +13 -13
  136. meerk40t/dxf/__init__.py +1 -1
  137. meerk40t/dxf/dxf_io.py +766 -554
  138. meerk40t/dxf/plugin.py +47 -35
  139. meerk40t/external_plugins.py +79 -79
  140. meerk40t/external_plugins_build.py +28 -28
  141. meerk40t/extra/cag.py +112 -116
  142. meerk40t/extra/coolant.py +403 -0
  143. meerk40t/extra/encode_detect.py +198 -0
  144. meerk40t/extra/ezd.py +1165 -1165
  145. meerk40t/extra/hershey.py +835 -340
  146. meerk40t/extra/imageactions.py +322 -316
  147. meerk40t/extra/inkscape.py +630 -622
  148. meerk40t/extra/lbrn.py +424 -424
  149. meerk40t/extra/outerworld.py +284 -0
  150. meerk40t/extra/param_functions.py +1542 -1556
  151. meerk40t/extra/potrace.py +257 -253
  152. meerk40t/extra/serial_exchange.py +118 -0
  153. meerk40t/extra/updater.py +602 -453
  154. meerk40t/extra/vectrace.py +147 -146
  155. meerk40t/extra/winsleep.py +83 -83
  156. meerk40t/extra/xcs_reader.py +597 -0
  157. meerk40t/fill/fills.py +781 -335
  158. meerk40t/fill/patternfill.py +1061 -1061
  159. meerk40t/fill/patterns.py +614 -567
  160. meerk40t/grbl/control.py +87 -87
  161. meerk40t/grbl/controller.py +990 -903
  162. meerk40t/grbl/device.py +1081 -768
  163. meerk40t/grbl/driver.py +989 -771
  164. meerk40t/grbl/emulator.py +532 -497
  165. meerk40t/grbl/gcodejob.py +783 -767
  166. meerk40t/grbl/gui/grblconfiguration.py +373 -298
  167. meerk40t/grbl/gui/grblcontroller.py +485 -271
  168. meerk40t/grbl/gui/grblhardwareconfig.py +269 -153
  169. meerk40t/grbl/gui/grbloperationconfig.py +105 -0
  170. meerk40t/grbl/gui/gui.py +147 -116
  171. meerk40t/grbl/interpreter.py +44 -44
  172. meerk40t/grbl/loader.py +22 -22
  173. meerk40t/grbl/mock_connection.py +56 -56
  174. meerk40t/grbl/plugin.py +294 -264
  175. meerk40t/grbl/serial_connection.py +93 -88
  176. meerk40t/grbl/tcp_connection.py +81 -79
  177. meerk40t/grbl/ws_connection.py +112 -0
  178. meerk40t/gui/__init__.py +1 -1
  179. meerk40t/gui/about.py +2042 -296
  180. meerk40t/gui/alignment.py +1644 -1608
  181. meerk40t/gui/autoexec.py +199 -0
  182. meerk40t/gui/basicops.py +791 -670
  183. meerk40t/gui/bufferview.py +77 -71
  184. meerk40t/gui/busy.py +170 -133
  185. meerk40t/gui/choicepropertypanel.py +1673 -1469
  186. meerk40t/gui/consolepanel.py +706 -542
  187. meerk40t/gui/devicepanel.py +687 -581
  188. meerk40t/gui/dialogoptions.py +110 -107
  189. meerk40t/gui/executejob.py +316 -306
  190. meerk40t/gui/fonts.py +90 -90
  191. meerk40t/gui/functionwrapper.py +252 -0
  192. meerk40t/gui/gui_mixins.py +729 -0
  193. meerk40t/gui/guicolors.py +205 -182
  194. meerk40t/gui/help_assets/help_assets.py +218 -201
  195. meerk40t/gui/helper.py +154 -0
  196. meerk40t/gui/hersheymanager.py +1430 -846
  197. meerk40t/gui/icons.py +3422 -2747
  198. meerk40t/gui/imagesplitter.py +555 -508
  199. meerk40t/gui/keymap.py +354 -344
  200. meerk40t/gui/laserpanel.py +892 -806
  201. meerk40t/gui/laserrender.py +1470 -1232
  202. meerk40t/gui/lasertoolpanel.py +805 -793
  203. meerk40t/gui/magnetoptions.py +436 -0
  204. meerk40t/gui/materialmanager.py +2917 -0
  205. meerk40t/gui/materialtest.py +1722 -1694
  206. meerk40t/gui/mkdebug.py +646 -359
  207. meerk40t/gui/mwindow.py +163 -140
  208. meerk40t/gui/navigationpanels.py +2605 -2467
  209. meerk40t/gui/notes.py +143 -142
  210. meerk40t/gui/opassignment.py +414 -410
  211. meerk40t/gui/operation_info.py +310 -299
  212. meerk40t/gui/plugin.py +494 -328
  213. meerk40t/gui/position.py +714 -669
  214. meerk40t/gui/preferences.py +901 -650
  215. meerk40t/gui/propertypanels/attributes.py +1461 -1131
  216. meerk40t/gui/propertypanels/blobproperty.py +117 -114
  217. meerk40t/gui/propertypanels/consoleproperty.py +83 -80
  218. meerk40t/gui/propertypanels/gotoproperty.py +77 -0
  219. meerk40t/gui/propertypanels/groupproperties.py +223 -217
  220. meerk40t/gui/propertypanels/hatchproperty.py +489 -469
  221. meerk40t/gui/propertypanels/imageproperty.py +2244 -1384
  222. meerk40t/gui/propertypanels/inputproperty.py +59 -58
  223. meerk40t/gui/propertypanels/opbranchproperties.py +82 -80
  224. meerk40t/gui/propertypanels/operationpropertymain.py +1890 -1638
  225. meerk40t/gui/propertypanels/outputproperty.py +59 -58
  226. meerk40t/gui/propertypanels/pathproperty.py +389 -380
  227. meerk40t/gui/propertypanels/placementproperty.py +1214 -383
  228. meerk40t/gui/propertypanels/pointproperty.py +140 -136
  229. meerk40t/gui/propertypanels/propertywindow.py +313 -181
  230. meerk40t/gui/propertypanels/rasterwizardpanels.py +996 -912
  231. meerk40t/gui/propertypanels/regbranchproperties.py +76 -0
  232. meerk40t/gui/propertypanels/textproperty.py +770 -755
  233. meerk40t/gui/propertypanels/waitproperty.py +56 -55
  234. meerk40t/gui/propertypanels/warpproperty.py +121 -0
  235. meerk40t/gui/propertypanels/wobbleproperty.py +255 -204
  236. meerk40t/gui/ribbon.py +2468 -2210
  237. meerk40t/gui/scene/scene.py +1100 -1051
  238. meerk40t/gui/scene/sceneconst.py +22 -22
  239. meerk40t/gui/scene/scenepanel.py +439 -349
  240. meerk40t/gui/scene/scenespacewidget.py +365 -365
  241. meerk40t/gui/scene/widget.py +518 -505
  242. meerk40t/gui/scenewidgets/affinemover.py +215 -215
  243. meerk40t/gui/scenewidgets/attractionwidget.py +315 -309
  244. meerk40t/gui/scenewidgets/bedwidget.py +120 -97
  245. meerk40t/gui/scenewidgets/elementswidget.py +137 -107
  246. meerk40t/gui/scenewidgets/gridwidget.py +785 -745
  247. meerk40t/gui/scenewidgets/guidewidget.py +765 -765
  248. meerk40t/gui/scenewidgets/laserpathwidget.py +66 -66
  249. meerk40t/gui/scenewidgets/machineoriginwidget.py +86 -86
  250. meerk40t/gui/scenewidgets/nodeselector.py +28 -28
  251. meerk40t/gui/scenewidgets/rectselectwidget.py +589 -346
  252. meerk40t/gui/scenewidgets/relocatewidget.py +33 -33
  253. meerk40t/gui/scenewidgets/reticlewidget.py +83 -83
  254. meerk40t/gui/scenewidgets/selectionwidget.py +2952 -2756
  255. meerk40t/gui/simpleui.py +357 -333
  256. meerk40t/gui/simulation.py +2431 -2094
  257. meerk40t/gui/snapoptions.py +208 -203
  258. meerk40t/gui/spoolerpanel.py +1227 -1180
  259. meerk40t/gui/statusbarwidgets/defaultoperations.py +480 -353
  260. meerk40t/gui/statusbarwidgets/infowidget.py +520 -483
  261. meerk40t/gui/statusbarwidgets/opassignwidget.py +356 -355
  262. meerk40t/gui/statusbarwidgets/selectionwidget.py +172 -171
  263. meerk40t/gui/statusbarwidgets/shapepropwidget.py +754 -236
  264. meerk40t/gui/statusbarwidgets/statusbar.py +272 -260
  265. meerk40t/gui/statusbarwidgets/statusbarwidget.py +268 -270
  266. meerk40t/gui/statusbarwidgets/strokewidget.py +267 -251
  267. meerk40t/gui/themes.py +200 -78
  268. meerk40t/gui/tips.py +591 -0
  269. meerk40t/gui/toolwidgets/circlebrush.py +35 -35
  270. meerk40t/gui/toolwidgets/toolcircle.py +248 -242
  271. meerk40t/gui/toolwidgets/toolcontainer.py +82 -77
  272. meerk40t/gui/toolwidgets/tooldraw.py +97 -90
  273. meerk40t/gui/toolwidgets/toolellipse.py +219 -212
  274. meerk40t/gui/toolwidgets/toolimagecut.py +25 -132
  275. meerk40t/gui/toolwidgets/toolline.py +39 -144
  276. meerk40t/gui/toolwidgets/toollinetext.py +79 -236
  277. meerk40t/gui/toolwidgets/toollinetext_inline.py +296 -0
  278. meerk40t/gui/toolwidgets/toolmeasure.py +160 -216
  279. meerk40t/gui/toolwidgets/toolnodeedit.py +2088 -2074
  280. meerk40t/gui/toolwidgets/toolnodemove.py +92 -94
  281. meerk40t/gui/toolwidgets/toolparameter.py +754 -668
  282. meerk40t/gui/toolwidgets/toolplacement.py +108 -108
  283. meerk40t/gui/toolwidgets/toolpoint.py +68 -59
  284. meerk40t/gui/toolwidgets/toolpointlistbuilder.py +294 -0
  285. meerk40t/gui/toolwidgets/toolpointmove.py +183 -0
  286. meerk40t/gui/toolwidgets/toolpolygon.py +288 -403
  287. meerk40t/gui/toolwidgets/toolpolyline.py +38 -196
  288. meerk40t/gui/toolwidgets/toolrect.py +211 -207
  289. meerk40t/gui/toolwidgets/toolrelocate.py +72 -72
  290. meerk40t/gui/toolwidgets/toolribbon.py +598 -113
  291. meerk40t/gui/toolwidgets/tooltabedit.py +546 -0
  292. meerk40t/gui/toolwidgets/tooltext.py +98 -89
  293. meerk40t/gui/toolwidgets/toolvector.py +213 -204
  294. meerk40t/gui/toolwidgets/toolwidget.py +39 -39
  295. meerk40t/gui/usbconnect.py +98 -91
  296. meerk40t/gui/utilitywidgets/buttonwidget.py +18 -18
  297. meerk40t/gui/utilitywidgets/checkboxwidget.py +90 -90
  298. meerk40t/gui/utilitywidgets/controlwidget.py +14 -14
  299. meerk40t/gui/utilitywidgets/cyclocycloidwidget.py +343 -340
  300. meerk40t/gui/utilitywidgets/debugwidgets.py +148 -0
  301. meerk40t/gui/utilitywidgets/handlewidget.py +27 -27
  302. meerk40t/gui/utilitywidgets/harmonograph.py +450 -447
  303. meerk40t/gui/utilitywidgets/openclosewidget.py +40 -40
  304. meerk40t/gui/utilitywidgets/rotationwidget.py +54 -54
  305. meerk40t/gui/utilitywidgets/scalewidget.py +75 -75
  306. meerk40t/gui/utilitywidgets/seekbarwidget.py +183 -183
  307. meerk40t/gui/utilitywidgets/togglewidget.py +142 -142
  308. meerk40t/gui/utilitywidgets/toolbarwidget.py +8 -8
  309. meerk40t/gui/wordlisteditor.py +985 -931
  310. meerk40t/gui/wxmeerk40t.py +1444 -1169
  311. meerk40t/gui/wxmmain.py +5578 -4112
  312. meerk40t/gui/wxmribbon.py +1591 -1076
  313. meerk40t/gui/wxmscene.py +1635 -1453
  314. meerk40t/gui/wxmtree.py +2410 -2089
  315. meerk40t/gui/wxutils.py +1769 -1099
  316. meerk40t/gui/zmatrix.py +102 -102
  317. meerk40t/image/__init__.py +1 -1
  318. meerk40t/image/dither.py +429 -0
  319. meerk40t/image/imagetools.py +2778 -2269
  320. meerk40t/internal_plugins.py +150 -130
  321. meerk40t/kernel/__init__.py +63 -12
  322. meerk40t/kernel/channel.py +259 -212
  323. meerk40t/kernel/context.py +538 -538
  324. meerk40t/kernel/exceptions.py +41 -41
  325. meerk40t/kernel/functions.py +463 -414
  326. meerk40t/kernel/jobs.py +100 -100
  327. meerk40t/kernel/kernel.py +3809 -3571
  328. meerk40t/kernel/lifecycles.py +71 -71
  329. meerk40t/kernel/module.py +49 -49
  330. meerk40t/kernel/service.py +147 -147
  331. meerk40t/kernel/settings.py +383 -343
  332. meerk40t/lihuiyu/controller.py +883 -876
  333. meerk40t/lihuiyu/device.py +1181 -1069
  334. meerk40t/lihuiyu/driver.py +1466 -1372
  335. meerk40t/lihuiyu/gui/gui.py +127 -106
  336. meerk40t/lihuiyu/gui/lhyaccelgui.py +377 -363
  337. meerk40t/lihuiyu/gui/lhycontrollergui.py +741 -651
  338. meerk40t/lihuiyu/gui/lhydrivergui.py +470 -446
  339. meerk40t/lihuiyu/gui/lhyoperationproperties.py +238 -237
  340. meerk40t/lihuiyu/gui/tcpcontroller.py +226 -190
  341. meerk40t/lihuiyu/interpreter.py +53 -53
  342. meerk40t/lihuiyu/laserspeed.py +450 -450
  343. meerk40t/lihuiyu/loader.py +90 -90
  344. meerk40t/lihuiyu/parser.py +404 -404
  345. meerk40t/lihuiyu/plugin.py +101 -102
  346. meerk40t/lihuiyu/tcp_connection.py +111 -109
  347. meerk40t/main.py +231 -165
  348. meerk40t/moshi/builder.py +788 -781
  349. meerk40t/moshi/controller.py +505 -499
  350. meerk40t/moshi/device.py +495 -442
  351. meerk40t/moshi/driver.py +862 -696
  352. meerk40t/moshi/gui/gui.py +78 -76
  353. meerk40t/moshi/gui/moshicontrollergui.py +538 -522
  354. meerk40t/moshi/gui/moshidrivergui.py +87 -75
  355. meerk40t/moshi/plugin.py +43 -43
  356. meerk40t/network/console_server.py +102 -57
  357. meerk40t/network/kernelserver.py +10 -9
  358. meerk40t/network/tcp_server.py +142 -140
  359. meerk40t/network/udp_server.py +103 -77
  360. meerk40t/network/web_server.py +390 -0
  361. meerk40t/newly/controller.py +1158 -1144
  362. meerk40t/newly/device.py +874 -732
  363. meerk40t/newly/driver.py +540 -412
  364. meerk40t/newly/gui/gui.py +219 -188
  365. meerk40t/newly/gui/newlyconfig.py +116 -101
  366. meerk40t/newly/gui/newlycontroller.py +193 -186
  367. meerk40t/newly/gui/operationproperties.py +51 -51
  368. meerk40t/newly/mock_connection.py +82 -82
  369. meerk40t/newly/newly_params.py +56 -56
  370. meerk40t/newly/plugin.py +1214 -1246
  371. meerk40t/newly/usb_connection.py +322 -322
  372. meerk40t/rotary/gui/gui.py +52 -46
  373. meerk40t/rotary/gui/rotarysettings.py +240 -232
  374. meerk40t/rotary/rotary.py +202 -98
  375. meerk40t/ruida/control.py +291 -91
  376. meerk40t/ruida/controller.py +138 -1088
  377. meerk40t/ruida/device.py +672 -231
  378. meerk40t/ruida/driver.py +534 -472
  379. meerk40t/ruida/emulator.py +1494 -1491
  380. meerk40t/ruida/exceptions.py +4 -4
  381. meerk40t/ruida/gui/gui.py +71 -76
  382. meerk40t/ruida/gui/ruidaconfig.py +239 -72
  383. meerk40t/ruida/gui/ruidacontroller.py +187 -184
  384. meerk40t/ruida/gui/ruidaoperationproperties.py +48 -47
  385. meerk40t/ruida/loader.py +54 -52
  386. meerk40t/ruida/mock_connection.py +57 -109
  387. meerk40t/ruida/plugin.py +124 -87
  388. meerk40t/ruida/rdjob.py +2084 -945
  389. meerk40t/ruida/serial_connection.py +116 -0
  390. meerk40t/ruida/tcp_connection.py +146 -0
  391. meerk40t/ruida/udp_connection.py +73 -0
  392. meerk40t/svgelements.py +9671 -9669
  393. meerk40t/tools/driver_to_path.py +584 -579
  394. meerk40t/tools/geomstr.py +5583 -4680
  395. meerk40t/tools/jhfparser.py +357 -292
  396. meerk40t/tools/kerftest.py +904 -890
  397. meerk40t/tools/livinghinges.py +1168 -1033
  398. meerk40t/tools/pathtools.py +987 -949
  399. meerk40t/tools/pmatrix.py +234 -0
  400. meerk40t/tools/pointfinder.py +942 -942
  401. meerk40t/tools/polybool.py +940 -940
  402. meerk40t/tools/rasterplotter.py +1660 -547
  403. meerk40t/tools/shxparser.py +989 -901
  404. meerk40t/tools/ttfparser.py +726 -446
  405. meerk40t/tools/zinglplotter.py +595 -593
  406. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/LICENSE +21 -21
  407. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/METADATA +150 -139
  408. meerk40t-0.9.7010.dist-info/RECORD +445 -0
  409. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/WHEEL +1 -1
  410. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/top_level.txt +0 -1
  411. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/zip-safe +1 -1
  412. meerk40t/balormk/elementlightjob.py +0 -159
  413. meerk40t-0.9.3001.dist-info/RECORD +0 -437
  414. test/bootstrap.py +0 -63
  415. test/test_cli.py +0 -12
  416. test/test_core_cutcode.py +0 -418
  417. test/test_core_elements.py +0 -144
  418. test/test_core_plotplanner.py +0 -397
  419. test/test_core_viewports.py +0 -312
  420. test/test_drivers_grbl.py +0 -108
  421. test/test_drivers_lihuiyu.py +0 -443
  422. test/test_drivers_newly.py +0 -113
  423. test/test_element_degenerate_points.py +0 -43
  424. test/test_elements_classify.py +0 -97
  425. test/test_elements_penbox.py +0 -22
  426. test/test_file_svg.py +0 -176
  427. test/test_fill.py +0 -155
  428. test/test_geomstr.py +0 -1523
  429. test/test_geomstr_nodes.py +0 -18
  430. test/test_imagetools_actualize.py +0 -306
  431. test/test_imagetools_wizard.py +0 -258
  432. test/test_kernel.py +0 -200
  433. test/test_laser_speeds.py +0 -3303
  434. test/test_length.py +0 -57
  435. test/test_lifecycle.py +0 -66
  436. test/test_operations.py +0 -251
  437. test/test_operations_hatch.py +0 -57
  438. test/test_ruida.py +0 -19
  439. test/test_spooler.py +0 -22
  440. test/test_tools_rasterplotter.py +0 -29
  441. test/test_wobble.py +0 -133
  442. test/test_zingl.py +0 -124
  443. {test → meerk40t/cylinder}/__init__.py +0 -0
  444. /meerk40t/{core/element_commands.py → cylinder/gui/__init__.py} +0 -0
  445. {meerk40t-0.9.3001.dist-info → meerk40t-0.9.7010.dist-info}/entry_points.txt +0 -0
@@ -1,876 +1,883 @@
1
- """
2
- Lihuiyu Controller
3
-
4
- Deals with the sending of data via the registered connection, and processes some limited realtime commands.
5
-
6
- - : require wait finish at the end of the queue processing.
7
- * : clear the buffers, and abort the thread.
8
- ! : pause.
9
- & : resume.
10
- % : fail checksum, do not resend
11
- ~ : begin/end realtime exception (Note, these characters would be consumed during
12
- the write process and should not exist in the queue)
13
- \x18 : quit.
14
-
15
- """
16
-
17
- import threading
18
- import time
19
-
20
- from meerk40t.ch341 import get_ch341_interface
21
-
22
- STATUS_SERIAL_CORRECT_M3_FINISH = 204
23
- # 0xCC, 11001100
24
- STATUS_OK = 206
25
- # 0xCE, 11001110
26
- STATUS_ERROR = 207
27
- # 0xCF, 11001111
28
- STATUS_FINISH = 236
29
- # 0xEC, 11101100
30
- STATUS_BUSY = 238
31
- # 0xEE, 11101110
32
- STATUS_POWER = 239
33
-
34
-
35
- STATE_X_FORWARD_LEFT = (
36
- 0b0000000000000001 # Direction is flagged left rather than right.
37
- )
38
- STATE_Y_FORWARD_TOP = 0b0000000000000010 # Direction is flagged top rather than bottom.
39
- STATE_X_STEPPER_ENABLE = 0b0000000000000100 # X-stepper motor is engaged.
40
- STATE_Y_STEPPER_ENABLE = 0b0000000000001000 # Y-stepper motor is engaged.
41
- STATE_HORIZONTAL_MAJOR = 0b0000000000010000
42
- REQUEST_X = 0b0000000000100000
43
- REQUEST_X_FORWARD_LEFT = 0b0000000001000000 # Requested direction towards the left.
44
- REQUEST_Y = 0b0000000010000000
45
- REQUEST_Y_FORWARD_TOP = 0b0000000100000000 # Requested direction towards the top.
46
- REQUEST_AXIS = 0b0000001000000000
47
- REQUEST_HORIZONTAL_MAJOR = 0b0000010000000000 # Requested horizontal major axis.
48
-
49
-
50
- def get_code_string_from_code(code):
51
- if code == STATUS_OK:
52
- return "OK"
53
- elif code == STATUS_BUSY:
54
- return "Busy"
55
- elif code == STATUS_ERROR:
56
- return "Rejected"
57
- elif code == STATUS_FINISH:
58
- return "Finish"
59
- elif code == STATUS_POWER:
60
- return "Low Power"
61
- elif code == STATUS_SERIAL_CORRECT_M3_FINISH:
62
- return "M3-Finished"
63
- elif code == 0:
64
- return "USB Failed"
65
- else:
66
- return f"UNK {code:02x}"
67
-
68
-
69
- def convert_to_list_bytes(data):
70
- if isinstance(data, str): # python 2
71
- packet = [0] * 30
72
- for i in range(0, 30):
73
- packet[i] = ord(data[i])
74
- return packet
75
- else:
76
- packet = [0] * 30
77
- for i in range(0, 30):
78
- packet[i] = data[i]
79
- return packet
80
-
81
-
82
- crc_table = [
83
- 0x00,
84
- 0x5E,
85
- 0xBC,
86
- 0xE2,
87
- 0x61,
88
- 0x3F,
89
- 0xDD,
90
- 0x83,
91
- 0xC2,
92
- 0x9C,
93
- 0x7E,
94
- 0x20,
95
- 0xA3,
96
- 0xFD,
97
- 0x1F,
98
- 0x41,
99
- 0x00,
100
- 0x9D,
101
- 0x23,
102
- 0xBE,
103
- 0x46,
104
- 0xDB,
105
- 0x65,
106
- 0xF8,
107
- 0x8C,
108
- 0x11,
109
- 0xAF,
110
- 0x32,
111
- 0xCA,
112
- 0x57,
113
- 0xE9,
114
- 0x74,
115
- ]
116
-
117
-
118
- def onewire_crc_lookup(line):
119
- """
120
- License: 2-clause "simplified" BSD license
121
- Copyright (C) 1992-2017 Arjen Lentz
122
- https://lentz.com.au/blog/calculating-crc-with-a-tiny-32-entry-lookup-table
123
-
124
- @param line: line to be CRC'd
125
- @return: 8 bit crc of line.
126
- """
127
- crc = 0
128
- for i in range(0, 30):
129
- crc = line[i] ^ crc
130
- crc = crc_table[crc & 0x0F] ^ crc_table[16 + ((crc >> 4) & 0x0F)]
131
- return crc
132
-
133
-
134
- class LihuiyuController:
135
- """
136
- K40 Controller controls the Lihuiyu boards sending any queued data to the USB when the signal is not busy.
137
-
138
- Opening and closing of the pipe are dealt with internally. There are three primary monitor data channels.
139
- 'send', 'recv' and 'usb'. They display the reading and writing of information to/from the USB and the USB connection
140
- log, providing information about the connecting and error status of the USB device.
141
- """
142
-
143
- def __init__(self, context, *args, **kwargs):
144
- self.context = context
145
- self.state = "unknown"
146
- self.is_shutdown = False
147
- self.serial_confirmed = None
148
-
149
- self._thread = None
150
- self._buffer = (
151
- bytearray()
152
- ) # Threadsafe buffered commands to be sent to controller.
153
- self._realtime_buffer = (
154
- bytearray() # Threadsafe realtime buffered commands to be sent to the controller.
155
- )
156
- self._queue = bytearray() # Thread-unsafe additional commands to append.
157
- self._preempt = (
158
- bytearray()
159
- ) # Thread-unsafe preempt commands to prepend to the buffer.
160
- self._queue_lock = threading.Lock()
161
- self._preempt_lock = threading.Lock()
162
- self._main_lock = threading.Lock()
163
- self._connect_lock = threading.RLock()
164
- self._loop_cond = threading.Condition()
165
-
166
- self._status = [0] * 6
167
- self._usb_state = -1
168
-
169
- self.connection = None
170
- self.max_attempts = 5
171
- self.refuse_counts = 0
172
- self.connection_errors = 0
173
- self.aborted_retries = False
174
- self.pre_ok = False
175
- self.realtime = False
176
-
177
- self.abort_waiting = False
178
-
179
- name = self.context.label
180
- self.pipe_channel = context.channel(f"{name}/events")
181
- self.usb_log = context.channel(f"{name}/usb", buffer_size=500)
182
- self.usb_send_channel = context.channel(f"{name}/usb_send")
183
- self.recv_channel = context.channel(f"{name}/recv")
184
- self.usb_log.watch(lambda e: context.signal("pipe;usb_status", e))
185
- self.reset()
186
-
187
- @property
188
- def viewbuffer(self):
189
- buffer = bytes(self._realtime_buffer) + bytes(self._buffer) + bytes(self._queue)
190
- try:
191
- buffer_str = buffer.decode()
192
- except ValueError:
193
- try:
194
- buffer_str = buffer.decode("utf8")
195
- except UnicodeDecodeError:
196
- buffer_str = str(buffer)
197
- except AttributeError:
198
- buffer_str = buffer
199
- return buffer_str
200
-
201
- def added(self):
202
- self.start()
203
-
204
- def service_detach(self):
205
- pass
206
-
207
- def shutdown(self, *args, **kwargs):
208
- if self._thread is not None:
209
- self.realtime_write(b"\x18\n")
210
-
211
- def __repr__(self):
212
- return f"LihuiyuController({str(self.context)})"
213
-
214
- def __len__(self):
215
- """Provides the length of the buffer of this device."""
216
- return len(self._buffer) + len(self._queue) + len(self._preempt)
217
-
218
- def open(self):
219
- with self._connect_lock:
220
- self._process_open()
221
-
222
- def _process_open(self):
223
- if self.connection is not None and self.connection.is_connected():
224
- return # Already connected.
225
- _ = self.usb_log._
226
- self.pipe_channel("open()")
227
- try:
228
- interfaces = list(
229
- get_ch341_interface(
230
- self.context,
231
- self.usb_log,
232
- mock=self.context.mock,
233
- mock_status=STATUS_OK,
234
- bulk=True,
235
- )
236
- )
237
- if self.context.usb_index != -1:
238
- # Instructed to check one specific device.
239
- devices = [self.context.usb_index]
240
- else:
241
- devices = range(16)
242
-
243
- for interface in interfaces:
244
- self.connection = interface
245
- for i in devices:
246
- try:
247
- self._open_at_index(i)
248
- return # Opened successfully.
249
- except ConnectionRefusedError as e:
250
- self.usb_log(str(e))
251
- if self.connection is not None:
252
- self.connection.close()
253
- except IndexError:
254
- self.usb_log(_("Connection failed."))
255
- self.connection = None
256
- break
257
- except PermissionError as e:
258
- self.usb_log(str(e))
259
- return # OS denied permissions, no point checking anything else.
260
-
261
- self.close()
262
- raise ConnectionRefusedError(
263
- _("No valid connection matched any given criteria.")
264
- )
265
-
266
- def _open_at_index(self, usb_index):
267
- _ = self.context.kernel.translation
268
- self.connection.open(usb_index=usb_index)
269
- if not self.connection.is_connected():
270
- raise ConnectionRefusedError("ch341 connect did not return a connection.")
271
- if self.context.usb_bus != -1 and self.connection.bus != -1:
272
- if self.connection.bus != self.context.usb_bus:
273
- raise ConnectionRefusedError(
274
- _("K40 devices were found but they were rejected due to usb bus.")
275
- )
276
- if self.context.usb_address != -1 and self.connection.address != -1:
277
- if self.connection.address != self.context.usb_address:
278
- raise ConnectionRefusedError(
279
- _(
280
- "K40 devices were found but they were rejected due to usb address."
281
- )
282
- )
283
- if self.context.usb_version != -1:
284
- version = self.connection.get_chip_version()
285
- if version != self.context.usb_version:
286
- raise ConnectionRefusedError(
287
- _(
288
- "K40 devices were found but they were rejected due to chip version."
289
- )
290
- )
291
- if self.context.serial_enable and self.context.serial is not None:
292
- if self.serial_confirmed:
293
- return # already passed.
294
- self.usb_log(_("Requires serial number confirmation."))
295
- self.challenge(self.context.serial)
296
- t = time.time()
297
- while time.time() - t < 0.5:
298
- if self.serial_confirmed:
299
- break
300
- if not self.serial_confirmed:
301
- raise ConnectionRefusedError("Serial number confirmation failed.")
302
- else:
303
- self.usb_log(_("Serial number confirmed."))
304
-
305
- def close(self):
306
- self.pipe_channel("close()")
307
- with self._connect_lock:
308
- if self.connection is None:
309
- return
310
- self.connection.close()
311
- self.connection = None
312
-
313
- def write(self, bytes_to_write):
314
- """
315
- Writes data to the queue, this will be moved into the buffer by the thread in a threadsafe manner.
316
-
317
- @param bytes_to_write: data to write to the queue.
318
- @return:
319
- """
320
- f = bytes_to_write.find(b"~")
321
- if f != -1:
322
- # ~ was found in bytes. We are in a realtime exception.
323
- self.realtime = True
324
-
325
- # All code prior to ~ is sent to write.
326
- queue_bytes = bytes_to_write[:f]
327
- if queue_bytes:
328
- self.write(queue_bytes)
329
-
330
- # All code after ~ is sent to realtime write.
331
- preempt_bytes = bytes_to_write[f + 1 :]
332
- if preempt_bytes:
333
- self.realtime_write(preempt_bytes)
334
- return self
335
- if self.realtime:
336
- # We are in a realtime exception that has not been terminated.
337
- self.realtime_write(bytes_to_write)
338
- return self
339
-
340
- self.pipe_channel(f"write({str(bytes_to_write)})")
341
- with self._queue_lock:
342
- self._queue += bytes_to_write
343
- self.start()
344
- self.update_buffer()
345
- return self
346
-
347
- def realtime_write(self, bytes_to_write):
348
- """
349
- Writes data to the preempting commands, this will be moved to the front of the buffer by the thread
350
- in a threadsafe manner.
351
-
352
- @param bytes_to_write: data to write to the front of the queue.
353
- @return:
354
- """
355
- f = bytes_to_write.find(b"~")
356
- if f != -1:
357
- # ~ was found in bytes. We are leaving realtime exception.
358
- self.realtime = False
359
-
360
- # All date prior to the ~ is sent to realtime write.
361
- preempt_bytes = bytes_to_write[:f]
362
- if preempt_bytes:
363
- self.realtime_write(preempt_bytes)
364
-
365
- # All data after ~ is sent back to normal write.
366
- queue_bytes = bytes_to_write[f + 1 :]
367
- if queue_bytes:
368
- self.write(queue_bytes)
369
- return self
370
- self.pipe_channel(f"realtime_write({str(bytes_to_write)})")
371
- if b"*" in bytes_to_write:
372
- self.abort_waiting = True
373
- with self._preempt_lock:
374
- self._preempt = bytearray(bytes_to_write) + self._preempt
375
- self.start()
376
- self.update_buffer()
377
- return self
378
-
379
- def start(self):
380
- """
381
- Controller state change to `Started`.
382
- @return:
383
- """
384
- with self._loop_cond:
385
- self._loop_cond.notify()
386
- if not self.is_shutdown and (
387
- self._thread is None or not self._thread.is_alive()
388
- ):
389
- self.update_state("init")
390
- self._thread = self.context.threaded(
391
- self._thread_data_send,
392
- thread_name=f"LhyPipe({self.context.path})",
393
- result=self.stop,
394
- )
395
- self._thread.stop = self.stop
396
-
397
- def _pause_busy(self):
398
- """
399
- BUSY can be called in a paused state to packet halt the controller.
400
-
401
- This can only be done from PAUSE.
402
- """
403
- if self.state != "pause":
404
- self.pause()
405
- if self.state == "pause":
406
- self.update_state("busy")
407
-
408
- def _resume_busy(self):
409
- """
410
- Resumes from a BUSY to restore the controller. This will return to a paused state.
411
-
412
- This can only be done from BUSY.
413
- """
414
- if self.state == "busy":
415
- self.update_state("pause")
416
- self.resume()
417
-
418
- def pause(self):
419
- """
420
- Pause simply holds the controller from sending any additional packets.
421
-
422
- If this state change is done from INITIALIZE it will start the processing.
423
- Otherwise, it must be done from ACTIVE or IDLE.
424
- """
425
- if self.state == "init":
426
- self.start()
427
- self.update_state("pause")
428
- if self.state in ("active", "idle"):
429
- self.update_state("pause")
430
-
431
- def resume(self):
432
- """
433
- Resume can only be called from PAUSE.
434
- """
435
- if self.state == "pause":
436
- self.update_state("active")
437
-
438
- def abort(self):
439
- self._buffer = bytearray()
440
- self._queue = bytearray()
441
- self._realtime_buffer = bytearray()
442
- self.abort_waiting = False
443
- self.context.signal("pipe;buffer", 0)
444
- self.update_state("terminate")
445
-
446
- def reset(self):
447
- self.update_state("init")
448
-
449
- def stop(self, *args):
450
- self.abort()
451
- try:
452
- if self._thread is not None:
453
- self._thread.join() # Wait until stop completes before continuing.
454
- self._thread = None
455
- except RuntimeError:
456
- pass # Stop called by current thread.
457
-
458
- def abort_retry(self):
459
- with self._loop_cond:
460
- self._loop_cond.notify()
461
- self.aborted_retries = True
462
- self.context.signal("pipe;state", "STATE_FAILED_SUSPENDED")
463
-
464
- def continue_retry(self):
465
- with self._loop_cond:
466
- self._loop_cond.notify()
467
- self.aborted_retries = False
468
- self.context.signal("pipe;state", "STATE_FAILED_RETRYING")
469
-
470
- def usb_release(self):
471
- if self.connection:
472
- self.connection.release()
473
- else:
474
- raise ConnectionError
475
-
476
- def usb_reset(self):
477
- if self.connection:
478
- self.connection.reset()
479
- else:
480
- raise ConnectionError
481
-
482
- def challenge(self, serial):
483
- if serial is None:
484
- return
485
-
486
- from hashlib import md5
487
-
488
- challenge = bytearray.fromhex(md5(bytes(serial.upper(), "utf8")).hexdigest())
489
- packet = b"A%s" % challenge
490
- packet += b"F" * (30 - len(packet))
491
- packet = b"\x00" + packet + bytes([onewire_crc_lookup(packet)])
492
- self.connection.write(packet)
493
- try:
494
- self._confirm_serial()
495
- except ConnectionError:
496
- # If we could not access the status, then we did not confirm the serial number.
497
- pass
498
-
499
- def update_state(self, state):
500
- with self._loop_cond:
501
- self._loop_cond.notify()
502
- if state == self.state:
503
- return
504
- self.state = state
505
- if self.context is not None:
506
- self.context.signal("pipe;thread", self.state)
507
-
508
- def update_buffer(self):
509
- self.context.signal("pipe;buffer", len(self))
510
-
511
- def update_packet(self, packet):
512
- self.context.signal("pipe;packet", convert_to_list_bytes(packet))
513
- self.context.signal("pipe;packet_text", packet)
514
- if self.usb_send_channel:
515
- self.usb_send_channel(packet)
516
-
517
- def _thread_loop(self):
518
- while self.state not in ("end", "terminate"):
519
- if self.state == "init":
520
- # If we are initialized. Change that to active since we're running.
521
- self.update_state("active")
522
- elif self.state in ("pause", "busy", "suspend"):
523
- # If we are paused just wait until the state changes.
524
- if len(self._realtime_buffer) == 0 and len(self._preempt) == 0:
525
- # Only pause if there are no realtime commands to queue.
526
- self.context.laser_status = "idle"
527
- with self._loop_cond:
528
- self._loop_cond.wait()
529
- continue
530
- if self.aborted_retries:
531
- # We are not trying reconnection anymore.
532
- self.context.laser_status = "idle"
533
- with self._loop_cond:
534
- self._loop_cond.wait()
535
- continue
536
-
537
- self._check_transfer_buffer()
538
- if len(self._realtime_buffer) <= 0 and len(self._buffer) <= 0:
539
- # The buffer and realtime buffers are empty. No packet creation possible.
540
- self.context.laser_status = "idle"
541
- with self._loop_cond:
542
- self._loop_cond.wait()
543
- continue
544
-
545
- try:
546
- # We try to process the queue.
547
- queue_processed = self.process_queue()
548
- if self.refuse_counts:
549
- self.context.signal("pipe;failing", 0)
550
- self.refuse_counts = 0
551
- if self.is_shutdown:
552
- return # Sometimes it could reset this and escape.
553
- except ConnectionRefusedError:
554
- # The attempt refused the connection.
555
- self.refuse_counts += 1
556
- self.pre_ok = False
557
- if self.refuse_counts >= 5:
558
- self.context.signal("pipe;state", "STATE_FAILED_RETRYING")
559
- self.context.signal("pipe;failing", self.refuse_counts)
560
- self.context.laser_status = "idle"
561
- if self.is_shutdown:
562
- return # Sometimes it could reset this and escape.
563
- time.sleep(3) # 3-second sleep on failed connection attempt.
564
- continue
565
- except ConnectionError:
566
- # There was an error with the connection, close it and try again.
567
- self.connection_errors += 1
568
- self.pre_ok = False
569
-
570
- self.context.laser_status = "idle"
571
- time.sleep(0.5)
572
- self.close()
573
- continue
574
-
575
- self.context.laser_status = "active" if queue_processed else "idle"
576
- if queue_processed:
577
- # Packet was sent.
578
- if self.state not in (
579
- "pause",
580
- "busy",
581
- "active",
582
- "terminate",
583
- ):
584
- self.update_state("active")
585
- continue
586
- # No packet could be sent.
587
- if self.state not in (
588
- "pause",
589
- "busy",
590
- "terminate",
591
- ):
592
- self.update_state("idle")
593
-
594
- def _thread_data_send(self):
595
- """
596
- Main threaded function to send data. While the controller is working the thread
597
- will be doing work in this function.
598
- """
599
- with self._main_lock:
600
- self.pre_ok = False
601
- self.is_shutdown = False
602
- self._thread_loop()
603
- self._thread = None
604
- self.update_state("end")
605
- self.pre_ok = False
606
- self.context.laser_status = "idle"
607
-
608
- def _check_transfer_buffer(self):
609
- if len(self._queue): # check for and append queue
610
- with self._queue_lock:
611
- self._buffer += self._queue
612
- self._queue.clear()
613
- self.update_buffer()
614
-
615
- if len(self._preempt): # check for and prepend preempt
616
- with self._preempt_lock:
617
- self._realtime_buffer += self._preempt
618
- self._preempt.clear()
619
- self.update_buffer()
620
-
621
- def process_queue(self):
622
- """
623
- Attempts to process the buffer/queue
624
- Will fail on ConnectionRefusedError at open, 'process_queue_pause = True' (anytime before packet sent),
625
- self._buffer is empty, or a failure to produce packet.
626
-
627
- Buffer will not be changed unless packet is successfully sent, or pipe commands are processed.
628
-
629
- The following are meta commands for the controller
630
- - : require wait finish at the end of the queue processing.
631
- * : clear the buffers, and abort the thread.
632
- ! : pause.
633
- & : resume.
634
- % : fail checksum, do not resend
635
- ~ : begin/end realtime exception (Note, these characters would be consumed during
636
- the write process and should not exist in the queue)
637
- \x18 : quit.
638
-
639
- @return: queue process success.
640
- """
641
- if len(self._realtime_buffer) > 0:
642
- buffer = self._realtime_buffer
643
- realtime = True
644
- elif len(self._buffer) > 0:
645
- buffer = self._buffer
646
- realtime = False
647
- else:
648
- return False
649
-
650
- # Find buffer of 30 or containing '\n'.
651
- find = buffer.find(b"\n", 0, 30)
652
- if find == -1: # No end found.
653
- length = min(30, len(buffer))
654
- else: # Line end found.
655
- length = min(30, len(buffer), find + 1)
656
- packet = bytes(buffer[:length])
657
-
658
- # edge condition of catching only pipe command without '\n'
659
- if packet.endswith((b"-", b"*", b"&", b"!", b"#", b"%", b"\x18")):
660
- packet += buffer[length : length + 1]
661
- length += 1
662
- post_send_command = None
663
- default_checksum = True
664
-
665
- # find pipe commands.
666
- if packet.endswith(b"\n"):
667
- packet = packet[:-1]
668
- if packet.endswith(b"-"): # wait finish
669
- packet = packet[:-1]
670
- post_send_command = self.wait_finished
671
- elif packet.endswith(b"*"): # abort
672
- post_send_command = self.abort
673
- packet = packet[:-1]
674
- elif packet.endswith(b"&"): # resume
675
- self._resume_busy()
676
- packet = packet[:-1]
677
- elif packet.endswith(b"!"): # pause
678
- self._pause_busy()
679
- packet = packet[:-1]
680
- elif packet.endswith(b"%"): # alt-checksum
681
- default_checksum = False
682
- packet = packet[:-1]
683
- elif packet.endswith(b"\x18"):
684
- self.update_state("terminate")
685
- self.is_shutdown = True
686
- packet = packet[:-1]
687
- if packet.startswith(b"A"):
688
- # This is a challenge code. A is only used for serial challenges.
689
- post_send_command = self._confirm_serial
690
- if len(packet) != 0:
691
- if packet.endswith(b"#"):
692
- packet = packet[:-1]
693
- try:
694
- c = packet[-1]
695
- except IndexError:
696
- c = b"F" # Packet was simply #. We can do nothing.
697
- packet += bytes([c]) * (30 - len(packet)) # Padding. '\n'
698
- else:
699
- packet += b"F" * (30 - len(packet)) # Padding. '\n'
700
- if not realtime and self.state in ("pause", "busy"):
701
- return False # Processing normal queue, PAUSE and BUSY apply.
702
-
703
- # Packet is prepared and ready to send. Open Channel.
704
- self.open()
705
-
706
- if len(packet) == 30:
707
- # We have a sendable packet.
708
- if not self.pre_ok:
709
- self.wait_until_accepting_packets()
710
- if default_checksum:
711
- packet = b"\x00" + packet + bytes([onewire_crc_lookup(packet)])
712
- else:
713
- packet = b"\x00" + packet + bytes([onewire_crc_lookup(packet) ^ 0xFF])
714
- self.connection.write(packet)
715
- self.pre_ok = False
716
-
717
- # Packet is sent, trying to confirm.
718
- status = 0
719
- flawless = True
720
- for attempts in range(500):
721
- # We'll try to confirm this at 500 times.
722
- try:
723
- self.update_status()
724
- status = self._status[1]
725
- if attempts > 10:
726
- time.sleep(min(0.001 * attempts, 0.1))
727
- except ConnectionError:
728
- # Errors are ignored, must confirm packet.
729
- flawless = False
730
- continue
731
- if status == 0:
732
- # We did not read a status.
733
- continue
734
- elif status == STATUS_OK:
735
- # Packet was fine.
736
- self.pre_ok = True
737
- break
738
- elif status == STATUS_BUSY:
739
- # Busy. We still do not have our confirmation. BUSY comes before ERROR or OK.
740
- continue
741
- elif status == STATUS_ERROR:
742
- if not default_checksum:
743
- break
744
- self.context.rejected_count += 1
745
- if flawless: # Packet was rejected. The CRC failed.
746
- return False
747
- else:
748
- # The channel had the error, assuming packet was actually good.
749
- break
750
- elif status == STATUS_FINISH:
751
- # We finished. If we were going to wait for that, we no longer need to.
752
- if post_send_command == self.wait_finished:
753
- post_send_command = None
754
- continue # This is not a confirmation.
755
- elif status == STATUS_SERIAL_CORRECT_M3_FINISH:
756
- if post_send_command == self._confirm_serial:
757
- # We confirmed the serial number on the card.
758
- self.serial_confirmed = True
759
- post_send_command = None
760
- break
761
- elif post_send_command == self.wait_finished:
762
- # This is a STATUS_M3_FINISHED, we no longer wait.
763
- post_send_command = None
764
- continue
765
-
766
- if status == 0: # After 500 attempts we could only get status = 0.
767
- raise ConnectionError # Broken pipe. Could not confirm packet.
768
- self.context.packet_count += (
769
- 1 # Our packet is confirmed or assumed confirmed.
770
- )
771
- else:
772
- if len(packet) != 0:
773
- # We could only generate a partial packet, throw it back
774
- return False
775
- # We have an empty packet of only commands. Continue work.
776
-
777
- # Packet was processed. Remove that data.
778
- if realtime:
779
- del self._realtime_buffer[:length]
780
- else:
781
- del self._buffer[:length]
782
- if len(packet) != 0:
783
- # Packet was completed and sent. Only then update the channel.
784
- self.update_packet(packet)
785
- self.update_buffer()
786
-
787
- if post_send_command is not None:
788
- # Post send command could be wait_finished, and might have a broken pipe.
789
- try:
790
- post_send_command()
791
- except ConnectionError:
792
- # We should have already sent the packet. So this should be fine.
793
- pass
794
- return True # A packet was prepped and sent correctly.
795
-
796
- def update_status(self):
797
- try:
798
- self._status = self.connection.get_status()
799
- except AttributeError:
800
- # self.connection was closed by something.
801
- raise ConnectionError
802
- if self.context is not None:
803
- try:
804
- self.context.signal(
805
- "pipe;status",
806
- self._status,
807
- get_code_string_from_code(self._status[1]),
808
- )
809
- except IndexError:
810
- pass
811
- if self.recv_channel:
812
- self.recv_channel(str(self._status))
813
-
814
- def wait_until_accepting_packets(self):
815
- i = 0
816
- while self.state != "terminate":
817
- self.update_status()
818
- if self._status is None:
819
- raise ConnectionError
820
- status = self._status[1]
821
- if status == 0:
822
- raise ConnectionError
823
- if status == STATUS_OK:
824
- self.pre_ok = False
825
- break
826
- if status == STATUS_ERROR:
827
- break
828
- time.sleep(0.05)
829
- if self.context is not None:
830
- self.context.signal("pipe;wait", STATUS_OK, i)
831
- i += 1
832
- if self.abort_waiting:
833
- self.abort_waiting = False
834
- return # Wait abort was requested.
835
-
836
- def wait_finished(self):
837
- i = 0
838
- original_state = self.state
839
- if self.state != "pause":
840
- self.pause()
841
-
842
- while True:
843
- if self.state != "wait":
844
- if self.state == "terminate":
845
- return # Abort all the processes was requested. This state change would be after clearing.
846
- self.update_state("wait")
847
- self.update_status()
848
- status = self._status[1]
849
- if status == 0:
850
- raise ConnectionError
851
- if status == STATUS_ERROR:
852
- self.context.rejected_count += 1
853
- if status & 0x02 == 0:
854
- # StateBitPEMP = 0x00000200, Finished = 0xEC, 11101100
855
- break
856
- if self.context is not None:
857
- self.context.signal("pipe;wait", status, i)
858
- i += 1
859
- if self.abort_waiting:
860
- self.abort_waiting = False
861
- break # Wait abort was requested.
862
- time.sleep(0.001) # Only if we are using control transfer status checks.
863
- self.update_state(original_state)
864
-
865
- def _confirm_serial(self):
866
- t = time.time()
867
- while time.time() - t < 0.5: # We spend up to half a second to confirm.
868
- if self.state == "terminate":
869
- # We are not confirmed.
870
- return # Abort all the processes was requested. This state change would be after clearing.
871
- self.update_status()
872
- status = self._status[1]
873
- if status == STATUS_SERIAL_CORRECT_M3_FINISH:
874
- self.serial_confirmed = True
875
- return # We're done.
876
- self.serial_confirmed = False
1
+ """
2
+ Lihuiyu Controller
3
+
4
+ Deals with the sending of data via the registered connection, and processes some limited realtime commands.
5
+
6
+ - : require wait finish at the end of the queue processing.
7
+ * : clear the buffers, and abort the thread.
8
+ ! : pause.
9
+ & : resume.
10
+ % : fail checksum, do not resend
11
+ ~ : begin/end realtime exception (Note, these characters would be consumed during
12
+ the write process and should not exist in the queue)
13
+ \x18 : quit.
14
+
15
+ """
16
+
17
+ import threading
18
+ import time
19
+
20
+ from meerk40t.ch341 import get_ch341_interface
21
+
22
+ STATUS_SERIAL_CORRECT_M3_FINISH = 204
23
+ # 0xCC, 11001100
24
+ STATUS_OK = 206
25
+ # 0xCE, 11001110
26
+ STATUS_ERROR = 207
27
+ # 0xCF, 11001111
28
+ STATUS_FINISH = 236
29
+ # 0xEC, 11101100
30
+ STATUS_BUSY = 238
31
+ # 0xEE, 11101110
32
+ STATUS_POWER = 239
33
+
34
+
35
+ STATE_X_FORWARD_LEFT = (
36
+ 0b0000000000000001 # Direction is flagged left rather than right.
37
+ )
38
+ STATE_Y_FORWARD_TOP = 0b0000000000000010 # Direction is flagged top rather than bottom.
39
+ STATE_X_STEPPER_ENABLE = 0b0000000000000100 # X-stepper motor is engaged.
40
+ STATE_Y_STEPPER_ENABLE = 0b0000000000001000 # Y-stepper motor is engaged.
41
+ STATE_HORIZONTAL_MAJOR = 0b0000000000010000
42
+ REQUEST_X = 0b0000000000100000
43
+ REQUEST_X_FORWARD_LEFT = 0b0000000001000000 # Requested direction towards the left.
44
+ REQUEST_Y = 0b0000000010000000
45
+ REQUEST_Y_FORWARD_TOP = 0b0000000100000000 # Requested direction towards the top.
46
+ REQUEST_AXIS = 0b0000001000000000
47
+ REQUEST_HORIZONTAL_MAJOR = 0b0000010000000000 # Requested horizontal major axis.
48
+
49
+
50
+ def get_code_string_from_code(code):
51
+ if code == STATUS_OK:
52
+ return "OK"
53
+ elif code == STATUS_BUSY:
54
+ return "Busy"
55
+ elif code == STATUS_ERROR:
56
+ return "Rejected"
57
+ elif code == STATUS_FINISH:
58
+ return "Finish"
59
+ elif code == STATUS_POWER:
60
+ return "Low Power"
61
+ elif code == STATUS_SERIAL_CORRECT_M3_FINISH:
62
+ return "M3-Finished"
63
+ elif code == 0:
64
+ return "USB Failed"
65
+ else:
66
+ return f"UNK {code:02x}"
67
+
68
+
69
+ def convert_to_list_bytes(data):
70
+ if isinstance(data, str): # python 2
71
+ packet = [0] * 30
72
+ for i in range(0, 30):
73
+ packet[i] = ord(data[i])
74
+ return packet
75
+ else:
76
+ packet = [0] * 30
77
+ for i in range(0, 30):
78
+ packet[i] = data[i]
79
+ return packet
80
+
81
+
82
+ crc_table = [
83
+ 0x00,
84
+ 0x5E,
85
+ 0xBC,
86
+ 0xE2,
87
+ 0x61,
88
+ 0x3F,
89
+ 0xDD,
90
+ 0x83,
91
+ 0xC2,
92
+ 0x9C,
93
+ 0x7E,
94
+ 0x20,
95
+ 0xA3,
96
+ 0xFD,
97
+ 0x1F,
98
+ 0x41,
99
+ 0x00,
100
+ 0x9D,
101
+ 0x23,
102
+ 0xBE,
103
+ 0x46,
104
+ 0xDB,
105
+ 0x65,
106
+ 0xF8,
107
+ 0x8C,
108
+ 0x11,
109
+ 0xAF,
110
+ 0x32,
111
+ 0xCA,
112
+ 0x57,
113
+ 0xE9,
114
+ 0x74,
115
+ ]
116
+
117
+
118
+ def onewire_crc_lookup(line):
119
+ """
120
+ License: 2-clause "simplified" BSD license
121
+ Copyright (C) 1992-2017 Arjen Lentz
122
+ https://lentz.com.au/blog/calculating-crc-with-a-tiny-32-entry-lookup-table
123
+
124
+ @param line: line to be CRC'd
125
+ @return: 8 bit crc of line.
126
+ """
127
+ crc = 0
128
+ for i in range(0, 30):
129
+ crc = line[i] ^ crc
130
+ crc = crc_table[crc & 0x0F] ^ crc_table[16 + ((crc >> 4) & 0x0F)]
131
+ return crc
132
+
133
+
134
+ class LihuiyuController:
135
+ """
136
+ K40 Controller controls the Lihuiyu boards sending any queued data to the USB when the signal is not busy.
137
+
138
+ Opening and closing of the pipe are dealt with internally. There are three primary monitor data channels.
139
+ 'send', 'recv' and 'usb'. They display the reading and writing of information to/from the USB and the USB connection
140
+ log, providing information about the connecting and error status of the USB device.
141
+ """
142
+
143
+ def __init__(self, service, *args, **kwargs):
144
+ self.context = service
145
+ self.state = "unknown"
146
+ self.is_shutdown = False
147
+ self.serial_confirmed = None
148
+
149
+ self._thread = None
150
+ self._buffer = (
151
+ bytearray()
152
+ ) # Threadsafe buffered commands to be sent to controller.
153
+ self._realtime_buffer = (
154
+ bytearray() # Threadsafe realtime buffered commands to be sent to the controller.
155
+ )
156
+ self._queue = bytearray() # Thread-unsafe additional commands to append.
157
+ self._preempt = (
158
+ bytearray()
159
+ ) # Thread-unsafe preempt commands to prepend to the buffer.
160
+ self._queue_lock = threading.Lock()
161
+ self._preempt_lock = threading.Lock()
162
+ self._main_lock = threading.Lock()
163
+ self._connect_lock = threading.RLock()
164
+ self._loop_cond = threading.Condition()
165
+
166
+ self._status = [0] * 6
167
+ self._usb_state = -1
168
+
169
+ self.connection = None
170
+ self.max_attempts = 5
171
+ self.refuse_counts = 0
172
+ self.connection_errors = 0
173
+ self.aborted_retries = False
174
+ self.pre_ok = False
175
+ self.realtime = False
176
+
177
+ self.abort_waiting = False
178
+
179
+ name = service.safe_label
180
+ self.pipe_channel = service.channel(f"{name}/events")
181
+ self.usb_log = service.channel(f"{name}/usb", buffer_size=500)
182
+ self.usb_send_channel = service.channel(f"{name}/usb_send")
183
+ self.recv_channel = service.channel(f"{name}/recv")
184
+ self.usb_log.watch(lambda e: service.signal("pipe;usb_status", e))
185
+ self.reset()
186
+
187
+ @property
188
+ def viewbuffer(self):
189
+ buffer = bytes(self._realtime_buffer) + bytes(self._buffer) + bytes(self._queue)
190
+ try:
191
+ buffer_str = buffer.decode()
192
+ except ValueError:
193
+ try:
194
+ buffer_str = buffer.decode("utf8")
195
+ except UnicodeDecodeError:
196
+ buffer_str = str(buffer)
197
+ except AttributeError:
198
+ buffer_str = buffer
199
+ return buffer_str
200
+
201
+ def added(self):
202
+ self.start()
203
+
204
+ def service_detach(self):
205
+ pass
206
+
207
+ def shutdown(self, *args, **kwargs):
208
+ if self._thread is not None:
209
+ self.realtime_write(b"\x18\n")
210
+
211
+ def __repr__(self):
212
+ return f"LihuiyuController({str(self.context)})"
213
+
214
+ def __len__(self):
215
+ """Provides the length of the buffer of this device."""
216
+ return len(self._buffer) + len(self._queue) + len(self._preempt)
217
+
218
+ def open(self):
219
+ with self._connect_lock:
220
+ self._process_open()
221
+
222
+ def _process_open(self):
223
+ if self.connection is not None and self.connection.is_connected():
224
+ return # Already connected.
225
+ _ = self.usb_log._
226
+ self.pipe_channel("open()")
227
+ try:
228
+ interfaces = list(
229
+ get_ch341_interface(
230
+ self.context,
231
+ self.usb_log,
232
+ mock=self.context.mock,
233
+ mock_status=STATUS_OK,
234
+ bulk=True,
235
+ )
236
+ )
237
+ if self.context.usb_index != -1:
238
+ # Instructed to check one specific device.
239
+ devices = [self.context.usb_index]
240
+ else:
241
+ devices = range(16)
242
+
243
+ for interface in interfaces:
244
+ self.connection = interface
245
+ for i in devices:
246
+ try:
247
+ self._open_at_index(i)
248
+ return # Opened successfully.
249
+ except ConnectionRefusedError as e:
250
+ self.usb_log(str(e))
251
+ if self.connection is not None:
252
+ self.connection.close()
253
+ except IndexError:
254
+ self.usb_log(_("Connection failed."))
255
+ self.connection = None
256
+ break
257
+ except PermissionError as e:
258
+ self.usb_log(str(e))
259
+ return # OS denied permissions, no point checking anything else.
260
+
261
+ self.close()
262
+ raise ConnectionRefusedError(
263
+ _("No valid connection matched any given criteria.")
264
+ )
265
+
266
+ def _open_at_index(self, usb_index):
267
+ _ = self.context.kernel.translation
268
+ self.connection.open(usb_index=usb_index)
269
+ if not self.connection.is_connected():
270
+ raise ConnectionRefusedError("ch341 connect did not return a connection.")
271
+ if self.context.usb_bus != -1 and self.connection.bus != -1:
272
+ if self.connection.bus != self.context.usb_bus:
273
+ raise ConnectionRefusedError(
274
+ _("K40 devices were found but they were rejected due to usb bus.")
275
+ )
276
+ if self.context.usb_address != -1 and self.connection.address != -1:
277
+ if self.connection.address != self.context.usb_address:
278
+ raise ConnectionRefusedError(
279
+ _(
280
+ "K40 devices were found but they were rejected due to usb address."
281
+ )
282
+ )
283
+ if self.context.usb_version != -1:
284
+ version = self.connection.get_chip_version()
285
+ if version != self.context.usb_version:
286
+ raise ConnectionRefusedError(
287
+ _(
288
+ "K40 devices were found but they were rejected due to chip version."
289
+ )
290
+ )
291
+ if self.context.serial_enable and self.context.serial is not None:
292
+ if self.serial_confirmed:
293
+ return # already passed.
294
+ self.usb_log(_("Requires serial number confirmation."))
295
+ self.challenge(self.context.serial)
296
+ t = time.time()
297
+ while time.time() - t < 0.5:
298
+ if self.serial_confirmed:
299
+ break
300
+ if not self.serial_confirmed:
301
+ raise ConnectionRefusedError("Serial number confirmation failed.")
302
+ else:
303
+ self.usb_log(_("Serial number confirmed."))
304
+
305
+ def close(self):
306
+ self.pipe_channel("close()")
307
+ with self._connect_lock:
308
+ if self.connection is None:
309
+ return
310
+ self.connection.close()
311
+ self.connection = None
312
+
313
+ def write(self, bytes_to_write):
314
+ """
315
+ Writes data to the queue, this will be moved into the buffer by the thread in a threadsafe manner.
316
+
317
+ @param bytes_to_write: data to write to the queue.
318
+ @return:
319
+ """
320
+ f = bytes_to_write.find(b"~")
321
+ if f != -1:
322
+ # ~ was found in bytes. We are in a realtime exception.
323
+ self.realtime = True
324
+
325
+ # All code prior to ~ is sent to write.
326
+ queue_bytes = bytes_to_write[:f]
327
+ if queue_bytes:
328
+ self.write(queue_bytes)
329
+
330
+ # All code after ~ is sent to realtime write.
331
+ preempt_bytes = bytes_to_write[f + 1 :]
332
+ if preempt_bytes:
333
+ self.realtime_write(preempt_bytes)
334
+ return self
335
+ if self.realtime:
336
+ # We are in a realtime exception that has not been terminated.
337
+ self.realtime_write(bytes_to_write)
338
+ return self
339
+
340
+ self.pipe_channel(f"write({str(bytes_to_write)})")
341
+ with self._queue_lock:
342
+ self._queue += bytes_to_write
343
+ self.start()
344
+ self.update_buffer()
345
+ return self
346
+
347
+ def realtime_write(self, bytes_to_write):
348
+ """
349
+ Writes data to the preempting commands, this will be moved to the front of the buffer by the thread
350
+ in a threadsafe manner.
351
+
352
+ @param bytes_to_write: data to write to the front of the queue.
353
+ @return:
354
+ """
355
+ f = bytes_to_write.find(b"~")
356
+ if f != -1:
357
+ # ~ was found in bytes. We are leaving realtime exception.
358
+ self.realtime = False
359
+
360
+ # All date prior to the ~ is sent to realtime write.
361
+ preempt_bytes = bytes_to_write[:f]
362
+ if preempt_bytes:
363
+ self.realtime_write(preempt_bytes)
364
+
365
+ # All data after ~ is sent back to normal write.
366
+ queue_bytes = bytes_to_write[f + 1 :]
367
+ if queue_bytes:
368
+ self.write(queue_bytes)
369
+ return self
370
+ self.pipe_channel(f"realtime_write({str(bytes_to_write)})")
371
+ if b"*" in bytes_to_write:
372
+ self.abort_waiting = True
373
+ with self._preempt_lock:
374
+ self._preempt = bytearray(bytes_to_write) + self._preempt
375
+ self.start()
376
+ self.update_buffer()
377
+ return self
378
+
379
+ def start(self):
380
+ """
381
+ Controller state change to `Started`.
382
+ @return:
383
+ """
384
+ with self._loop_cond:
385
+ self._loop_cond.notify()
386
+ if not self.is_shutdown and (
387
+ self._thread is None or not self._thread.is_alive()
388
+ ):
389
+ self.update_state("init")
390
+ self._thread = self.context.threaded(
391
+ self._thread_data_send,
392
+ thread_name=f"LhyPipe({self.context.path})",
393
+ result=self.stop,
394
+ )
395
+ self._thread.stop = self.stop
396
+
397
+ def _pause_busy(self):
398
+ """
399
+ BUSY can be called in a paused state to packet halt the controller.
400
+
401
+ This can only be done from PAUSE.
402
+ """
403
+ if self.state != "pause":
404
+ self.pause()
405
+ if self.state == "pause":
406
+ self.update_state("busy")
407
+
408
+ def _resume_busy(self):
409
+ """
410
+ Resumes from a BUSY to restore the controller. This will return to a paused state.
411
+
412
+ This can only be done from BUSY.
413
+ """
414
+ if self.state == "busy":
415
+ self.update_state("pause")
416
+ self.resume()
417
+
418
+ def pause(self):
419
+ """
420
+ Pause simply holds the controller from sending any additional packets.
421
+
422
+ If this state change is done from INITIALIZE it will start the processing.
423
+ Otherwise, it must be done from ACTIVE or IDLE.
424
+ """
425
+ if self.state == "init":
426
+ self.start()
427
+ self.update_state("pause")
428
+ if self.state in ("active", "idle"):
429
+ self.update_state("pause")
430
+
431
+ def resume(self):
432
+ """
433
+ Resume can only be called from PAUSE.
434
+ """
435
+ if self.state == "pause":
436
+ self.update_state("active")
437
+
438
+ def abort(self):
439
+ self._buffer = bytearray()
440
+ self._queue = bytearray()
441
+ self._realtime_buffer = bytearray()
442
+ self.abort_waiting = False
443
+ self.context.signal("pipe;buffer", 0)
444
+ self.update_state("terminate")
445
+
446
+ def reset(self):
447
+ self.update_state("init")
448
+
449
+ def stop(self, *args):
450
+ self.abort()
451
+ try:
452
+ if self._thread is not None:
453
+ self._thread.join() # Wait until stop completes before continuing.
454
+ self._thread = None
455
+ except RuntimeError:
456
+ pass # Stop called by current thread.
457
+
458
+ def abort_retry(self):
459
+ with self._loop_cond:
460
+ self._loop_cond.notify()
461
+ self.aborted_retries = True
462
+ self.context.signal("pipe;state", "STATE_FAILED_SUSPENDED")
463
+
464
+ def continue_retry(self):
465
+ with self._loop_cond:
466
+ self._loop_cond.notify()
467
+ self.aborted_retries = False
468
+ self.context.signal("pipe;state", "STATE_FAILED_RETRYING")
469
+
470
+ def usb_release(self):
471
+ if self.connection:
472
+ self.connection.release()
473
+ else:
474
+ raise ConnectionError
475
+
476
+ def usb_reset(self):
477
+ if self.connection:
478
+ self.connection.reset()
479
+ else:
480
+ raise ConnectionError
481
+
482
+ def challenge(self, serial):
483
+ if serial is None:
484
+ return
485
+
486
+ from hashlib import md5
487
+
488
+ challenge = bytearray.fromhex(md5(bytes(serial.upper(), "utf8")).hexdigest())
489
+ packet = b"A%s" % challenge
490
+ packet += b"F" * (30 - len(packet))
491
+ packet = b"\x00" + packet + bytes([onewire_crc_lookup(packet)])
492
+ self.connection.write(packet)
493
+ try:
494
+ self._confirm_serial()
495
+ except ConnectionError:
496
+ # If we could not access the status, then we did not confirm the serial number.
497
+ pass
498
+
499
+ def update_state(self, state):
500
+ with self._loop_cond:
501
+ self._loop_cond.notify()
502
+ if state == self.state:
503
+ return
504
+ self.state = state
505
+ if self.context is not None:
506
+ self.context.signal("pipe;thread", self.state)
507
+
508
+ def update_buffer(self):
509
+ self.context.signal("pipe;buffer", len(self))
510
+
511
+ def update_packet(self, packet):
512
+ self.context.signal("pipe;packet", convert_to_list_bytes(packet))
513
+ self.context.signal("pipe;packet_text", packet)
514
+ if self.usb_send_channel:
515
+ self.usb_send_channel(packet)
516
+
517
+ def _thread_loop(self):
518
+ while self.state not in ("end", "terminate"):
519
+ if self.state == "init":
520
+ # If we are initialized. Change that to active since we're running.
521
+ self.update_state("active")
522
+ elif self.state in ("pause", "busy", "suspend"):
523
+ # If we are paused just wait until the state changes.
524
+ if len(self._realtime_buffer) == 0 and len(self._preempt) == 0:
525
+ # Only pause if there are no realtime commands to queue.
526
+ self.context.laser_status = "idle"
527
+ with self._loop_cond:
528
+ self._loop_cond.wait()
529
+ continue
530
+ if self.aborted_retries:
531
+ # We are not trying reconnection anymore.
532
+ self.context.laser_status = "idle"
533
+ with self._loop_cond:
534
+ self._loop_cond.wait()
535
+ continue
536
+
537
+ self._check_transfer_buffer()
538
+ if len(self._realtime_buffer) <= 0 and len(self._buffer) <= 0:
539
+ # The buffer and realtime buffers are empty. No packet creation possible.
540
+ self.context.laser_status = "idle"
541
+ with self._loop_cond:
542
+ self._loop_cond.wait()
543
+ continue
544
+
545
+ try:
546
+ # We try to process the queue.
547
+ queue_processed = self.process_queue()
548
+ if self.refuse_counts:
549
+ self.context.signal("pipe;failing", 0)
550
+ self.refuse_counts = 0
551
+ if self.is_shutdown:
552
+ return # Sometimes it could reset this and escape.
553
+ except ConnectionRefusedError:
554
+ # The attempt refused the connection.
555
+ self.refuse_counts += 1
556
+ self.pre_ok = False
557
+ if self.refuse_counts >= 5:
558
+ self.context.signal("pipe;state", "STATE_FAILED_RETRYING")
559
+ self.context.signal("pipe;failing", self.refuse_counts)
560
+ self.context.laser_status = "idle"
561
+ if self.is_shutdown:
562
+ return # Sometimes it could reset this and escape.
563
+ time.sleep(3) # 3-second sleep on failed connection attempt.
564
+ continue
565
+ except ConnectionError:
566
+ # There was an error with the connection, close it and try again.
567
+ self.connection_errors += 1
568
+ self.pre_ok = False
569
+
570
+ self.context.laser_status = "idle"
571
+ time.sleep(0.5)
572
+ self.close()
573
+ continue
574
+
575
+ self.context.laser_status = "active" if queue_processed else "idle"
576
+ if queue_processed:
577
+ # Packet was sent.
578
+ if self.state not in (
579
+ "pause",
580
+ "busy",
581
+ "active",
582
+ "terminate",
583
+ ):
584
+ self.update_state("active")
585
+ continue
586
+ # No packet could be sent.
587
+ if self.state not in (
588
+ "pause",
589
+ "busy",
590
+ "terminate",
591
+ ):
592
+ self.update_state("idle")
593
+
594
+ def _thread_data_send(self):
595
+ """
596
+ Main threaded function to send data. While the controller is working the thread
597
+ will be doing work in this function.
598
+ """
599
+ with self._main_lock:
600
+ self.pre_ok = False
601
+ self.is_shutdown = False
602
+ self._thread_loop()
603
+ self._thread = None
604
+ self.update_state("end")
605
+ self.pre_ok = False
606
+ self.context.laser_status = "idle"
607
+
608
+ def _check_transfer_buffer(self):
609
+ if len(self._queue): # check for and append queue
610
+ with self._queue_lock:
611
+ self._buffer += self._queue
612
+ self._queue.clear()
613
+ self.update_buffer()
614
+
615
+ if len(self._preempt): # check for and prepend preempt
616
+ with self._preempt_lock:
617
+ self._realtime_buffer += self._preempt
618
+ self._preempt.clear()
619
+ self.update_buffer()
620
+
621
+ def process_queue(self):
622
+ """
623
+ Attempts to process the buffer/queue
624
+ Will fail on ConnectionRefusedError at open, 'process_queue_pause = True' (anytime before packet sent),
625
+ self._buffer is empty, or a failure to produce packet.
626
+
627
+ Buffer will not be changed unless packet is successfully sent, or pipe commands are processed.
628
+
629
+ The following are meta commands for the controller
630
+ - : require wait finish at the end of the queue processing.
631
+ * : clear the buffers, and abort the thread.
632
+ ! : pause.
633
+ & : resume.
634
+ % : fail checksum, do not resend
635
+ ~ : begin/end realtime exception (Note, these characters would be consumed during
636
+ the write process and should not exist in the queue)
637
+ \x18 : quit.
638
+
639
+ @return: queue process success.
640
+ """
641
+ if len(self._realtime_buffer) > 0:
642
+ buffer = self._realtime_buffer
643
+ realtime = True
644
+ elif len(self._buffer) > 0:
645
+ buffer = self._buffer
646
+ realtime = False
647
+ else:
648
+ return False
649
+
650
+ # Find buffer of 30 or containing '\n'.
651
+ find = buffer.find(b"\n", 0, 30)
652
+ if find == -1: # No end found.
653
+ length = min(30, len(buffer))
654
+ else: # Line end found.
655
+ length = min(30, len(buffer), find + 1)
656
+ packet = bytes(buffer[:length])
657
+
658
+ # edge condition of catching only pipe command without '\n'
659
+ if packet.endswith((b"-", b"*", b"&", b"!", b"#", b"%", b"\x18")):
660
+ packet += buffer[length : length + 1]
661
+ length += 1
662
+ post_send_command = None
663
+ default_checksum = True
664
+
665
+ # find pipe commands.
666
+ if packet.endswith(b"\n"):
667
+ packet = packet[:-1]
668
+ # There's a special case where we have a trailing "\n" at an exactly 30 byte command,
669
+ # that requires another package of 30 x F to be sent, so we need to deal with an empty string...
670
+ if len(packet) == 0:
671
+ packet += b"F"
672
+ if packet.endswith(b"P"):
673
+ # This is a special case where the m3nano seems to fail. So we extend the buffer...
674
+ packet += b"F"
675
+ elif packet.endswith(b"-"): # wait finish
676
+ packet = packet[:-1]
677
+ post_send_command = self.wait_finished
678
+ elif packet.endswith(b"*"): # abort
679
+ post_send_command = self.abort
680
+ packet = packet[:-1]
681
+ elif packet.endswith(b"&"): # resume
682
+ self._resume_busy()
683
+ packet = packet[:-1]
684
+ elif packet.endswith(b"!"): # pause
685
+ self._pause_busy()
686
+ packet = packet[:-1]
687
+ elif packet.endswith(b"%"): # alt-checksum
688
+ default_checksum = False
689
+ packet = packet[:-1]
690
+ elif packet.endswith(b"\x18"):
691
+ self.update_state("terminate")
692
+ self.is_shutdown = True
693
+ packet = packet[:-1]
694
+ if packet.startswith(b"A"):
695
+ # This is a challenge code. A is only used for serial challenges.
696
+ post_send_command = self._confirm_serial
697
+ if len(packet) != 0:
698
+ if packet.endswith(b"#"):
699
+ packet = packet[:-1]
700
+ try:
701
+ c = packet[-1]
702
+ except IndexError:
703
+ c = b"F" # Packet was simply #. We can do nothing.
704
+ packet += bytes([c]) * (30 - len(packet)) # Padding. '\n'
705
+ else:
706
+ packet += b"F" * (30 - len(packet)) # Padding. '\n'
707
+ if not realtime and self.state in ("pause", "busy"):
708
+ return False # Processing normal queue, PAUSE and BUSY apply.
709
+
710
+ # Packet is prepared and ready to send. Open Channel.
711
+ self.open()
712
+
713
+ if len(packet) == 30:
714
+ # We have a sendable packet.
715
+ if not self.pre_ok:
716
+ self.wait_until_accepting_packets()
717
+ if default_checksum:
718
+ packet = b"\x00" + packet + bytes([onewire_crc_lookup(packet)])
719
+ else:
720
+ packet = b"\x00" + packet + bytes([onewire_crc_lookup(packet) ^ 0xFF])
721
+ self.connection.write(packet)
722
+ self.pre_ok = False
723
+
724
+ # Packet is sent, trying to confirm.
725
+ status = 0
726
+ flawless = True
727
+ for attempts in range(500):
728
+ # We'll try to confirm this at 500 times.
729
+ try:
730
+ self.update_status()
731
+ status = self._status[1]
732
+ if attempts > 10:
733
+ time.sleep(min(0.001 * attempts, 0.1))
734
+ except ConnectionError:
735
+ # Errors are ignored, must confirm packet.
736
+ flawless = False
737
+ continue
738
+ if status == 0:
739
+ # We did not read a status.
740
+ continue
741
+ if status == STATUS_OK:
742
+ # Packet was fine.
743
+ self.pre_ok = True
744
+ break
745
+ elif status == STATUS_BUSY:
746
+ # Busy. We still do not have our confirmation. BUSY comes before ERROR or OK.
747
+ continue
748
+ elif status == STATUS_ERROR:
749
+ if not default_checksum:
750
+ break
751
+ self.context.rejected_count += 1
752
+ if flawless: # Packet was rejected. The CRC failed.
753
+ return False
754
+ else:
755
+ # The channel had the error, assuming packet was actually good.
756
+ break
757
+ elif status == STATUS_FINISH:
758
+ # We finished. If we were going to wait for that, we no longer need to.
759
+ if post_send_command == self.wait_finished:
760
+ post_send_command = None
761
+ continue # This is not a confirmation.
762
+ elif status == STATUS_SERIAL_CORRECT_M3_FINISH:
763
+ if post_send_command == self._confirm_serial:
764
+ # We confirmed the serial number on the card.
765
+ self.serial_confirmed = True
766
+ post_send_command = None
767
+ break
768
+ elif post_send_command == self.wait_finished:
769
+ # This is a STATUS_M3_FINISHED, we no longer wait.
770
+ post_send_command = None
771
+ continue
772
+
773
+ if status == 0: # After 500 attempts we could only get status = 0.
774
+ raise ConnectionError # Broken pipe. Could not confirm packet.
775
+ self.context.packet_count += (
776
+ 1 # Our packet is confirmed or assumed confirmed.
777
+ )
778
+ else:
779
+ if len(packet) != 0:
780
+ # We could only generate a partial packet, throw it back
781
+ return False
782
+ # We have an empty packet of only commands. Continue work.
783
+
784
+ # Packet was processed. Remove that data.
785
+ if realtime:
786
+ del self._realtime_buffer[:length]
787
+ else:
788
+ del self._buffer[:length]
789
+ if len(packet) != 0:
790
+ # Packet was completed and sent. Only then update the channel.
791
+ self.update_packet(packet)
792
+ self.update_buffer()
793
+
794
+ if post_send_command is not None:
795
+ # Post send command could be wait_finished, and might have a broken pipe.
796
+ try:
797
+ post_send_command()
798
+ except ConnectionError:
799
+ # We should have already sent the packet. So this should be fine.
800
+ pass
801
+ return True # A packet was prepped and sent correctly.
802
+
803
+ def update_status(self):
804
+ try:
805
+ self._status = self.connection.get_status()
806
+ except AttributeError:
807
+ # self.connection was closed by something.
808
+ raise ConnectionError
809
+ if self.context is not None:
810
+ try:
811
+ self.context.signal(
812
+ "pipe;status",
813
+ self._status,
814
+ get_code_string_from_code(self._status[1]),
815
+ )
816
+ except IndexError:
817
+ pass
818
+ if self.recv_channel:
819
+ self.recv_channel(str(self._status))
820
+
821
+ def wait_until_accepting_packets(self):
822
+ i = 0
823
+ while self.state != "terminate":
824
+ self.update_status()
825
+ if self._status is None:
826
+ raise ConnectionError
827
+ status = self._status[1]
828
+ if status == 0:
829
+ raise ConnectionError
830
+ if status == STATUS_OK:
831
+ self.pre_ok = False
832
+ break
833
+ if status == STATUS_ERROR:
834
+ break
835
+ time.sleep(0.05)
836
+ if self.context is not None:
837
+ self.context.signal("pipe;wait", STATUS_OK, i)
838
+ i += 1
839
+ if self.abort_waiting:
840
+ self.abort_waiting = False
841
+ return # Wait abort was requested.
842
+
843
+ def wait_finished(self):
844
+ i = 0
845
+ original_state = self.state
846
+ if self.state != "pause":
847
+ self.pause()
848
+
849
+ while True:
850
+ if self.state != "wait":
851
+ if self.state == "terminate":
852
+ return # Abort all the processes was requested. This state change would be after clearing.
853
+ self.update_state("wait")
854
+ self.update_status()
855
+ status = self._status[1]
856
+ if status == 0:
857
+ raise ConnectionError
858
+ if status == STATUS_ERROR:
859
+ self.context.rejected_count += 1
860
+ if status & 0x02 == 0:
861
+ # StateBitPEMP = 0x00000200, Finished = 0xEC, 11101100
862
+ break
863
+ if self.context is not None:
864
+ self.context.signal("pipe;wait", status, i)
865
+ i += 1
866
+ if self.abort_waiting:
867
+ self.abort_waiting = False
868
+ break # Wait abort was requested.
869
+ time.sleep(0.001) # Only if we are using control transfer status checks.
870
+ self.update_state(original_state)
871
+
872
+ def _confirm_serial(self):
873
+ t = time.time()
874
+ while time.time() - t < 0.5: # We spend up to half a second to confirm.
875
+ if self.state == "terminate":
876
+ # We are not confirmed.
877
+ return # Abort all the processes was requested. This state change would be after clearing.
878
+ self.update_status()
879
+ status = self._status[1]
880
+ if status == STATUS_SERIAL_CORRECT_M3_FINISH:
881
+ self.serial_confirmed = True
882
+ return # We're done.
883
+ self.serial_confirmed = False