index.js 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676
  1. function initLanguage(langKey) {
  2. let defaultLang = 'en';
  3. let lang = langKey || defaultLang;
  4. if (defaultLang !== lang) {
  5. injectLanguageJsSources(lang);
  6. //updateLanguageText();
  7. }
  8. }
  9. // logout
  10. $("#modal_logout_btn").on("click", function () {
  11. // logout();
  12. });
  13. document.domain = "cocorobo.cn";
  14. function logout() {
  15. $.ajax(`${CCB.base_url}api/logout`, {
  16. type: "GET",
  17. xhrFields: {
  18. withCredentials: true
  19. },
  20. success: () => {
  21. // $('#login_iframe').attr('src', '//staging.cocorobo.hk/login/');
  22. appendIframe("TM_login");
  23. $('#TM_login').children().css("height", "820px");
  24. appendIframe("TM_login_Model_download_modal");
  25. $('#TM_login_Model_download_modal').children().css("height", "820px");
  26. $('#TM_login_Model_download_modal').children().css("margin-top", "-225px");
  27. appendIframe("TM_login_object");
  28. $('#TM_login_object').children().css("height", "820px");
  29. appendIframe("TM_login_posenet");
  30. $('#TM_login_posenet').children().css("height", "820px");
  31. appendIframe("TM_posenet_login");
  32. $('#TM_posenet_login').children().css("height", "820px");
  33. appendIframe("before_login");
  34. appendIframe("cloud_askLogin");
  35. appendIframe("TM_login_webcam_capture_modal");
  36. $('#TM_login_webcam_capture_modal').children().css("width", "820px");
  37. $('#TM_login_webcam_capture_modal').children().css("height", "820px");
  38. appendIframe("TM_login_gesture_recog_modal");
  39. $('#TM_login_gesture_recog_modal').children().css("width", "820px");
  40. $('#TM_login_gesture_recog_modal').children().css("height", "820px");
  41. appendIframe("TM_login_voice_input_modal");
  42. $('#TM_login_voice_input_modal').children().css("width", "820px");
  43. $('#TM_login_voice_input_modal').children().css("height", "820px");
  44. appendIframe("TM_center_game");
  45. $('#TM_center_game').children().css("margin-top", "-300px");
  46. $('#TM_center_game').children().css("height", "820px");
  47. Materialize.toast(CCB.str_group.success_userLogout, 4000);
  48. CCB.userState = false;
  49. $("#cloud_fileListArea").html("");
  50. loginModalStatus();
  51. $("#modal_logout_btn").addClass('blue')
  52. $(".svgImg").css('display', 'none');
  53. $(".translate-signout").css('opacity', '1')
  54. }
  55. });
  56. }
  57. // 点击语言下拉隐藏
  58. // document.onclick = function () {
  59. // $('#languages').removeClass('active');
  60. // $('#languages').css({ display: 'none' })
  61. // }
  62. // 点击切换语言
  63. // $('#nav_language').click(function (e) {
  64. // $('#languages').addClass('active');
  65. // $('#languages').css({ display: 'block', opacity: 1, position: 'absolute',top:'64px' })
  66. // var ev = e || window.event;
  67. // if (ev.stopPropagation) { //阻止冒泡,否则会触发点击空白区域的事件
  68. // ev.stopPropagation();
  69. // } else if (window.event) {
  70. // window.event.cancelBubble = true; //兼容IE
  71. // }
  72. // })
  73. function getUrlLanguage() {
  74. const val = location.search.match(new RegExp('[?&]lang=([^&]+)'));
  75. let language = val ? decodeURIComponent(val[1].replace(/\+/g, '%20')) : '';
  76. if (['en', 'zh-hant', 'zh-hans'].indexOf(language) < 0) return 'zh-hant';
  77. return language;
  78. };
  79. function injectLanguageJsSources(langKey) {
  80. const head = document.getElementsByTagName('head')[0];
  81. // Retrieve and inject Ardublockly translations synchronously
  82. const appLangJsLoad = document.createElement('script');
  83. const request = createAjaxRequest();
  84. const appLangJdPath = `msg/${langKey}.js`;
  85. try {
  86. request.open('GET', appLangJdPath, false);
  87. request.send('');
  88. appLangJsLoad.text = request.responseText;
  89. } catch (e) {
  90. // But still asynchronous lazy load so at least some text gets translated
  91. appLangJsLoad.src = appLangJdPath;
  92. }
  93. head.appendChild(appLangJsLoad);
  94. // Retrieve and inject Blockly translations asynchronously
  95. const blocklyLangJsLoad = document.createElement('script');
  96. blocklyLangJsLoad.src = `blockly/msg/js/${langKey}.js`;
  97. head.appendChild(blocklyLangJsLoad);
  98. };
  99. function createAjaxRequest() {
  100. let request = false;
  101. try {
  102. // Firefox, Chrome, IE7+, Opera, Safari
  103. request = new XMLHttpRequest();
  104. } catch (e) {
  105. // IE6 and earlier
  106. try {
  107. request = new ActiveXObject('Msxml2.XMLHTTP');
  108. } catch (e) {
  109. try {
  110. request = new ActiveXObject('Microsoft.XMLHTTP');
  111. } catch (e) {
  112. throw 'Your browser does not support AJAX. You will not be able to' +
  113. 'use all of Ardublockly features.';
  114. request = null;
  115. }
  116. }
  117. }
  118. return request;
  119. };
  120. function updateLanguageText() {
  121. for (let textId in LOCALISED_TEXT) {
  122. const textStrings = document.getElementsByClassName(`translate-${textId}`);
  123. for (let i = 0; i < textStrings.length; i++) {
  124. textStrings[i].innerHTML = LOCALISED_TEXT[textId];
  125. }
  126. }
  127. };
  128. function clearBlocks(cb = () => { }) {
  129. const length = Blockly.mainWorkspace.getAllBlocks(true).length;
  130. if (length < 2) {
  131. Blockly.mainWorkspace.clear();
  132. cb();
  133. } else {
  134. Blockly.confirm(
  135. Blockly.Msg.DELETE_ALL_BLOCKS.replace("%1", length),
  136. ok => {
  137. if (!ok) return;
  138. Blockly.mainWorkspace.clear();
  139. cb();
  140. }
  141. );
  142. }
  143. }
  144. function addLibButton(lang) {
  145. // const addLib = document.createElement("button");
  146. // addLib.className = "waves-effect waves-light btn blue";
  147. // let content = lang === 'zh-hans' ? "添加库" : lang === 'zh-hant' ? "添加庫" : "Add Library";
  148. // addLib.textContent = content;
  149. // addLib.style = `
  150. // position: absolute;
  151. // width: 88%;
  152. // bottom: 10px;
  153. // left: 50%;
  154. // transform: translateX(-50%);
  155. // `;
  156. // $(addLib).click(e =>
  157. // blockpy.components.dialog.show("Add Library", document.createElement("div")));
  158. // $(".blocklyToolboxDiv").append(addLib);
  159. }
  160. // /**
  161. // * Save blocks into local storage. Note that MSIE 11 does not support
  162. // * LocalStorage on file:// URLs.
  163. // */
  164. // function saveLocalStorageBlocks() {
  165. // if (window.sessionStorage) {
  166. // var xml = blockpy.components.editor.getBlocksFromXml();
  167. // var text = Blockly.Xml.domToText(xml);
  168. // localStorage.setItem("blocks", text);
  169. // }
  170. // // blockpy.components.editor.getBlocksFromXml()
  171. // };
  172. // /** Load blocks saved on loacl storage and deletes them from storage. */
  173. // function loadLocalStorageBlocks() {
  174. // // try {
  175. // // var loadOnce = window.localStorage.loadOnceBlocks;
  176. // // } catch (e) {
  177. // // // Firefox sometimes throws a SecurityError when accessing sessionStorage.
  178. // // // Restarting Firefox fixes this, so it looks like a bug.
  179. // // var loadOnce = null;
  180. // // }
  181. // var loadBlocks = localStorage.getItem("blocks");
  182. // if (loadBlocks) {
  183. // var xml = Blockly.Xml.textToDom(loadBlocks);
  184. // blockpy.components.editor.setBlocksFromXml(xml);
  185. // localStorage.removeItem('blocks')
  186. // }
  187. // };
  188. var copyCodeClipboard;
  189. window.onbeforeunload = window.onunload = function () {
  190. if ($("#mode")[0].selectedIndex == 0) {
  191. saveLocalStorage("type", 1);
  192. saveLocalStorageBlocks("pythonai-mode-blocks-xml");
  193. } else {
  194. saveLocalStorage("type", 1);
  195. saveLocalStorageBlocks("pythonai-mode-blocks-xml");
  196. }
  197. }
  198. function getJsonData(filepath) {
  199. return new Promise(resolve => {
  200. $.getJSON(filepath, data => resolve(data));
  201. });
  202. }
  203. var isRunCodeData = '';
  204. var RunInterval = '';
  205. window.onload = async function () {
  206. $("#copyright_middle")[0].innerText = new Date().getFullYear()
  207. var url = window.location.hash.substring(1);
  208. // if (url) {
  209. // document.getElementById('ipAddress').value = 'ws://' + url;
  210. // }
  211. $('.dropdown-trigger').dropdown();
  212. setTimeout(() => $('.modal').modal(), 0);
  213. blockpy = new BlockPy({
  214. blocklyPath: "blockly/",
  215. attachmentPoint: document.getElementById("blockpy-div"),
  216. instructor:
  217. !getQueryParams()["instructor"] ||
  218. getQueryParams()["instructor"] == "true",
  219. developer: true,
  220. editor: getQueryParams()["mode"] || "Split",
  221. urls: {
  222. }
  223. });
  224. // ready();
  225. var size = calculate_size($("#term")[0]);
  226. term = new Terminal({
  227. cols: size[0],
  228. rows: size[1],
  229. useStyle: true,
  230. screenKeys: true,
  231. cursorBlink: false
  232. });
  233. term.open(document.getElementById("term"));
  234. //show_https_warning();
  235. $(".filled-in")[0].onclick = function () {
  236. var _chi = $(".filled-in")[0];
  237. var _par = $(".filled-in")[0].parentNode;
  238. if (!_chi.checked) {
  239. _par.children[1].className = 'filled-in_nocheked translatable_Adapter_fill_connected';
  240. _par.children[1].innerHTML = CCB.str_group.Adapter_fill_connected;
  241. } else {
  242. _par.children[1].className = 'translatable_Adapter_connected';
  243. _par.children[1].innerHTML = CCB.str_group.Adapter_connected;
  244. };
  245. }
  246. setTimeout(() => {
  247. cocoblockly();
  248. document.getElementsByTagName("svg")[0].focus()
  249. }, 0);
  250. $('.blockpy-toolbar-download').on(
  251. "click", () => export_data(
  252. pythonnewcode || Blockly.Python.workspaceToCode(blockpy.components.editor.blockly) || blockpy.components.editor.codeMirror.getValue(), '.py', 0
  253. )
  254. );
  255. // uploadpy
  256. document.getElementById('uploadpy').onclick = async function () {
  257. // decounce(uploadpyCocoPi(), 1000)
  258. uploadpyCocoPi()
  259. }
  260. // runCode
  261. document.getElementById('runCode').onclick = async function () {
  262. // decounce(runCocoPi(), 1000)
  263. runCocoPi()
  264. }
  265. const uploadXmlButton = $('#pyFileImport > input');
  266. uploadXmlButton.change(function () {
  267. var fr = new FileReader();
  268. var files = uploadXmlButton[0].files;
  269. const file = files[0];
  270. Ardublockly.alertExampleMessage(
  271. '', Ardublockly.getLocalStr('loadBlockBody'),
  272. true, {});
  273. fr.onload = function (e) {
  274. var pyInnerHTML = e.target.result;
  275. blockpy.components.editor.codeMirror.setValue(pyInnerHTML);
  276. };
  277. fr.readAsText(file);
  278. setTimeout(() => {
  279. $('#loading').css({ 'display': 'none' });
  280. $('#example_alert').modal('close');
  281. }, 300)
  282. uploadXmlButton.val("");
  283. });
  284. $('.blockpy-toolbar-upload').click(e => $('#pyFileImport > input').click());
  285. fanyi();
  286. selectOnload();
  287. styled()
  288. $('#toggle-button').click(() => {
  289. if ($('#toggle-button')[0].checked) {
  290. $('.edit')[0].style.display = 'none';
  291. // $('.edit')[1].style.display = 'none';
  292. // $('.translatable_editing')[0].style.display = "none";
  293. // $('.translatable_close_editing')[0].style.display = "inline-block"
  294. } else {
  295. $('.edit')[0].style.display = 'block';
  296. // $('.edit')[1].style.display = 'block';
  297. // $('.translatable_editing')[0].style.display = "inline-block";
  298. // $('.translatable_close_editing')[0].style.display = "none"
  299. }
  300. })
  301. $('#toggle-button1').click(() => {
  302. if ($('#toggle-button1')[0].checked) {
  303. $('#image_transmission_canvas')[0].style.display = 'none';
  304. // $('.translatable_editing')[0].style.display = "none";
  305. // $('.translatable_close_editing')[0].style.display = "inline-block"
  306. } else {
  307. $('#image_transmission_canvas')[0].style.display = 'block';
  308. // $('.translatable_editing')[0].style.display = "inline-block";
  309. // $('.translatable_close_editing')[0].style.display = "none"
  310. }
  311. })
  312. $("#webadbErro").click(() => {
  313. window.file_manger_modal = false
  314. let webadb_document = document.getElementById('webadb_iframe').contentWindow.getdevice()
  315. webadb_document.device.subprocess.shell(Repair).then(function (e) {
  316. e.stdout.reader.read().then(function (m) {
  317. var str = Uint8ArrayToString(m.value);
  318. if (str.indexOf("/bin/sh") > -1 || str.indexOf("Read-only file system") > -1) {
  319. webadb_document.device.subprocess.shell("reboot").then(s => {
  320. $("#webadbErro").css("display", "none")
  321. })
  322. } else {
  323. $("#webadbErro").css("display", "none")
  324. }
  325. setTimeout(() => {
  326. window.file_manger_modal = true
  327. })
  328. // 重启修复
  329. })
  330. }).catch(err => {
  331. window.file_manger_modal = true
  332. })
  333. })
  334. const _lang = getUrlLanguage();
  335. // 判断从python blcokly 跳转过来是ai或者iot
  336. if (window.location.search.indexOf('name=1') > -1 || window.location.search.indexOf('id=ai') > -1) {
  337. $("#mode")[0].selectedIndex = 1;
  338. $("#mode")[0].onchange();
  339. $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
  340. history.pushState(null, null, '//x.cocorobo.cn/?lang=' + _lang);
  341. selectmode($("#mode")[0], true);
  342. // document.getElementById("list").getElementsByTagName("li")[1].onclick();
  343. }
  344. else if (window.location.search.indexOf('name=0') > -1 || window.location.search.indexOf('id=iot') > -1) {
  345. $("#mode")[0].selectedIndex = 0;
  346. $("#mode")[0].onchange();
  347. $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.iot_module;
  348. history.pushState(null, null, '//x.cocorobo.cn/?lang=' + _lang);
  349. selectmode($("#mode")[0], true);
  350. // document.getElementById("list").getElementsByTagName("li")[0].onclick();
  351. }
  352. else {
  353. if (getLocalStorage("type") == 1) {
  354. $("#mode")[0].selectedIndex = 1;
  355. $("#mode")[0].onchange();
  356. $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
  357. selectmode($("#mode")[0], true);
  358. // document.getElementById("list").getElementsByTagName("li")[1].onclick();
  359. } else {
  360. $("#mode")[0].selectedIndex = 0;
  361. $("#mode")[0].onchange();
  362. $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.iot_module;
  363. selectmode($("#mode")[0], true);
  364. // document.getElementById("list").getElementsByTagName("li")[0].onclick();
  365. }
  366. }
  367. $('#white-box').css('display', 'none');
  368. const copyCodeClipboard = new ClipboardJS(".copy_code", {
  369. text: function () {
  370. return blockpy.components.editor.codeMirror.getValue();
  371. }
  372. });
  373. copyCodeClipboard.on("success", () => copyCodeToast(2000));
  374. mouseMove();
  375. const copyCodeToast = (function (lang) {
  376. let toast = null,
  377. timeout = null;
  378. const content = lang === 'zh-hans' ? "复制成功" :
  379. lang === 'zh-hant' ? "複製成功" : "Copy Successfully";
  380. return function (ms) {
  381. if (toast) {
  382. toast.dismiss();
  383. clearTimeout(timeout);
  384. }
  385. toast = Materialize.toast(content, ms);
  386. timeout = setTimeout(() => toast = timeout = null, ms);
  387. };
  388. })(_lang);
  389. $("#delete-all").click(() => clearBlocks());
  390. $("#screenshot").click(() => Blockly.captureDialog_());
  391. $("#clearOutput").click(() => $(".blockpy-printer").html(""));
  392. $("#resetAll").click(() => clearBlocks(() => $(".blockpy-printer").html("")));
  393. // $("#lang-tool").click(() => $("#side-lang-trigger > a").dropdown('open'));
  394. // $("#file-tool").click(() => $("#side-file-trigger > a").dropdown('open'));
  395. $("#blockpy-content > .blockpy-editor img.fullscreenIcon").click(e => {
  396. $(e.currentTarget.parentNode).toggleClass("fullscreen");
  397. $('.edit')[0].style.display = 'none';
  398. // $('.edit')[1].style.display = 'none';
  399. $("#blockpy-content > .blockpy-editor img.fullscreenIcon").toggleClass("hidden");
  400. $("html").toggleClass("fullscreenMode");
  401. setTimeout(function () {
  402. Blockly.svgResize(blockpy.components.editor.blockly);
  403. Blockly.svgResize(Blockly.mainWorkspace);
  404. }, 100)
  405. });
  406. $("#blockpy-content .card-header > img.fullscreenIcon").click(e => {
  407. $(e.currentTarget.parentNode.parentNode).toggleClass("fullscreen");
  408. $('.edit')[0].style.display = 'block';
  409. // $('.edit')[1].style.display = 'block';
  410. $("#blockpy-content .card-header > img.fullscreenIcon").toggleClass("hidden");
  411. $("html").toggleClass("fullscreenMode");
  412. setTimeout(() => $(".blockpy-toolbar > .blockpy-text")
  413. .css("height", "90%")
  414. .css("height", "100%"), 0);
  415. });
  416. let browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  417. if (browserWidth < 500) {
  418. $('.mobileSwitch')[0].style.display = "block"
  419. $('#py-editor')[0].style.display = "none"
  420. // $("#IP")[0].style.display = "block"
  421. }
  422. // if (document.getElementById("v831_img_save")) {
  423. // document.getElementById("v831_img_save").onclick = function (e) {
  424. // console.log(this,e)
  425. // console.log("v831_img_save 被点击")
  426. // };
  427. // }
  428. // 点击复制分享链接
  429. copyShare()
  430. window.file_manger_modal = true
  431. document.getElementById("webadb_iframe").onload = function () {
  432. setInterval(function () {
  433. if (document.getElementById("webadb_iframe").contentWindow.getdevice && window.file_manger_modal && deviceType == 0) {
  434. isDevice = document.getElementById("webadb_iframe").contentWindow.getdevice();
  435. isConnect = document.getElementById("webadb_iframe").contentWindow.isconnect()
  436. if (isDevice.device == undefined && isDevice.selectdevice == undefined) {
  437. $("#webadb_connect")[0].disabled = true;
  438. $("#webadb_add")[0].disabled = false;
  439. $("#runCode").addClass('disabled')
  440. $("#uploadpy").addClass('disabled')
  441. $("#resetDevice").addClass('disabled')
  442. $("#backHome").addClass('disabled')
  443. $("#poweroff").addClass('disabled')
  444. $("#OneClickUpgradeId").addClass("disabled")
  445. $("#CocoPiUpgrades").addClass("disabled")
  446. $('#message_file').css({ display: 'none' })
  447. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
  448. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusNotConn
  449. $('.progress > .determinate').css('width', 0);
  450. $('#cnt_icon').css('display', 'none')
  451. $('#discnt_icon').css('display', 'inline-block')
  452. $('#select-connected').attr("disabled", false)
  453. }
  454. else if (isDevice.device == undefined && isDevice.selectdevice != undefined) {
  455. $("#webadb_connect")[0].disabled = false;
  456. $("#webadb_add")[0].disabled = false;
  457. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusNotConn
  458. $("#runCode").addClass('disabled')
  459. $("#uploadpy").addClass('disabled')
  460. $("#resetDevice").addClass('disabled')
  461. $("#backHome").addClass('disabled')
  462. $("#poweroff").addClass('disabled')
  463. $("#OneClickUpgradeId").addClass("disabled")
  464. $("#CocoPiUpgrades").addClass("disabled")
  465. $('#message_file').css({ display: 'none' })
  466. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
  467. $('.progress > .determinate').css('width', 0);
  468. $('#cnt_icon').css('display', 'none')
  469. $('#discnt_icon').css('display', 'inline-block')
  470. $('#select-connected').attr("disabled", false);
  471. if (reconnect && switch_connect) {
  472. webadbConnect();
  473. }
  474. }
  475. else if (isDevice.device != undefined && isDevice.selectdevice != undefined) {
  476. $("#webadb_add")[0].disabled = true;
  477. if (!!isConnect) {
  478. $('#select-connected').attr("disabled", true)
  479. $('#cnt_icon').css('display', 'inline-block')
  480. $('#discnt_icon').css('display', 'none')
  481. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.disConnect
  482. $("#webadb_connect")[0].disabled = false;
  483. $('#message_file').css({ display: 'inline-block' })
  484. $("#runCode").removeClass('disabled')
  485. $("#uploadpy").removeClass('disabled')
  486. $("#resetDevice").removeClass('disabled')
  487. $("#poweroff").removeClass('disabled')
  488. $("#OneClickUpgradeId").removeClass("disabled")
  489. $("#CocoPiUpgrades").removeClass("disabled")
  490. if (autoContent) {
  491. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusbar
  492. }
  493. } else {
  494. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
  495. $("#webadb_connect")[0].disabled = true;
  496. $('#message_file').css({ display: 'none' })
  497. }
  498. }
  499. } else if (deviceType == 2) {
  500. // console.log("bledevice",bledevice)
  501. if (bledevice && bledevice.gatt && bledevice.gatt.connected) {
  502. $('#select-connected').attr("disabled", true)
  503. $('#cnt_icon').css('display', 'inline-block')
  504. $('#discnt_icon').css('display', 'none')
  505. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.disConnect
  506. $("#webadb_connect")[0].disabled = false;
  507. $('#message_file').css({ display: 'inline-block' })
  508. $("#runCode").removeClass('disabled')
  509. $("#uploadpy").removeClass('disabled')
  510. $("#resetDevice").addClass('disabled')
  511. $("#poweroff").addClass('disabled')
  512. $("#OneClickUpgradeId").removeClass("disabled")
  513. $("#CocoPiUpgrades").removeClass("disabled")
  514. if ($("#status_txt")[0].innerHTML == Ardublockly.LOCALISED_TEXT.statusNotConn) {
  515. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusbar
  516. }
  517. } else {
  518. $("#webadb_add")[0].disabled = false;
  519. $("#runCode").addClass('disabled')
  520. $("#uploadpy").addClass('disabled')
  521. $("#resetDevice").addClass('disabled')
  522. // $("#backHome").removeClass('disabled')
  523. $("#poweroff").addClass('disabled')
  524. $("#OneClickUpgradeId").addClass("disabled")
  525. $("#CocoPiUpgrades").addClass("disabled")
  526. $('#message_file').css({ display: 'none' })
  527. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
  528. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusNotConn
  529. $('.progress > .determinate').css('width', 0);
  530. $('#cnt_icon').css('display', 'none')
  531. $('#discnt_icon').css('display', 'inline-block')
  532. $('#select-connected').attr("disabled", false)
  533. if (bledevice && bledevice.id) {
  534. $("#webadb_connect")[0].disabled = false;
  535. }
  536. }
  537. }
  538. }, 1000)
  539. }
  540. // 加载更新提示框
  541. let updateData = await getJsonData('./update.json');
  542. // 最新更新你内容
  543. let updateNew = _lang == "zh-hans" ? updateData.updateNew.zhHans : _lang == "zh-hant" ? updateData.updateNew.zhHant : updateData.updateNew.en;
  544. let isUpdate = localStorage.getItem('isUpdate') || 0
  545. let blocklLis = "";
  546. let exampleLis = "";
  547. let noteLis = ""
  548. for (let i = 0; i < updateNew.blocks.length; i++) {
  549. let blockLi = `<li>${updateNew.blocks[i]}</li>`
  550. blocklLis = blocklLis + blockLi
  551. }
  552. $('#blockLis').append(blocklLis)
  553. for (let i = 0; i < updateNew.example.length; i++) {
  554. let exampleLi = `<li>${updateNew.example[i]}</li>`
  555. exampleLis = exampleLis + exampleLi
  556. }
  557. $('#exampleLis').append(exampleLis)
  558. for (let i = 0; i < updateNew.note.length; i++) {
  559. let noteLi = `<li>${updateNew.note[i]}</li>`
  560. noteLis = noteLis + noteLi
  561. }
  562. $('#noteLis').append(noteLis)
  563. $(".updateTime")[0].innerHTML = updateData.updateNew.time
  564. // 历史更新
  565. let updateDataOld = updateData.updateOld
  566. let leftStr = ''
  567. let noteStr = ''
  568. for (let i = 0; i < updateDataOld.length; i++) {
  569. let data = updateDataOld[i]
  570. let time = `<h5>${data.time}</h5>`;
  571. let updateData = _lang == "zh-hans" ? data.zhHans : _lang == "zh-hant" ? data.zhHant : data.en;
  572. let blocklLisOld = ''
  573. let exampleLisOld = ''
  574. let noteLisOld = ''
  575. for (let i = 0; i < updateData.blocks.length; i++) {
  576. let blockLi = `<li>${updateData.blocks[i]}</li>`
  577. blocklLisOld = blocklLisOld + blockLi
  578. }
  579. for (let i = 0; i < updateData.example.length; i++) {
  580. let exampleLi = `<li>${updateData.example[i]}</li>`
  581. exampleLisOld = exampleLisOld + exampleLi
  582. }
  583. for (let i = 0; i < updateData.note.length; i++) {
  584. let noteLi = `<li>${updateData.note[i]}</li>`
  585. noteLisOld = noteLisOld + noteLi
  586. }
  587. leftStr = leftStr + `${time}<li><span>${Ardublockly.LOCALISED_TEXT.updateblock}<ul class="updateContent">${blocklLisOld}</ul></li><li>${Ardublockly.LOCALISED_TEXT.updateexample}<ul class="updateContent">${exampleLisOld}</ul></li>`
  588. noteStr = noteStr + `${time}${noteLisOld}`
  589. }
  590. $('#leftUpdateOld').append(leftStr)
  591. $('#noteLisOld').append(noteStr)
  592. // $("#root").modal("open");
  593. }
  594. function styled() {
  595. if (window.location.search.indexOf("en") > -1) {
  596. $(".downbox-style").css({ width: '280px', marginLeft: '-100px' }),
  597. $(".HarxA1").css({ left: "calc(100% - 610px)" });
  598. $('#aaa .HarxA1').addClass('HarxA1_style')
  599. // $(".container-bottom").css("height","390px")
  600. $(".modelDownloadItemTitle").css("marginTop", "15px");
  601. $(".vision_category").css("marginTop", "15px");
  602. $(".model_download_modal_column").css("height", "435px");
  603. $(".modelDownloadItemDesc").css("height", "110px");
  604. }
  605. }
  606. function fanyi() {
  607. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn
  608. $('.ModeSelect')[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_Example;
  609. $('.ModeBox')[0].children[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.artificial_intelligence_textbook_program;
  610. $('.Hardware9 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.third_grade;
  611. $('.ModeBox ul')[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.recorded_voice_command;
  612. $('.ModeBox ul')[0].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.voice_recognition_lamp_stand;
  613. $('.Hardware4n div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.four_grade;
  614. $('.ModeBox ul')[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_aifr;
  615. $('.ModeBox ul')[1].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aiaor;
  616. $('.Hardware5 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.fifth_grade;
  617. $('.ModeBox ul')[2].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.recorded_voice_command;
  618. $('.ModeBox ul')[2].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.intelligent_curtain;
  619. $('.ModeBox ul')[2].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.fruit_picking_robot;
  620. $('.ModeBox ul')[2].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.fntelligent_inspection_robot;
  621. $('.Hardware6 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.sixth_grade;
  622. $('.ModeBox ul')[3].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.intelligent_traffic_lights;
  623. $('.ModeBox ul')[3].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.seeing_eye_necklace;
  624. $('.ModeBox ul')[3].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.code_package_sorting_robot;
  625. $('.ModeBox ul')[3].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.unmanned_circulation_car;
  626. $('.Hardware7 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.seventh_grade;
  627. $('.ModeBox ul')[4].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.face_recognition_electronic_police;
  628. $('.Hardware8 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.eighth_grade;
  629. $('.ModeBox ul')[5].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.payment_platform;
  630. $('.ModeBox')[0].children[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_Basics;
  631. $('.ModeBox ul')[6].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_sbcb;
  632. $('.ModeBox ul')[6].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_sbcsl;
  633. $('.ModeBox ul')[6].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_tacl;
  634. $('.ModeBox ul')[6].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_ba;
  635. $('.ModeBox ul')[6].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_desl;
  636. $('.ModeBox ul')[6].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_tdsl;
  637. $('.ModeBox ul')[6].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_ha;
  638. $('.ModeBox ul')[6].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_ssl;
  639. $('.ModeBox ul')[6].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_ldliv;
  640. $('.ModeBox')[0].children[2].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_imefc;
  641. $('.ModeBox ul')[7].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_uls;
  642. $('.ModeBox ul')[7].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_umdm;
  643. $('.ModeBox ul')[7].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_uoglls;
  644. $('.ModeBox ul')[7].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_auogsm;
  645. $('.ModeBox ul')[7].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_ctsotem;
  646. $('.ModeBox ul')[7].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_thwos;
  647. $('.ModeBox ul')[7].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_sdla;
  648. $('.ModeBox ul')[7].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_line;
  649. $('.ModeBox ul')[7].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_bccs;
  650. $('.ModeBox ul')[7].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_stepCounter;
  651. $('.ModeBox ul')[7].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_stepCounter_1;
  652. $('.ModeBox ul')[7].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_bluetooth_send;
  653. $('.ModeBox ul')[7].children[12].innerHTML = Ardublockly.LOCALISED_TEXT.select_bluetooth_receive;
  654. $('.ModeBox')[0].children[3].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_ionc;
  655. $('.ModeBox ul')[8].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_btsldtc;
  656. $('.ModeBox ul')[8].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_ktsedti;
  657. $('.ModeBox ul')[8].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_btoldalua;
  658. $('.ModeBox ul')[8].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_tsedtc;
  659. $('.ModeBox ul')[8].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_toedaluatc;
  660. $('.ModeBox ul')[8].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_ewhadtnocd;
  661. $('.ModeBox ul')[8].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_ledss;
  662. $('.ModeBox ul')[8].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_ledac;
  663. $('.ModeBox ul')[8].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_ctwn;
  664. $('.ModeBox ul')[8].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_bssbms;
  665. $('.ModeBox ul')[8].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_bsrbmc;
  666. $('.ModeBox ul')[8].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_wrcbms;
  667. $('.ModeBox ul')[8].children[12].innerHTML = Ardublockly.LOCALISED_TEXT.select_wrcbmr;
  668. $('.ModeBox ul')[8].children[13].innerHTML = Ardublockly.LOCALISED_TEXT.select_snt;
  669. $('.ModeBox ul')[8].children[14].innerHTML = Ardublockly.LOCALISED_TEXT.select_dwsdat;
  670. $('.ModeBox')[0].children[4].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_work_u;
  671. $('.ModeBox ul')[9].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_middle_led;
  672. $('.ModeBox ul')[9].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_all_led;
  673. $('.ModeBox ul')[9].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_liu_led;
  674. $('.ModeBox ul')[9].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_warning;
  675. $('.ModeBox ul')[9].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_music;
  676. $('.ModeBox ul')[9].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_button_open;
  677. $('.ModeBox ul')[9].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_touch_open;
  678. $('.ModeBox ul')[9].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_button_close;
  679. $('.ModeBox ul')[9].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_control_LED;
  680. $('.ModeBox ul')[9].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_sensor_LED;
  681. $('.ModeBox ul')[9].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_humidity_alarm;
  682. $('.ModeBox')[0].children[5].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_work_d;
  683. $('.ModeBox ul')[10].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_shaking_LED;
  684. // $('.ModeBox ul')[4].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_connect_wifi;
  685. $('.ModeBox ul')[10].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_show_statement;
  686. $('.ModeBox ul')[10].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_establish_WiFi;
  687. $('.ModeBox ul')[10].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_download_lighting;
  688. $('.ModeBox ul')[10].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_controlling_servo;
  689. $('.ModeBox ul')[10].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_move_servo;
  690. $('.ModeBox ul')[10].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_button_controlling_servo;
  691. $('.ModeBox ul')[10].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_face_recognition_door;
  692. $('.ModeBox ul')[10].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_speech_recognition_car;
  693. $('.ModeBox ul')[10].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_gyro_control_robot;
  694. $('.ModeBox ul')[10].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_gesture_recognition_robot;
  695. $('.ModeBox ul')[10].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_speech_recogniton_lamp;
  696. $('.ModeBox')[0].children[6].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_smmlc;
  697. $('.ModeBox ul')[11].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.basis_face_Intelligent;
  698. $('.ModeBox ul')[11].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_gcaerhk;
  699. $('.ModeBox ul')[11].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_frs;
  700. $('.ModeBox ul')[11].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_ors;
  701. $('.ModeBox ul')[11].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_fr;
  702. $('.ModeBox ul')[11].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_or;
  703. $('.ModeBox ul')[11].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_srd;
  704. $('.ModeBox ul')[11].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_srt;
  705. $('.ModeBox ul')[11].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_mhdr;
  706. $('.ModeBox')[0].children[7].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_ambc;
  707. $('.ModeBox ul')[12].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_bcsc;
  708. $('.ModeBox ul')[12].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_kcpccs;
  709. $('.ModeBox ul')[12].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_kcpficc;
  710. $('.ModeBox ul')[12].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_bccs;
  711. $('.ModeBox ul')[12].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_mc;
  712. $('.ModeBox ul')[12].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_sor;
  713. $('.ModeBox ul')[12].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_sdla;
  714. $('.ModeBox')[0].children[8].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_amefc;
  715. $('.ModeBox ul')[13].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_auls;
  716. $('.ModeBox ul')[13].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aumdm;
  717. $('.ModeBox ul')[13].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_auogsm;
  718. $('.ModeBox ul')[13].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_actsotem;
  719. $('.ModeBox ul')[13].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_greedy_snake;
  720. $('.ModeBox')[0].children[9].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_amvc;
  721. $('.ModeBox ul')[14].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_bctbotci;
  722. $('.ModeBox ul')[14].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aca;
  723. $('.ModeBox ul')[14].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_rqc;
  724. $('.ModeBox ul')[14].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_lhbl;
  725. $('.ModeBox ul')[14].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_fgr;
  726. $('.ModeBox ul')[14].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_fgaat;
  727. $('.ModeBox')[0].children[10].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_av;
  728. $('.ModeBox ul')[15].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.paly_video;
  729. $('.ModeBox ul')[15].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.paly_music;
  730. $('.ModeBox ul')[15].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.recording_camera;
  731. $('.ModeBox ul')[15].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.microphone_sound_analysis;
  732. $('.ModeBox')[0].children[11].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_teacher;
  733. $('.ModeBox ul')[16].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_thw;
  734. $('.ModeBox ul')[16].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_thwos;
  735. $('.ModeBox ul')[16].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_uoc;
  736. $('.ModeBox ul')[16].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_mc;
  737. $('.ModeBox ul')[16].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_sor;
  738. $('.ModeBox')[0].children[12].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_teacher2;
  739. $('.ModeBox ul')[17].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_aiaor;
  740. $('.ModeBox ul')[17].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aifr;
  741. $('.ModeBox ul')[17].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_aica;
  742. $('.ModeBox ul')[17].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_aisrc;
  743. $('.ModeBox ul')[17].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_aisrr;
  744. $('.ModeBox ul')[17].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_aiaa;
  745. $('.ModeBox')[0].children[13].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_teachingcases;
  746. $('.ModeBox ul')[18].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ex1_servo;
  747. $('.ModeBox ul')[18].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ex2_Ultrasound;
  748. // $('.ModeBox ul')[12].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ex3_RangeFinder;
  749. // $('.ModeBox ul')[12].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ex4_LightStrip;
  750. // $('.ModeBox ul')[12].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.ex5_Microbit;
  751. // $('.ModeBox ul')[12].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.ex6_MicrobitFace;
  752. // $('.ModeBox ul')[12].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.ex7_Door;
  753. $('.ModeBox ul')[18].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ex4_LightStrip
  754. $('.ModeBox ul')[18].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ex5_Microbit;
  755. $('.ModeBox ul')[18].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.ex6_MicrobitFace;
  756. $('.ModeBox ul')[18].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.ex7_Door;
  757. $('.ModeBox')[0].children[14].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_wc;
  758. $('.ModeBox ul')[19].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_smaa;
  759. $('.ModeBox ul')[19].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ai_gc;
  760. $('.ModeBox ul')[19].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ai_wsb;
  761. $('.ModeBox')[0].children[15].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_ad;
  762. $('.ModeBox ul')[20].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_trsr;
  763. $('.ModeBox ul')[20].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tpl2;
  764. $('.ModeBox ul')[20].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tpll;
  765. $('.ModeBox ul')[20].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tph;
  766. $('.ModeBox')[0].children[16].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm;
  767. $('.ModeBox ul')[21].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm_iot_send;
  768. $('.ModeBox ul')[21].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm_ai_get;
  769. $('.ModeBox ul')[21].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm_ai_send;
  770. $('.ModeBox ul')[21].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm_iot_get;
  771. $('.ModeBox1')[0].children[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.artificial_intelligence_textbook_program;
  772. $('.Hardware9 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.third_grade;
  773. $('.ModeBox1 ul')[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.recorded_voice_command;
  774. $('.ModeBox1 ul')[0].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.voice_recognition_lamp_stand;
  775. $('.Hardware4n div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.four_grade;
  776. $('.ModeBox1 ul')[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_aifr;
  777. $('.ModeBox1 ul')[1].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aiaor;
  778. $('.Hardware5 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.fifth_grade;
  779. $('.ModeBox1 ul')[2].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.recorded_voice_command;
  780. $('.ModeBox1 ul')[2].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.intelligent_curtain;
  781. $('.ModeBox1 ul')[2].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.fruit_picking_robot;
  782. $('.ModeBox1 ul')[2].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.fntelligent_inspection_robot;
  783. $('.Hardware6 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.sixth_grade;
  784. $('.ModeBox1 ul')[3].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.intelligent_traffic_lights;
  785. $('.ModeBox1 ul')[3].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.seeing_eye_necklace;
  786. $('.ModeBox1 ul')[3].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.code_package_sorting_robot;
  787. $('.ModeBox1 ul')[3].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.unmanned_circulation_car;
  788. $('.Hardware7 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.seventh_grade;
  789. $('.ModeBox1 ul')[4].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.face_recognition_electronic_police;
  790. $('.Hardware8 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.eighth_grade;
  791. $('.ModeBox1 ul')[5].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.payment_platform;
  792. $('.ModeBox1')[0].children[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_Basics;
  793. $('.ModeBox1 ul')[6].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_sbcb;
  794. $('.ModeBox1 ul')[6].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_sbcsl;
  795. $('.ModeBox1 ul')[6].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_tacl;
  796. $('.ModeBox1 ul')[6].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_ba;
  797. $('.ModeBox1 ul')[6].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_desl;
  798. $('.ModeBox1 ul')[6].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_tdsl;
  799. $('.ModeBox1 ul')[6].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_ha;
  800. $('.ModeBox1 ul')[6].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_ssl;
  801. $('.ModeBox1 ul')[6].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_ldliv;
  802. $('.ModeBox1')[0].children[2].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_imefc;
  803. $('.ModeBox1 ul')[7].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_uls;
  804. $('.ModeBox1 ul')[7].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_umdm;
  805. $('.ModeBox1 ul')[7].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_uoglls;
  806. $('.ModeBox1 ul')[7].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_auogsm;
  807. $('.ModeBox1 ul')[7].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_ctsotem;
  808. $('.ModeBox1 ul')[7].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_thwos;
  809. $('.ModeBox1 ul')[7].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_sdla;
  810. $('.ModeBox1 ul')[7].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_line;
  811. $('.ModeBox1 ul')[7].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_bccs;
  812. $('.ModeBox1 ul')[7].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_stepCounter;
  813. $('.ModeBox1 ul')[7].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_stepCounter_1;
  814. $('.ModeBox1 ul')[7].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_bluetooth_send;
  815. $('.ModeBox1 ul')[7].children[12].innerHTML = Ardublockly.LOCALISED_TEXT.select_bluetooth_receive;
  816. $('.ModeBox1')[0].children[3].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_ionc;
  817. $('.ModeBox1 ul')[8].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_btsldtc;
  818. $('.ModeBox1 ul')[8].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_ktsedti;
  819. $('.ModeBox1 ul')[8].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_btoldalua;
  820. $('.ModeBox1 ul')[8].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_tsedtc;
  821. $('.ModeBox1 ul')[8].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_toedaluatc;
  822. $('.ModeBox1 ul')[8].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_ewhadtnocd;
  823. $('.ModeBox1 ul')[8].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_ledss;
  824. $('.ModeBox1 ul')[8].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_ledac;
  825. $('.ModeBox1 ul')[8].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_ctwn;
  826. $('.ModeBox1 ul')[8].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_bssbms;
  827. $('.ModeBox1 ul')[8].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_bsrbmc;
  828. $('.ModeBox1 ul')[8].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_wrcbms;
  829. $('.ModeBox1 ul')[8].children[12].innerHTML = Ardublockly.LOCALISED_TEXT.select_wrcbmr;
  830. $('.ModeBox1 ul')[8].children[13].innerHTML = Ardublockly.LOCALISED_TEXT.select_snt;
  831. $('.ModeBox1 ul')[8].children[14].innerHTML = Ardublockly.LOCALISED_TEXT.select_dwsdat;
  832. $('.ModeBox1')[0].children[4].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_smmlc;
  833. $('.ModeBox1 ul')[9].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.basis_face_Intelligent;
  834. $('.ModeBox1 ul')[9].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_gcaerhk;
  835. $('.ModeBox1 ul')[9].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_frs;
  836. $('.ModeBox1 ul')[9].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_ors;
  837. $('.ModeBox1 ul')[9].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_fr;
  838. $('.ModeBox1 ul')[9].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_or;
  839. $('.ModeBox1 ul')[9].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_srd;
  840. $('.ModeBox1 ul')[9].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_srt;
  841. $('.ModeBox1 ul')[9].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_mhdr;
  842. $('.ModeBox1')[0].children[5].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_ad;
  843. $('.ModeBox1 ul')[10].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_trsr;
  844. $('.ModeBox1 ul')[10].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tpl2;
  845. $('.ModeBox1 ul')[10].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tpll;
  846. $('.ModeBox1 ul')[10].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tph;
  847. // $('#uploadFiles')[0].innerHTML = Ardublockly.LOCALISED_TEXT.uploadFiles;
  848. $("#sketch_name").val(Ardublockly.LOCALISED_TEXT.sketch_name);
  849. // $('#runCode')[0].innerHTML = Ardublockly.LOCALISED_TEXT.runCode;
  850. // $('#uploadFiles')[0].innerHTML = Ardublockly.LOCALISED_TEXT.uploadFiles;
  851. // $('#resetMainUI')[0].innerHTML = Ardublockly.LOCALISED_TEXT.resetMainUI;
  852. $('#select_dropdown')[0].value = Ardublockly.LOCALISED_TEXT.select_dropdown;
  853. // $('#iot_modules')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
  854. $(".qiehuanbtn")[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.a_csm;
  855. $("#localsssssaveOrOpen")[0].children[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.a_butvmi;
  856. $("#localsssssaveOrOpen")[0].children[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.a_buartlp;
  857. }
  858. var deviceType = 0 // 0有线;1无线;2蓝牙
  859. function selectOnload() {
  860. $('.select-connected')[0].onchange = function () {
  861. var a = $('.select-connected')[0].selectedIndex;
  862. deviceType = a
  863. if (a == 0) {
  864. $('#Serial_Interaction').css("display", 'inline-block')
  865. $('#IP').css('display', 'none')
  866. } else if (a == 2) {
  867. // console.log("蓝牙")webadb_add
  868. // deviceType = 2
  869. $('#Serial_Interaction').css("display", 'none')
  870. $('#IP').css('display', 'none')
  871. }
  872. else {
  873. // deviceType = 1
  874. $('#Serial_Interaction').css("display", 'none')
  875. $('#IP').css('display', 'block')
  876. // 进行socket 连接
  877. }
  878. }
  879. $('.selectMode_input')[0].parentNode.onclick = function (e) {
  880. $('.MouduleBox')[0].style.cssText = 'display:block';
  881. }
  882. $('.ModeSelectBox')[0].onclick = function (e) {
  883. U.UF.EV.stopBubble();
  884. // $('.ModeSelect')[0].className = 'ModeSelect active';
  885. $("#select_Example_modal").modal("open")
  886. }
  887. $('#update_log')[0].onclick = function (e) {
  888. $("#loadModal").modal("open")
  889. }
  890. $('#model_download_modal')[0].onclick = function (e) {
  891. $("#select_Model_download_modal").modal("open")
  892. }
  893. var modelsItems = document.getElementsByClassName("modelDownloadItemTitle");
  894. var modelsItemDescs = document.getElementsByClassName("modelDownloadItemDesc");
  895. for (var i = 0, len = modelsItems.length; i < len; i++) {
  896. modelsItems[i].title = modelsItems[i].innerHTML;
  897. }
  898. for (var i = 0, len = modelsItemDescs.length; i < len; i++) {
  899. modelsItemDescs[i].title = modelsItemDescs[i].innerHTML;
  900. }
  901. // var items = document.getElementById("list").getElementsByTagName("li");
  902. //获取5个内容盒子;
  903. var divs = document.getElementById("item").getElementsByTagName("div");
  904. var examples = document.getElementById("item").getElementsByTagName("li");
  905. var divs_type = document.getElementById("item_1").getElementsByTagName("div");
  906. var examples_type = document.getElementById("item_1").getElementsByTagName("li");
  907. var exampleList = document.getElementById("example").getElementsByClassName("con");
  908. // if (items.length != divs.length) {
  909. // return;
  910. // }
  911. for (var i = 0, len = examples.length; i < len; i++) {
  912. examples[i].id = i;
  913. examples[i].onclick = function () {
  914. for (var j = 0, len = examples.length; j < len; j++) {
  915. examples[j].className = "container-middle-noactive arrow";
  916. divs_type[j].style.display = "none";
  917. }
  918. for (var k = 0, len = examples_type.length; k < len; k++) {
  919. examples_type[k].className = "container-middle-1-noactive arrow";
  920. exampleList[k].style.display = "none";
  921. }
  922. this.className = "container-middle-active arrow_active";
  923. divs_type[this.id].getElementsByTagName("li")[0].className = "container-middle-1-active arrow_active";
  924. divs_type[this.id].style.display = "block";
  925. if (this.id == 0) {
  926. for (var k = 0, len = exampleList.length; k < len; k++) {
  927. exampleList[k].style.display = "none";
  928. }
  929. exampleList[0].style.display = "block";
  930. }
  931. else if (this.id == 1) {
  932. for (var k = 0, len = exampleList.length; k < len; k++) {
  933. exampleList[k].style.display = "none";
  934. }
  935. exampleList[8].style.display = "block";
  936. }
  937. else if (this.id == 2) {
  938. for (var k = 0, len = exampleList.length; k < len; k++) {
  939. exampleList[k].style.display = "none";
  940. }
  941. exampleList[11].style.display = "block";
  942. }
  943. else if (this.id == 3) {
  944. for (var k = 0, len = exampleList.length; k < len; k++) {
  945. exampleList[k].style.display = "none";
  946. }
  947. exampleList[13].style.display = "block";
  948. }
  949. else if (this.id == 4) {
  950. for (var k = 0, len = exampleList.length; k < len; k++) {
  951. exampleList[k].style.display = "none";
  952. }
  953. exampleList[15].style.display = "block";
  954. }
  955. else if (this.id == 5) {
  956. for (var k = 0, len = exampleList.length; k < len; k++) {
  957. exampleList[k].style.display = "none";
  958. }
  959. exampleList[22].style.display = "block";
  960. }
  961. else if (this.id == 6) {
  962. for (var k = 0, len = exampleList.length; k < len; k++) {
  963. exampleList[k].style.display = "none";
  964. }
  965. exampleList[27].style.display = "block";
  966. }
  967. else {
  968. for (var k = 0, len = exampleList.length; k < len; k++) {
  969. exampleList[k].style.display = "none";
  970. }
  971. exampleList[32].style.display = "block";
  972. }
  973. }
  974. }
  975. for (var i = 0, len = examples_type.length; i < len; i++) {
  976. examples_type[i].id = i;
  977. examples_type[i].onclick = function () {
  978. for (var k = 0, len = examples_type.length; k < len; k++) {
  979. examples_type[k].className = "container-middle-1-noactive arrow";
  980. exampleList[k].style.display = "none";
  981. }
  982. this.className = "container-middle-1-active arrow_active";
  983. exampleList[this.id].style.display = "block";
  984. }
  985. }
  986. likeclose($('.selectMode_input')[0].parentNode, $('.MouduleBox')[0], '', '');
  987. likeclose($('.ModeSelect')[0].children[0], $('.ModeSelect')[0], 1, 'ModeSelect');
  988. likeclose($('#bar_ai img')[0], $('.MouduleBox')[1], '', '');
  989. likeclose($('#bar_t img')[0], $('#ai_tt')[0], '', '');
  990. var MChild = $('.MouduleBox')[0].children;
  991. var tchild = $('.MouduleBox')[1].children;
  992. for (var i = 0; i < MChild.length; i++) {
  993. tchild[i].onclick = MChild[i].onclick = function (e) {
  994. window.event ? window.event.cancelBubble = true : e.stopPropagation()
  995. var e = e.target;
  996. if (e.parentElement.children[2] && e.parentElement.children[2].children.length > 0) { } else {
  997. if (e.innerHTML == Ardublockly.LOCALISED_TEXT.iot_module) {
  998. $("#mode")[0].selectedIndex = 0;
  999. $("#mode")[0].onchange();
  1000. $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.iot_module;
  1001. // document.getElementById("list").getElementsByTagName("li")[0].onclick();
  1002. }
  1003. else if (e.innerHTML == Ardublockly.LOCALISED_TEXT.ai_module) {
  1004. $("#mode")[0].selectedIndex = 1;
  1005. $("#mode")[0].onchange();
  1006. $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
  1007. // document.getElementById("list").getElementsByTagName("li")[1].onclick();
  1008. }
  1009. $('.MouduleBox')[0].style.display = 'none';
  1010. $('.MouduleBox')[1].style.display = 'none';
  1011. $('#ai_tt')[0].style.display = 'none';
  1012. }
  1013. }
  1014. }
  1015. for (var i = 0; i < $('.ModeBox')[0].children.length; i++) {
  1016. $('.ModeBox')[0].children[i].onclick = function (e) {
  1017. window.event ? window.event.cancelBubble = true : e.stopPropagation()
  1018. }
  1019. }
  1020. for (var i = 0; i < $('.ModeBox1')[0].children.length; i++) {
  1021. $('.ModeBox1')[0].children[i].onclick = function (e) {
  1022. window.event ? window.event.cancelBubble = true : e.stopPropagation()
  1023. }
  1024. }
  1025. $("#repl_delete")[0].onclick = function () {
  1026. $("#repl_box_content")[0].innerHTML = "";
  1027. }
  1028. }
  1029. function clickLoadingExample(name) {
  1030. console.log(name)
  1031. $('#select_Example_modal').modal('close');
  1032. Ardublockly.alertExampleMessage(
  1033. '',
  1034. Ardublockly.getLocalStr('loadBlockBody'),
  1035. true, {});
  1036. readTxt("src/python/" + name, function (txt) {
  1037. if (name.split(".")[1] == "xml") {
  1038. var xmlfile = Blockly.Xml.textToDom(txt);
  1039. blockpy.components.editor.setBlocksFromXml(xmlfile);
  1040. } else {
  1041. blockpy.components.editor.codeMirror.setValue(txt);
  1042. }
  1043. saveLocalStorageBlocks("pythonai-mode-blocks-xml");
  1044. setTimeout(() => {
  1045. $('#loading').css({ 'display': 'none' });
  1046. $('#example_alert').modal('close');
  1047. }, 300)
  1048. });
  1049. }
  1050. function readTxt(url, fun) {
  1051. var xhr = new XMLHttpRequest();
  1052. xhr.open('get', url, true);
  1053. xhr.send();
  1054. xhr.onreadystatechange = function () {
  1055. if (xhr.readyState == 4 && xhr.status == 200) {
  1056. fun(xhr.responseText)
  1057. }
  1058. };
  1059. }
  1060. function serialSwich(type) {
  1061. if (type == 'Serial_Interaction') {
  1062. $('#python_box').addClass('hidden')
  1063. $('#repl_box').removeClass('hidden')
  1064. $('#help_document').addClass('hidden')
  1065. $('#serial_plotter_content').addClass('hidden')
  1066. $('#repl_delete').addClass('hidden')
  1067. document.getElementById('repl_delete').style.display = 'none';
  1068. $('#python_SourceCode').removeClass('switch_select')
  1069. $('#python_SourceCode').addClass('switch_box1')
  1070. $('#Serial_Interaction').removeClass('switch_box1')
  1071. $('#Serial_Interaction').addClass('switch_select')
  1072. $('#serial_plotter').removeClass('switch_select')
  1073. $('#serial_plotter').addClass('switch_box1')
  1074. $('#help_documents').removeClass('switch_select')
  1075. $('#help_documents').addClass('switch_box1')
  1076. } else if (type == 'python_SourceCode') {
  1077. $('#repl_box').addClass('hidden')
  1078. $('#python_box').removeClass('hidden')
  1079. $('#help_document').addClass('hidden')
  1080. $('#serial_plotter_content').addClass('hidden')
  1081. $('#repl_delete').addClass('hidden')
  1082. document.getElementById('repl_delete').style.display = 'none';
  1083. $('#Serial_Interaction').removeClass('switch_select')
  1084. $('#Serial_Interaction').addClass('switch_box1')
  1085. $('#python_SourceCode').removeClass('switch_box1')
  1086. $('#python_SourceCode').addClass('switch_select')
  1087. $('#serial_plotter').removeClass('switch_select')
  1088. $('#serial_plotter').addClass('switch_box1')
  1089. $('#help_documents').removeClass('switch_select')
  1090. $('#help_documents').addClass('switch_box1')
  1091. saveLocalStorageBlocks('pythonai-mode-blocks-xml')
  1092. setTimeout(function () {
  1093. blockpy.components.editor.updateTextFromModel();
  1094. blockpy.components.editor.updateText()
  1095. blockpy.components.editor.unhighlightLines()
  1096. var text = localStorage.getItem('pythonai-mode-blocks-xml')
  1097. var xmlfile = Blockly.Xml.textToDom(text);
  1098. blockpy.components.editor.setBlocksFromXml(xmlfile);
  1099. }, 100)
  1100. } else if (type == 'serial_plotter') {
  1101. $('#repl_box').addClass('hidden')
  1102. $('#python_box').addClass('hidden')
  1103. $('#help_document').addClass('hidden')
  1104. $('#serial_plotter_content').removeClass('hidden')
  1105. $('#help_documents').addClass('hidden')
  1106. document.getElementById('repl_delete').style.display = 'inline-block';
  1107. $('#Serial_Interaction').removeClass('switch_select')
  1108. $('#Serial_Interaction').addClass('switch_box1')
  1109. $('#python_SourceCode').removeClass('switch_select')
  1110. $('#python_SourceCode').addClass('switch_box1')
  1111. $('#serial_plotter').removeClass('switch_box1')
  1112. $('#serial_plotter').addClass('switch_select')
  1113. $('#help_documents').removeClass('switch_select')
  1114. $('#help_documents').addClass('switch_box1')
  1115. } else if (type == 'help_document') {
  1116. $('#repl_box').addClass('hidden')
  1117. $('#python_box').addClass('hidden')
  1118. $('#serial_plotter_content').addClass('hidden')
  1119. $('#help_document').removeClass('hidden')
  1120. $('#repl_delete').addClass('hidden')
  1121. document.getElementById('repl_delete').style.display = 'none';
  1122. $('#Serial_Interaction').removeClass('switch_select')
  1123. $('#Serial_Interaction').addClass('switch_box1')
  1124. $('#python_SourceCode').removeClass('switch_select')
  1125. $('#python_SourceCode').addClass('switch_box1')
  1126. $('#serial_plotter').removeClass('switch_select')
  1127. $('#serial_plotter').addClass('switch_box1')
  1128. $('#help_documents').removeClass('switch_box1')
  1129. $('#help_documents').addClass('switch_select')
  1130. }
  1131. }
  1132. function qiehuanjjj(ele, _container) {
  1133. $("body")[0].addEventListener('click', function (e) {
  1134. if (ele != e.target) {
  1135. _container.className = 'dropdown-content';
  1136. }
  1137. })
  1138. }
  1139. function likeclose(ele, _container, type, _className) {
  1140. $("body")[0].addEventListener('click', function (e) {
  1141. if (ele != e.target && e.target.parentNode != ele) {
  1142. if (type == 1) {
  1143. _container.className = _className;
  1144. } else {
  1145. _container.style.display = 'none'
  1146. }
  1147. }
  1148. })
  1149. }
  1150. function export_data(data, postfix, is_firefox) {
  1151. let url = new Blob([data], { type: 'text/plain' });
  1152. let download_link = URL.createObjectURL(url);
  1153. let a = document.createElement('a');
  1154. a.style = "display:none";
  1155. a.href = download_link;
  1156. a.download = "user_latest_code" + postfix;
  1157. if (is_firefox) {
  1158. document.body.appendChild(a);
  1159. a.click();
  1160. setTimeout(() => document.body.removeChild(a), 100);
  1161. } else
  1162. a.click();
  1163. // URL.revokeObjectURL(download_link);
  1164. // IE edge need a short delay before revoke virtual download link
  1165. setTimeout(() => URL.revokeObjectURL(download_link), 100);
  1166. }
  1167. // 积木生成
  1168. function selectmode(sel, isload) {
  1169. // var _type = 1;
  1170. // if (sel.selectedIndex == 0 && (_type != 0 || isload === true)) {
  1171. saveLocalStorageBlocks("pythonmc-mode-blocks-xml");
  1172. saveLocalStorage("type", 1);
  1173. // $("#changeRunCuploadFilesode").css("display", "inline-block");
  1174. // $("#resetMainUIBtn").css("display", "inline-block");
  1175. blockpy.setAssignment(
  1176. // settings
  1177. {},
  1178. // assignment
  1179. {
  1180. modules: {
  1181. added: ["Decisions", "Iteration", "Calculation", "Variables", "Values", "Lists", "Functions", "Logic", "Loops", "Math", "Text", "Dictionary", "Tuples", "Set", "Functionsa", "Files", "Time", "Serial Comm.", "A.I.Board", "ExtendedFunctions", "AI", "IOT", "system", "ExtendedFunction", "Third_party_Sensor"],
  1182. removed: ['MainBoard']
  1183. }
  1184. },
  1185. // programs
  1186. {
  1187. __main__: ""
  1188. }
  1189. );
  1190. loadLocalStorageBlocks("pythonai-mode-blocks-xml")
  1191. // }
  1192. }
  1193. function getQueryParams() {
  1194. try {
  1195. url = window.location.href;
  1196. query_str = url.substr(url.indexOf("?") + 1, url.length - 1);
  1197. r_params = query_str.split("&");
  1198. params = {};
  1199. for (i in r_params) {
  1200. param = r_params[i].split("=");
  1201. params[param[0]] = param[1];
  1202. }
  1203. return params;
  1204. } catch (e) {
  1205. return {};
  1206. }
  1207. }
  1208. // onresize 多次执行解决办法
  1209. var debounce = function (func, threshold, execAsap) {
  1210. var timeout;
  1211. return function debounced() {
  1212. var obj = this, args = arguments;
  1213. function delayed() {
  1214. if (!execAsap)
  1215. func.apply(obj, args);
  1216. timeout = null;
  1217. };
  1218. if (timeout)
  1219. clearTimeout(timeout);
  1220. else if (execAsap)
  1221. func.apply(obj, args);
  1222. timeout = setTimeout(delayed, threshold || 100);
  1223. };
  1224. }
  1225. // 切换数据显示方式
  1226. var myChart = "";
  1227. function switchSerial(type) {
  1228. if (type == 2) {
  1229. document.getElementById('image_transmission').style.display = 'none';
  1230. document.getElementById('repl_box_content').style.display = 'block';
  1231. // document.getElementById('repl_box_content').innerHTML = ""
  1232. document.getElementsByClassName('translatable_image_transmission')[0].classList.remove("serial-active")
  1233. document.getElementsByClassName('translatable_serial_plotter')[1].classList.add("serial-active")
  1234. } else {
  1235. document.getElementById('image_transmission').style.display = 'block';
  1236. document.getElementById('repl_box_content').style.display = 'none';
  1237. document.getElementsByClassName('translatable_image_transmission')[0].classList.add("serial-active")
  1238. document.getElementsByClassName('translatable_serial_plotter')[1].classList.remove("serial-active")
  1239. // document.getElementById('repl_box_content').innerHTML = ""
  1240. }
  1241. }
  1242. // 点击下载文件
  1243. function fileDownload(url, name) {
  1244. var nowA = document.createElement('a');
  1245. nowA.setAttribute('href', url);
  1246. nowA.setAttribute('download', name);
  1247. nowA.style.display = 'none';
  1248. document.body.appendChild(nowA);
  1249. nowA.click();
  1250. document.body.removeChild(nowA);
  1251. }
  1252. // 点击复制分享链接
  1253. function copyShare() {
  1254. $('#cloudBtn-shares').click(() => {
  1255. if (CCB.userState) {
  1256. let time = 10000
  1257. var $toastContent = $(`<span id="abc">${CCB.str_group.share_loading}</span>`)
  1258. Materialize.toast($toastContent, time, "shareUrl")
  1259. let fileNmae = new Date().getTime()
  1260. $.ajax(`${CCB.base_url}blockx/`, {
  1261. type: "POST",
  1262. xhrFields: {
  1263. withCredentials: true
  1264. },
  1265. data: {
  1266. filename: fileNmae,
  1267. xml: Ardublockly.generateXml()
  1268. },
  1269. success: (res) => {
  1270. let fileobject = {
  1271. filenameId: res.filename,
  1272. filename: fileNmae,
  1273. time: getCurrentDate(),
  1274. timestamp: (new Date()).valueOf()
  1275. };
  1276. CCB.cloudFileList.push(fileobject);
  1277. CCB.selectCloudFile = filename;
  1278. var id = U.UF.C.queryString("Qd");
  1279. var url = window.location.href + '&Qd=' + res.filename;
  1280. if (id) {
  1281. url = window.location.href.replace(/Qd=[0-9a-zA-Z_]+/g, "Qd=" + res.filename);
  1282. }
  1283. let flag = copyText(url);
  1284. // time = 3000;
  1285. // document.getElementById('abc').innerHTML = flag ? CCB.str_group.share_success : CCB.str_group.share_fail
  1286. // setTimeout(function () {
  1287. Materialize.toast(flag ? CCB.str_group.share_success : CCB.str_group.share_fail, 3000, "shareUrl")
  1288. //}, time)
  1289. },
  1290. error: () => {
  1291. $("#cloud_modal_preload").css("display", "none");
  1292. // time = 4000;
  1293. // Materialize.toast(CCB.str_group.error_uploadFile, 4000);
  1294. // document.getElementById('abc').style.display = CCB.str_group.error_uploadFile
  1295. setTimeout(function () {
  1296. Materialize.toast(CCB.str_group.error_uploadFile, 4000)
  1297. }, time)
  1298. }
  1299. });
  1300. } else {
  1301. Materialize.toast(CCB.str_group.requestLogin, 3000);
  1302. $("#login_modal").modal("open")
  1303. }
  1304. })
  1305. }
  1306. String.prototype.isEmpty = function () {
  1307. var s1 = this.replace(/[\r\n]/g, '').replace(/[ ]/g, ''),
  1308. s2 = (s1 == '') ? true : false;
  1309. return s2;
  1310. };
  1311. function isInArray(str, value) {
  1312. var arr = str.split(",");
  1313. for (var i = 0; i < arr.length; i++) {
  1314. if (value === arr[i].replace("\r", "").replace("\r", "")) {
  1315. return true;
  1316. }
  1317. }
  1318. return false;
  1319. }
  1320. function uploadSuccess(data) {
  1321. console.log(data);
  1322. }
  1323. function toHref_own(href) {
  1324. window.open(href + "&lang=" + localStorage.getItem("handPyLanguage"), "_blank");
  1325. }
  1326. function toHref(href) {
  1327. window.open(href + "/?lang=" + localStorage.getItem("handPyLanguage"), "_blank");
  1328. }
  1329. function select_Module(module) {
  1330. if (module == 'AI_module') {
  1331. $('#AI_module').addClass("moduleActive");
  1332. $('#IoT_module').removeClass("moduleActive");
  1333. }
  1334. else {
  1335. $('#IoT_module').addClass("moduleActive");
  1336. $('#AI_module').removeClass("moduleActive");
  1337. }
  1338. }
  1339. function selectModule_confirm() {
  1340. if ($("#AI_module").attr('class') == "moduleActive") {
  1341. $("#mode")[0].selectedIndex = 1;
  1342. $("#mode")[0].onchange();
  1343. $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
  1344. // document.getElementById("list").getElementsByTagName("li")[1].onclick();
  1345. $("#selectModule").modal('close');
  1346. $('#IoT_module').removeClass("moduleActive");
  1347. $('#AI_module').removeClass("moduleActive");
  1348. }
  1349. else if ($("#IoT_module").attr('class') == "moduleActive") {
  1350. $("#mode")[0].selectedIndex = 0;
  1351. $("#mode")[0].onchange();
  1352. $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.iot_module;
  1353. // document.getElementById("list").getElementsByTagName("li")[0].onclick();
  1354. $("#selectModule").modal('close');
  1355. $('#IoT_module').removeClass("moduleActive");
  1356. $('#AI_module').removeClass("moduleActive");
  1357. }
  1358. }
  1359. function mouseMove() {
  1360. // 拖拉改变右侧上下块的高度
  1361. let PC = document.getElementById('mouseMove')
  1362. let divA = document.getElementById('py-editor')
  1363. let divB = document.getElementById('mouseMove-bottom')
  1364. let midd = document.getElementById('left_move_right')
  1365. let left_midd = document.getElementById('blocks_content')
  1366. let right = document.getElementById('sss')
  1367. // $('#mouseMove').click()
  1368. // window.addEventListener('mousemove', function () {
  1369. PC.onmousedown = function (ev) {
  1370. $('#wabadb_iframe_model').removeClass('hidden')
  1371. // 鼠标按下坐标
  1372. let pX1 = ev.clientX
  1373. let pY1 = ev.clientY
  1374. // 得到两个 div 的高度
  1375. let heightA = divA.clientHeight
  1376. let heightB = divB.clientHeight
  1377. // divB.style.height = '300px'
  1378. document.onmousemove = function (ev) {
  1379. // document.onmousedown = new Function("return false");
  1380. // document.onmouseup = new Function("return true");
  1381. // 鼠标移动是坐标
  1382. let pX2 = ev.clientX
  1383. let pY2 = ev.clientY
  1384. // 计算出鼠标上下移动的距离
  1385. let Y = pY2 - pY1
  1386. if (heightB - Y > 5 && heightA + Y > 60) {
  1387. divB.style.height = heightB - Y + 'px'
  1388. divA.style.height = heightA + Y + 'px'
  1389. }
  1390. }
  1391. //清除
  1392. document.onmouseup = function (ev) {
  1393. $('#wabadb_iframe_model').addClass('hidden')
  1394. document.onmousemove = null;
  1395. document.onmouseup = null;
  1396. }
  1397. }
  1398. midd.onmousedown = function (ev) {
  1399. $('#wabadb_iframe_model').removeClass('hidden')
  1400. let pX1 = ev.clientX
  1401. let pY1 = ev.clientY
  1402. // 得到两个 div 的宽度
  1403. let widthA = left_midd.clientWidth
  1404. let widthB = right.clientWidth
  1405. // divB.style.height = '300px'
  1406. document.onmousemove = function (ev) {
  1407. // 鼠标移动是坐标
  1408. let pX2 = ev.clientX
  1409. let pY2 = ev.clientY
  1410. // 计算出鼠标左右移动的距离
  1411. let Y = pX2 - pX1
  1412. if (Number(widthB - Y) > 425 && widthA + Y > 135) {
  1413. left_midd.style.width = widthA + Y + 'px'
  1414. right.style.width = widthB - Y + 'px'
  1415. // Ardublockly.toogleToolbox()
  1416. setTimeout(function () {
  1417. Blockly.svgResize(blockpy.components.editor.blockly);
  1418. Blockly.svgResize(Blockly.mainWorkspace);
  1419. }, 100)
  1420. }
  1421. }
  1422. //清除
  1423. document.onmouseup = function (ev) {
  1424. $('#wabadb_iframe_model').addClass('hidden')
  1425. document.onmousemove = null;
  1426. document.onmouseup = null;
  1427. }
  1428. }
  1429. // })
  1430. }
  1431. var reconnect = true
  1432. document.addEventListener("visibilitychange", function () {
  1433. // console.log(document.visibilityState);
  1434. if (document.visibilityState == "hidden") {
  1435. console.log('隐藏');
  1436. reconnect = false
  1437. } else if (document.visibilityState == "visible") {
  1438. console.log('显示')
  1439. reconnect = true
  1440. }
  1441. });
  1442. let isWebadb = ''
  1443. let isDevice = ''
  1444. let isConnect = ''
  1445. var bluetoothDevice = ''
  1446. async function addWebadb() {
  1447. if (deviceType == 1) {
  1448. // $("#webadb_connect")[0].disabled = false;
  1449. if ($('#IP').val().length > 0) {
  1450. $('#wifi_process').modal('open');
  1451. console.log(`${$('#IP').val()}:5678`)
  1452. if (window.location.href.split("://")[0] === "https") {
  1453. $("#getIpLink").html(`https://${$('#IP').val()}:5678`)
  1454. } else {
  1455. $("#getIpLink").html(`http://${$('#IP').val()}:5678`)
  1456. }
  1457. } else {
  1458. alert(CCB.str_group.ipAddress)
  1459. }
  1460. // console.log(window.location.origin.indexOf("https"))
  1461. }
  1462. else if (deviceType == 2) {
  1463. bluetoothDevice = await requestDevice();
  1464. }
  1465. else {
  1466. document.getElementById("webadb_iframe").contentWindow.document.getElementById("usbadd").click();
  1467. }
  1468. }
  1469. window.addEventListener('storage', function (e) {
  1470. if (e.key === 'ctc-msg' && !!isConnect) {
  1471. console.log("断开当前页面连接")
  1472. document.getElementById("webadb_iframe").contentWindow.document.getElementById("usbdisconnect").click()
  1473. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn
  1474. }
  1475. });
  1476. let autoContent = true
  1477. function addWebadbCorsPage() {
  1478. let dat = new Date()
  1479. window.localStorage.setItem("ctc-msg", JSON.stringify(dat))
  1480. }
  1481. // webadb 连接
  1482. async function webadbConnect() {
  1483. if (deviceType == 1) {
  1484. if ($('#webadb_connect')[0].innerHTML == Ardublockly.LOCALISED_TEXT.connectBtn) {
  1485. connectWebsocket()
  1486. } else {
  1487. ws.close()
  1488. }
  1489. } else if (deviceType == 2) {
  1490. if (bledevice.gatt.connected) {
  1491. bledevice.gatt.disconnect()
  1492. } else {
  1493. bleconnect()
  1494. }
  1495. }
  1496. else {
  1497. await addWebadbCorsPage()
  1498. if (!!isConnect) {
  1499. reconnect = false
  1500. document.getElementById("webadb_iframe").contentWindow.document.getElementById("usbdisconnect").click()
  1501. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn
  1502. } else {
  1503. serialSwich('Serial_Interaction')
  1504. document.getElementById("webadb_iframe").contentWindow.document.getElementById("usbconnect").click()
  1505. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.disConnect
  1506. autoContent = true
  1507. reconnect = true
  1508. await connectTest()
  1509. }
  1510. }
  1511. }
  1512. function connectTest() {
  1513. // let fileCfgTest = `{ echo "" > /etc/wifi/fileCfgTest && echo "" > /root/fileCfgTest && echo "" > /home/fileCfgTest && echo "" > /tmp/fileCfgTest; } || { sync; fsck.ext4 -y /dev/root; (mount -o remount,rw -n /dev/root / ; mount -o remount,rw -n /dev/mmcblk0p4 / ; mount -o remount,rw -n /dev/mmcblk0p4 /mnt/UDISK ; mount -o remount,rw -n / / ; mount -o remount,rw -n /root / ; ) ; sync ; }`
  1514. setTimeout(() => {
  1515. let webadb_document = document.getElementById('webadb_iframe').contentWindow.getdevice()
  1516. webadb_document.device.subprocess.shell(Repair).then(res => {
  1517. res.stdout.reader.read().then(m => {
  1518. var str = Uint8ArrayToString(m.value);
  1519. console.log(str)
  1520. if (str.indexOf("/bin/sh") > -1 || str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
  1521. $("#webadbErro").css("display", "inline-block")
  1522. // webadb_document.device.subprocess.shell(`mount -o remount,rw /`)
  1523. }
  1524. })
  1525. })
  1526. }, 1000)
  1527. }
  1528. function systemCommand(com) {
  1529. if (deviceType == 1) {
  1530. sendWebsocket(`import os
  1531. os.system("${com}")`, 'run')
  1532. setTimeout(() => {
  1533. ws.close()
  1534. }, 200)
  1535. } else {
  1536. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(com).then(function (e) {
  1537. e.stdout.reader.read().then(function (e) {
  1538. // 重启或关机
  1539. $("#webadbErro").css("display", "none")
  1540. })
  1541. }).catch(err => {
  1542. })
  1543. }
  1544. }
  1545. function backHome() {
  1546. if (deviceType == 1) {
  1547. // ws.send(`import os
  1548. // os.system("rm /tmp/disable")`,"run")
  1549. } else if (deviceType == 2) {
  1550. blestop(function (event) {
  1551. console.log("蓝牙结束程序", event)
  1552. })
  1553. }
  1554. else {
  1555. if (isRunCodeData) {
  1556. isRunCodeData.kill().then(() => {
  1557. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`rm /tmp/disable`).then(function (e) {
  1558. isRunCodeData = e;
  1559. })
  1560. })
  1561. } else {
  1562. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`rm /tmp/disable`).then(function (e) {
  1563. isRunCodeData = e;
  1564. })
  1565. }
  1566. }
  1567. $("#backHome").addClass('disabled')
  1568. }
  1569. // 点击切换更新记录
  1570. function switchUpdate(type) {
  1571. if (type == '1') {
  1572. $('.update-old').css({ display: 'none' })
  1573. $('.update-new').css({ display: 'block' })
  1574. } else {
  1575. $('.update-old').css({ display: 'block' })
  1576. $('.update-new').css({ display: 'none' })
  1577. }
  1578. }
  1579. function Uint8ArrayToString(fileData) {
  1580. const Utf8Decoder = new TextDecoder();
  1581. return Utf8Decoder.decode(fileData);
  1582. // var dataString = "";
  1583. // for (var i = 0; i < fileData.length; i++) {
  1584. // dataString += String.fromCharCode(fileData[i]);
  1585. // }
  1586. // return dataString
  1587. }
  1588. async function fileBlobLoad(text, name, type) {
  1589. // 这么写是因为文件转换是异步任务
  1590. transToFile = async (blob, fileName, fileType) => {
  1591. return new window.File([blob], fileName, { type: fileType })
  1592. }
  1593. let outBlob = new Blob([text], { type: "text/plain;charset=utf-8" })
  1594. const data = await transToFile(outBlob, name, type);
  1595. return data
  1596. }
  1597. function uploadFilesCocoPi(file, fileOut) {
  1598. document.getElementById('webadb_iframe').contentWindow.upload(file, "/root/").then(s => {
  1599. document.getElementById('webadb_iframe').contentWindow.upload(fileOut, "/root/").then(res => {
  1600. $('.progress > .determinate').css('width', '50%');
  1601. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "50%"
  1602. clearInterval(RunInterval);
  1603. if (isRunCodeData) {
  1604. isRunCodeData.kill().then(() => {
  1605. run_user_lastet_code()
  1606. })
  1607. }
  1608. else {
  1609. run_user_lastet_code()
  1610. }
  1611. }).catch(err => {
  1612. window.file_manger_modal = true
  1613. })
  1614. }).catch(err => {
  1615. window.file_manger_modal = true
  1616. })
  1617. }
  1618. function run_user_lastet_code() {
  1619. canvasImg = $("#image_transmission_canvas")[0].getContext("2d")
  1620. canImage = new Image();
  1621. //
  1622. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`(echo '' > /root/output.log ; touch /tmp/disable) && python -u /root/out.py; `).then(function (e) {
  1623. $("#webadbErro").css("display", "none")
  1624. isRunCodeData = e;
  1625. _data = "";
  1626. _ti = "";
  1627. serverPrint(e)
  1628. RunInterval = setInterval(() => {
  1629. serverPrint(e)
  1630. }, 50);
  1631. setTimeout(function () {
  1632. $("#webadbErro").css("display", "none")
  1633. window.file_manger_modal = true
  1634. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
  1635. $('.progress > .determinate').css('width', '100%');
  1636. $("#runCode").removeClass('disabled')
  1637. $("#uploadpy").removeClass('disabled')
  1638. $("#resetDevice").removeClass('disabled')
  1639. $("#poweroff").removeClass('disabled')
  1640. window.file_manger_modal = true
  1641. }, 2000);
  1642. }).catch(err => {
  1643. window.file_manger_modal = true
  1644. })
  1645. }
  1646. var _data = "";
  1647. var _ti;
  1648. var canvasImg = "";
  1649. var canImage = "";
  1650. function serverPrint(e) {
  1651. e.stdout.reader.read().then(function (e) {
  1652. if (e.value) {
  1653. clearTimeout(_ti);
  1654. _data += Uint8ArrayToString(e.value);
  1655. _ti = setTimeout(function () {
  1656. showServal(_data)
  1657. _data = "";
  1658. }, 10)
  1659. }
  1660. }).catch(err => {
  1661. $('.progress > .determinate').css('width', 0);
  1662. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
  1663. })
  1664. if (isRunCodeData) {
  1665. if (isRunCodeData.stdout.readable._state != 'readable') {
  1666. $('#backHome').addClass('disabled')
  1667. clearInterval(RunInterval)
  1668. backHome()
  1669. }
  1670. else {
  1671. $('#backHome').removeClass('disabled')
  1672. }
  1673. }
  1674. }
  1675. function showServal(_data) {
  1676. if (_data.indexOf('data:image/jpg;base64') > -1) {
  1677. try {
  1678. canImage.src = _data;
  1679. canImage.onload = () => {
  1680. canvasImg.drawImage(canImage, 0, 0, 300, 150)
  1681. }
  1682. }
  1683. catch (e) {
  1684. }
  1685. } else {
  1686. let errMsg = ""
  1687. let errData = ""
  1688. let c = ''
  1689. if (_data.indexOf(`camera`) == -1 && _data.length < 500) {
  1690. if (_data.indexOf("/bin/sh:") > -1 || _data.indexOf("No such file or directory") > -1 || _data.indexOf("Read-only file system") > -1) {
  1691. $("#webadbErro").css("display", "inline-block")
  1692. }
  1693. let b = _data.split('\r\n')
  1694. for (let i = 0; i <= b.length - 1; i++) {
  1695. c += `<div>${b[i]}</div>`
  1696. }
  1697. $('#repl_box_content').append(c);
  1698. repl_box_contentheight = $("#repl_box_content")[0].scrollHeight;
  1699. $("#repl_box_content").scrollTop(repl_box_contentheight);
  1700. }
  1701. if (_data.indexOf(`NameError`) > -1) {
  1702. setTimeout(() => {
  1703. $("#error-btn").css("display", "block")
  1704. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1705. }, 500)
  1706. errMsg = _data.split('\r\n')
  1707. for (let i = 0; i <= errMsg.length - 1; i++) {
  1708. errData += `${errMsg[i]}\n`
  1709. }
  1710. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_pv}`)
  1711. } else if (_data.indexOf("IndentationError") > -1 || _data.indexOf("SyntaxError") > -1) {
  1712. setTimeout(() => {
  1713. $("#error-btn").css("display", "block")
  1714. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1715. }, 500)
  1716. errMsg = _data.split('\r\n')
  1717. for (let i = 0; i <= errMsg.length - 1; i++) {
  1718. errData += `${errMsg[i]}\n`
  1719. }
  1720. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_unindent}`)
  1721. } else if (_data.indexOf("IndexError") > -1) {
  1722. setTimeout(() => {
  1723. $("#error-btn").css("display", "block")
  1724. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1725. }, 500)
  1726. errMsg = _data.split('\r\n')
  1727. for (let i = 0; i <= errMsg.length - 1; i++) {
  1728. errData += `${errMsg[i]}\n`
  1729. }
  1730. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.IndexError}`)
  1731. } else if (_data.indexOf("AttributeError") > -1) {
  1732. setTimeout(() => {
  1733. $("#error-btn").css("display", "block")
  1734. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1735. }, 500)
  1736. errMsg = _data.split('\r\n')
  1737. for (let i = 0; i <= errMsg.length - 1; i++) {
  1738. errData += `${errMsg[i]}\n`
  1739. }
  1740. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.AttributeError}`)
  1741. } else if (_data.indexOf("TypeError") > -1) {
  1742. setTimeout(() => {
  1743. $("#error-btn").css("display", "block")
  1744. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1745. }, 500)
  1746. errMsg = _data.split('\r\n')
  1747. for (let i = 0; i <= errMsg.length - 1; i++) {
  1748. errData += `${errMsg[i]}\n`
  1749. }
  1750. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_unindent}`)
  1751. } else if (_data.indexOf("KeyError") > -1) {
  1752. setTimeout(() => {
  1753. $("#error-btn").css("display", "block")
  1754. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1755. }, 500)
  1756. errMsg = _data.split('\r\n')
  1757. for (let i = 0; i <= errMsg.length - 1; i++) {
  1758. errData += `${errMsg[i]}\n`
  1759. }
  1760. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.KeyError}`)
  1761. } else if (_data.indexOf("Read-only file system:") > -1) {
  1762. setTimeout(() => {
  1763. $("#error-btn").css("display", "block")
  1764. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1765. }, 500)
  1766. errMsg = _data.split('\r\n')
  1767. for (let i = 0; i <= errMsg.length - 1; i++) {
  1768. errData += `${errMsg[i]}\n`
  1769. }
  1770. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.OsError}`)
  1771. } else if (_data.indexOf("FileNotFoundError") > -1) {
  1772. setTimeout(() => {
  1773. $("#error-btn").css("display", "block")
  1774. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1775. }, 500)
  1776. errMsg = _data.split('\r\n')
  1777. for (let i = 0; i <= errMsg.length - 1; i++) {
  1778. errData += `${errMsg[i]}\n`
  1779. }
  1780. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.ENOEN}`)
  1781. } else if (_data.indexOf(`File "/tmp/event"`) > -1) {
  1782. setTimeout(() => {
  1783. $("#error-btn").css("display", "block")
  1784. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1785. }, 500)
  1786. errMsg = _data.split('\r\n')
  1787. for (let i = 0; i <= errMsg.length - 1; i++) {
  1788. errData += `${errMsg[i]}\n`
  1789. }
  1790. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_unindent}`)
  1791. }
  1792. }
  1793. }
  1794. var repl_box_contentheight = 0
  1795. function getQrCode() {
  1796. document.getElementById("codeImg").innerHTML = ""
  1797. let browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  1798. let qrCode = ""
  1799. if (browserWidth < 500) {
  1800. qrCode = new QRCode(document.getElementById("codeImg"), {
  1801. width: 150,
  1802. height: 150
  1803. })
  1804. } else {
  1805. qrCode = new QRCode(document.getElementById("codeImg"), {
  1806. width: 200,
  1807. height: 200
  1808. })
  1809. }
  1810. let SSID = $('#SSID').val()
  1811. let PASS = $('#PAS').val()
  1812. if (SSID == "" && PASS == "") {
  1813. alert(Ardublockly.LOCALISED_TEXT.SSIDPWD)
  1814. return
  1815. }
  1816. console.log(`SSID:${SSID};PASS:${PASS}`)
  1817. qrCode.makeCode(`SSID:${SSID};PASS:${PASS}`)
  1818. }
  1819. var ws = ''
  1820. var WifiContent = 'close';
  1821. let ifconfig = "wifi_get_connection_info_test 1 > /root/event.log &";
  1822. // let ifconfig = `import os
  1823. // cmd = "wifi_get_connection_info_test 1"
  1824. // res = os.popen(cmd).read()
  1825. // print("res",res)
  1826. // `
  1827. function connectWebsocket(type) {
  1828. ws = new WebSocket(`wss://${$('#IP').val()}:5678`);
  1829. WifiContent = type
  1830. ws.onopen = () => {
  1831. // console.log('连接服务端WebSocket成功');
  1832. $('#repl_box_content').append(`<div>${CCB.str_group.connection_success}</div>`);
  1833. serialSwich('serial_plotter')
  1834. $("#runCode").removeClass('disabled')
  1835. $("#uploadpy").removeClass('disabled')
  1836. $("#resetDevice").removeClass('disabled')
  1837. $("#poweroff").removeClass('disabled')
  1838. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.disConnect
  1839. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusbar
  1840. $('#cnt_icon').css('display', 'inline-block')
  1841. $('#discnt_icon').css('display', 'none')
  1842. $('#select-connected').attr("disabled", true)
  1843. setTimeout(() => {
  1844. //sendWebsocket(ifconfig,"run")
  1845. ws.send(ifconfig)
  1846. }, 1000)
  1847. };
  1848. // 监听服务端消息(接收消息)
  1849. ws.onmessage = (msg) => {
  1850. $('#repl_box_content').append(`<div>${msg.data}</div>`);
  1851. repl_box_contentheight = $("#repl_box_content")[0].scrollHeight;
  1852. $("#repl_box_content").scrollTop(repl_box_contentheight);
  1853. };
  1854. // 监听连接失败
  1855. ws.onerror = () => {
  1856. // console.log('连接失败,正在重连...');
  1857. $('.progress > .determinate').css('width', '0');
  1858. $('#repl_box_content').append(`<div>${CCB.str_group.connection}</div>`);
  1859. // connectWebsocket();
  1860. };
  1861. // 监听连接关闭
  1862. ws.onclose = () => {
  1863. $('#repl_box_content').append(`<div>${CCB.str_group.disconnect}</div>`);
  1864. // console.log('连接关闭');
  1865. $('#cnt_icon').css('display', 'none')
  1866. $('#discnt_icon').css('display', 'inline-block')
  1867. $('#select-connected').attr("disabled", false)
  1868. setTimeout(() => {
  1869. $("#webadb_connect")[0].disabled = false;
  1870. $("#webadb_add")[0].disabled = false;
  1871. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusNotConn
  1872. $("#runCode").addClass('disabled')
  1873. $("#uploadpy").addClass('disabled')
  1874. $("#resetDevice").addClass('disabled')
  1875. $("#backHome").addClass('disabled')
  1876. $("#poweroff").addClass('disabled')
  1877. $('#message_file').css({ display: 'none' })
  1878. $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
  1879. $('.progress > .determinate').css('width', 0);
  1880. $("status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
  1881. }, 500)
  1882. };
  1883. };
  1884. function sendWebsocket(file, type) {
  1885. canvasImg = $("#image_transmission_canvas")[0].getContext("2d")
  1886. canImage = new Image()
  1887. // console.log(file)
  1888. // ws.send('ls')
  1889. // ws.send(`echo '${file}' > user_latest_code.py && ln -sf /root/user_latest_code.py /tmp/event && touch /tmp/disable && python /tmp/event`)
  1890. if (type == "run") {
  1891. ws.send(`echo '${file}' > /root/user_latest_code.py && ln -sf /root/user_latest_code.py /tmp/event && touch /tmp/disable && python -u /tmp/event > /root/event.log`)
  1892. } else {
  1893. ws.send(`echo '${file}' > /root/user_latest_code.py`)
  1894. }
  1895. ws.onmessage = (msg) => {
  1896. if (msg.data.indexOf('data:image/jpg;base64') > -1) {
  1897. try {
  1898. canImage.src = msg.data;
  1899. canImage.onload = () => {
  1900. canvasImg.drawImage(canImage, 0, 0, 300, 150)
  1901. }
  1902. }
  1903. catch (e) {
  1904. }
  1905. } else {
  1906. if (_data.indexOf(`NameError`) > -1) {
  1907. setTimeout(() => {
  1908. $("#error-btn").css("display", "block")
  1909. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1910. }, 500)
  1911. let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
  1912. $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_pv}`)
  1913. } else if (_data.indexOf("IndentationError") > -1 || _data.indexOf("SyntaxError") > -1) {
  1914. setTimeout(() => {
  1915. $("#error-btn").css("display", "block")
  1916. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1917. }, 500)
  1918. let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
  1919. $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_unindent}`)
  1920. } else if (_data.indexOf("IndexError") > -1) {
  1921. setTimeout(() => {
  1922. $("#error-btn").css("display", "block")
  1923. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1924. }, 500)
  1925. let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
  1926. $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.IndexError}`)
  1927. } else if (_data.indexOf("AttributeError") > -1) {
  1928. setTimeout(() => {
  1929. $("#error-btn").css("display", "block")
  1930. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1931. }, 500)
  1932. let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
  1933. $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.AttributeError}`)
  1934. } else if (_data.indexOf("TypeError") > -1) {
  1935. setTimeout(() => {
  1936. $("#error-btn").css("display", "block")
  1937. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1938. }, 500)
  1939. let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
  1940. $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${errMsg[1]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.TypeError}`)
  1941. } else if (_data.indexOf("KeyError") > -1) {
  1942. setTimeout(() => {
  1943. $("#error-btn").css("display", "block")
  1944. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1945. }, 500)
  1946. let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
  1947. $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.KeyError}`)
  1948. } else if (_data.indexOf("Read-only file system:") > -1) {
  1949. setTimeout(() => {
  1950. $("#error-btn").css("display", "block")
  1951. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1952. }, 500)
  1953. errMsg = _data.split('\r\n')
  1954. for (let i = 0; i <= errMsg.length - 1; i++) {
  1955. errData += `${errMsg[i]}\n`
  1956. }
  1957. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.OsError}`)
  1958. } else if (_data.indexOf("FileNotFoundError") > -1) {
  1959. setTimeout(() => {
  1960. $("#error-btn").css("display", "block")
  1961. $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
  1962. }, 500)
  1963. errMsg = _data.split('\r\n')
  1964. for (let i = 0; i <= errMsg.length - 1; i++) {
  1965. errData += `${errMsg[i]}\n`
  1966. }
  1967. $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.ENOEN}`)
  1968. }
  1969. // modName ,tag,branch,commit,author
  1970. let a = msg.data.indexOf("DEBUG") > -1 || msg.data.indexOf("debug") > -1 || msg.data.indexOf("modName") > -1 || msg.data.indexOf("tag") > -1 || msg.data.indexOf("branch") > -1 || msg.data.indexOf("commit") > -1 || msg.data.indexOf("author") > -1
  1971. if (!a) {
  1972. $('#repl_box_content').append(`<div>${msg.data}</div>`);
  1973. repl_box_contentheight = $("#repl_box_content")[0].scrollHeight;
  1974. $("#repl_box_content").scrollTop(repl_box_contentheight);
  1975. }
  1976. // $('.progress > .determinate').css('width', '100%');
  1977. }
  1978. // $("#backHome").removeClass('disabled')
  1979. $('.progress > .determinate').css('width', '100%');
  1980. };
  1981. // setTimeout(function () {
  1982. $('.progress > .determinate').css('width', '100%');
  1983. $("#runCode").removeClass('disabled')
  1984. $("#uploadpy").removeClass('disabled')
  1985. $("#resetDevice").removeClass('disabled')
  1986. $("#poweroff").removeClass('disabled')
  1987. // }, 2000);
  1988. }
  1989. function mobileSwitchMode(type) {
  1990. if (type == 'python') {
  1991. $('.mobileSwitch')[0].style.display = "block"
  1992. $('.mobileSwitch')[1].style.display = "none"
  1993. $('#blocks_content')[0].style.display = "block"
  1994. $('#py-editor')[0].style.display = "none"
  1995. $('#sss')[0].style.height = 'fit-content'
  1996. } else {
  1997. $('.mobileSwitch')[1].style.display = "block"
  1998. $('.mobileSwitch')[0].style.display = "none"
  1999. $('#blocks_content')[0].style.display = "none"
  2000. $('#py-editor')[0].style.display = "block"
  2001. $('#sss')[0].style.height = '100%'
  2002. }
  2003. setTimeout(function () {
  2004. blockpy.components.editor.updateTextFromModel();
  2005. blockpy.components.editor.updateText()
  2006. blockpy.components.editor.unhighlightLines()
  2007. var text = localStorage.getItem('pythonai-mode-blocks-xml')
  2008. var xmlfile = Blockly.Xml.textToDom(text);
  2009. blockpy.components.editor.setBlocksFromXml(xmlfile);
  2010. }, 100)
  2011. }
  2012. function linkOkay() {
  2013. $("#webadb_connect")[0].disabled = false;
  2014. console.log(`https://${$('#IP').val()}:5678`)
  2015. if (window.location.href.split("://")[0] === "https") {
  2016. window.open(`https://${$('#IP').val()}:5678`, '_blank');
  2017. } else {
  2018. window.open(`http://${$('#IP').val()}:5678`, '_blank');
  2019. }
  2020. $('#wifi_process').modal('close');
  2021. }
  2022. // 跨网页复制
  2023. document.addEventListener("paste", function (event) {
  2024. if ((event.clipboardData || event.originalEvent)) {
  2025. var clipboardData = (event.clipboardData || window.clipboardData);
  2026. var val = clipboardData.getData('text');
  2027. // console.log(Blockly.Xml.workspaceToDom(blockpy.components.editor.blockly))
  2028. // let a = val.substr(0,7)+val.substr(44,val.length)
  2029. let c = Blockly.Xml.textToDom(val)
  2030. Blockly.clipboardSource_ = blockpy.components.editor.blockly
  2031. Blockly.clipboardSource_.paste(c)
  2032. // event.preventDefault();
  2033. }
  2034. });
  2035. function loadingXml(result_xml) {
  2036. var success = Ardublockly.replaceBlocksfromXml(result_xml);
  2037. if (!success) {
  2038. Ardublockly.alertMessage(Ardublockly.getLocalStr('ErrorBlockTitle'), Ardublockly.getLocalStr('ErrorBlockBody'), false);
  2039. }
  2040. }
  2041. function getLoadXmlStr() {
  2042. var xml = Blockly.Xml.workspaceToDom(blockpy.components.editor.blockly);
  2043. var XmlStr = Blockly.Xml.domToText(xml);
  2044. return XmlStr
  2045. }
  2046. // 一键更新固件
  2047. async function OneClickUpgrade() {
  2048. let text = `import os
  2049. os.system("cd root/user && mkdir model && chmod 777 *")
  2050. os.system("cd /")
  2051. os.system("rm /etc/banner")
  2052. os.system("mv /root/banner /etc/")
  2053. os.system("sync && reboot")
  2054. `
  2055. let strText = `import os
  2056. import sys
  2057. import traceback
  2058. import logging
  2059. logger = logging.getLogger()
  2060. logger.setLevel(logging.INFO)
  2061. file_handler = logging.FileHandler('/root/output.log')
  2062. file_handler.setLevel(logging.INFO)
  2063. formatter = logging.Formatter('%(message)s')
  2064. file_handler.setFormatter(formatter)
  2065. logger.addHandler(file_handler)
  2066. def log_output(*args, **kwargs):
  2067. output = ' '.join(map(str, args))
  2068. logger.info(output.strip(), **kwargs)
  2069. sys.stderr.write = sys.stdout.write = log_output
  2070. os.close(1)
  2071. os.close(2)
  2072. try:
  2073. source_code = r'''${text}
  2074. '''
  2075. exec(source_code)
  2076. except Exception as e:
  2077. error_info = traceback.format_exc()
  2078. print(error_info)
  2079. `;
  2080. //let textContain =
  2081. // console.log(strText)
  2082. let file = await fileBlobLoad(strText, "event", "text/plain")
  2083. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`echo "" > /root/fileCfgTest`).then(r => {
  2084. setTimeout(function () {
  2085. window.file_manger_modal = true
  2086. r.stdout.reader.read().then(m => {
  2087. var str = Uint8ArrayToString(m.value);
  2088. if (str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
  2089. //错误处理
  2090. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`mount -o remount -rw /dev/mmcblk0p4`).then(r => {
  2091. uploadFilesCocoPi(file, "")
  2092. }).catch(err => {
  2093. $('.progress > .determinate').css('width', 0);
  2094. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
  2095. })
  2096. }
  2097. else {
  2098. // 没有错误处理
  2099. uploadFilesCocoPi(file, "")
  2100. }
  2101. }).catch(n => {
  2102. console.log(n)
  2103. })
  2104. }, 100)
  2105. }).catch(err => {
  2106. console.log(err)
  2107. })
  2108. }
  2109. // 一键更新CocoPi文件
  2110. async function CocoPiUpgrades() {
  2111. // const appLangJsLoad = document.createElement('script');
  2112. const request = createAjaxRequest();
  2113. const appLangJdPath = `CocoPi.js`;
  2114. try {
  2115. request.open('GET', appLangJdPath, false);
  2116. request.send('');
  2117. let file = await fileBlobLoad(request.responseText, "CocoPi.py", "text/plain")
  2118. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`echo "" > /etc/wifi/fileCfgTest && echo "" > /root/fileCfgTest && echo "" > /home/fileCfgTest && echo "" > /tmp/fileCfgTest`).then(r => {
  2119. setTimeout(function () {
  2120. window.file_manger_modal = true
  2121. r.stdout.reader.read().then(m => {
  2122. var str = Uint8ArrayToString(m.value);
  2123. if (str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
  2124. //错误处理
  2125. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`mount -o remount -rw /dev/mmcblk0p4`).then(r => {
  2126. uploadFilesCocoPi("", file)
  2127. }).catch(err => {
  2128. $('.progress > .determinate').css('width', 0);
  2129. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
  2130. })
  2131. }
  2132. else {
  2133. // 没有错误处理
  2134. uploadFilesCocoPi("", file)
  2135. }
  2136. }).catch(n => {
  2137. console.log(n)
  2138. })
  2139. }, 100)
  2140. }).catch(err => {
  2141. console.log(err)
  2142. })
  2143. // appLangJsLoad.text = request.responseText;
  2144. } catch (e) {
  2145. // But still asynchronous lazy load so at least some text gets translated
  2146. // appLangJsLoad.src = appLangJdPath;
  2147. }
  2148. }
  2149. const decounce = function (fn, delay) {
  2150. let timer = null
  2151. return function () {
  2152. const context = this
  2153. let args = arguments
  2154. clearTimeout(timer) // 每次调用debounce函数都会将前一次的timer清空,确保只执行一次
  2155. timer = setTimeout(() => {
  2156. fn.apply(context, args)
  2157. }, delay)
  2158. }
  2159. }
  2160. function uploadpyCocoPi() {
  2161. $('.progress > .determinate').css('width', 0);
  2162. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution
  2163. setTimeout(async () => {
  2164. window.file_manger_modal = false
  2165. $("#runCode").addClass('disabled')
  2166. $("#uploadpy").addClass('disabled')
  2167. $("#resetDevice").addClass('disabled')
  2168. $("#poweroff").addClass('disabled')
  2169. $("#backHome").addClass('disabled')
  2170. // 上传
  2171. let text = pythonnewcode || Blockly.Python.workspaceToCode(blockpy.components.editor.blockly) || blockpy.components.editor.codeMirror.getValue()
  2172. // 开始上传
  2173. let textContain = fileBlobLoad(text, "user_latest_code.py", "text/plain")
  2174. if (deviceType == 1) {
  2175. sendWebsocket(text, 'upload')
  2176. } else if (deviceType == 2) {
  2177. $('.progress > .determinate').css('width', '50%');
  2178. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "50%"
  2179. bluetoothUpload(text, true)
  2180. }
  2181. else {
  2182. // 转换完成后可以将file对象传给接口
  2183. textContain.then((res) => {
  2184. let file = res;
  2185. // window.stateapi.upload(file,"/root/")
  2186. $('.progress > .determinate').css('width', '50%');
  2187. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "50%"
  2188. setTimeout(() => {
  2189. if (file) {
  2190. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(Repair).then(r => {
  2191. setTimeout(function () {
  2192. r.stdout.reader.read().then(m => {
  2193. var str = Uint8ArrayToString(m.value);
  2194. if (str.indexOf("/bin/sh:") > -1 || str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
  2195. $("#webadbErro").css("display", "inline-block")
  2196. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`rm /root/user_latest_code.py`).then(s => {
  2197. //错误处理
  2198. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(Repair1).then(r => {
  2199. $("#webadbErro").css("display", "none")
  2200. document.getElementById('webadb_iframe').contentWindow.upload(file, "/root/").then(s => {
  2201. $('.progress > .determinate').css('width', '100%');
  2202. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
  2203. })
  2204. }).catch(err => {
  2205. $('.progress > .determinate').css('width', 0);
  2206. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
  2207. })
  2208. })
  2209. }
  2210. else {
  2211. $("#webadbErro").css("display", "none")
  2212. // 没有错误处理
  2213. document.getElementById('webadb_iframe').contentWindow.upload(file, "/root/").then(s => {
  2214. $('.progress > .determinate').css('width', '100%');
  2215. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
  2216. })
  2217. }
  2218. }).catch(n => {
  2219. console.log(n)
  2220. })
  2221. }, 100)
  2222. }).catch(err => {
  2223. console.log(err)
  2224. })
  2225. } else {
  2226. $('.progress > .determinate').css('width', 0);
  2227. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
  2228. }
  2229. window.file_manger_modal = true
  2230. $("#runCode").removeClass('disabled')
  2231. $("#uploadpy").removeClass('disabled')
  2232. $("#resetDevice").removeClass('disabled')
  2233. $("#poweroff").removeClass('disabled')
  2234. }, 500)
  2235. })
  2236. }
  2237. }, 1000)
  2238. }
  2239. var Repair = `{ echo "" > /etc/wifi/fileCfgTest && echo "" > /root/fileCfgTest && echo "" > /home/fileCfgTest && echo "" > /tmp/fileCfgTest; } || { sync; fsck.ext4 -y /dev/root; fsck.ext4 -y /dev/mmcblk0p4; (mount -o remount,rw -n /dev/root / ; mount -o remount,rw -n /dev/mmcblk0p4 / ; mount -o remount,rw -n /dev/mmcblk0p4 /mnt/UDISK ; mount -o remount,rw -n / / ; mount -o remount,rw -n /root / ; ) ; fsck.ext4 -y /dev/root; fsck.ext4 -y /dev/mmcblk0p4; sync ; } ; { wpa_supplicant -i wlan0 -D nl80211 -c /etc/wifi/wpa_supplicant.conf -O /etc/wifi/sockets -B || (echo "" > /etc/wifi/wpa_supplicant.conf ; wpa_supplicant -i wlan0 -D nl80211 -c /etc/wifi/wpa_supplicant.conf -O /etc/wifi/sockets -B) ; } ; `
  2240. var Repair1 = Repair;
  2241. //`mount -o remount -rw /dev/mmcblk0p4 && fsck.ext4 -p /dev/root && mount -o remount -o rw /dev/root && mount -o remount,rw -n / && mount -o remount,rw -n /home && mount -o remount,rw -n /root && sleep 1;`
  2242. async function runCocoPi() {
  2243. let text = pythonnewcode || Blockly.Python.workspaceToCode(blockpy.components.editor.blockly) || blockpy.components.editor.codeMirror.getValue() || ""
  2244. if (text == "\n") {
  2245. return true
  2246. }
  2247. text = `import time
  2248. from maix import *
  2249. import gc
  2250. import os
  2251. import sys
  2252. sys.path.append('/root/')
  2253. from CocoPi import BUTTON
  2254. from CocoPi import stm8s
  2255. from CocoPi import multiFuncGpio
  2256. from CocoPi import singleRgb
  2257. from CocoPi import LED
  2258. gc.enable()
  2259. gc.collect()
  2260. iic_slaver=stm8s()
  2261. iic_slaver.clear()
  2262. PIXEL_LED1= multiFuncGpio(0,0)
  2263. PIXEL_LED2= multiFuncGpio(1,0)
  2264. PIXEL_LED1.pixelInit_()
  2265. PIXEL_LED2.pixelInit_()
  2266. time.sleep(0.1)
  2267. L1=singleRgb()
  2268. L1.setColor(0,0,0)
  2269. L1.show()
  2270. time.sleep(0.2)
  2271. L2=LED()
  2272. L2.out(0)
  2273. del iic_slaver
  2274. del PIXEL_LED1
  2275. del PIXEL_LED2
  2276. del L1
  2277. del L2
  2278. ${text}`
  2279. window.file_manger_modal = false
  2280. autoContent = false
  2281. $("#runCode").addClass('disabled')
  2282. $("#uploadpy").addClass('disabled')
  2283. $("#resetDevice").addClass('disabled')
  2284. $("#poweroff").addClass('disabled')
  2285. $("#backHome").addClass('disabled')
  2286. $('.progress > .determinate').css('width', 0);
  2287. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution
  2288. $("#error-btn").css("display", "none")
  2289. let strText = `import traceback
  2290. import logging
  2291. import sys
  2292. import os
  2293. import time
  2294. logger = logging.getLogger()
  2295. logger.setLevel(logging.INFO)
  2296. file_handler = logging.FileHandler('/root/output.log')
  2297. file_handler.setLevel(logging.INFO)
  2298. formatter = logging.Formatter('%(message)s')
  2299. file_handler.setFormatter(formatter)
  2300. logger.addHandler(file_handler)
  2301. def log_output(*args, **kwargs):
  2302. output = ' '.join(map(str, args))
  2303. logger.info(output.strip(), **kwargs)
  2304. sys.stderr.write = sys.stdout.write = log_output
  2305. os.close(1)
  2306. os.close(2)
  2307. try:
  2308. source_code = r'''${text}
  2309. '''
  2310. exec(source_code)
  2311. except Exception as e:
  2312. error_info = traceback.format_exc()
  2313. print(error_info)
  2314. `;
  2315. //let textContain =
  2316. // console.log(strText)
  2317. let file = await fileBlobLoad(strText, "event", "text/plain")
  2318. let out = `import asyncio
  2319. import subprocess
  2320. import linecache
  2321. async def tailf(filename):
  2322. command = "python -u /root/event"
  2323. process = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
  2324. print("")
  2325. while True:
  2326. await asyncio.sleep(0.03)
  2327. try:
  2328. linecache.clearcache()
  2329. logarr = linecache.getlines(filename)[-20:]
  2330. if len(logarr) == 0:
  2331. if process.poll() is None:
  2332. continue
  2333. else:
  2334. return
  2335. open(filename, 'w').close()
  2336. print("".join(logarr).strip())
  2337. except asyncio.TimeoutError:
  2338. pass
  2339. filename = "/root/output.log"
  2340. loop = asyncio.get_event_loop()
  2341. loop.run_until_complete(tailf(filename))
  2342. loop.close()
  2343. `
  2344. let fileOut = await fileBlobLoad(out, "out.py", "text/plain")
  2345. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution
  2346. if (deviceType == 1) {
  2347. // 无线连接
  2348. sendWebsocket(text, 'run')
  2349. $('.progress > .determinate').css('width', '50%');
  2350. // $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "50%"
  2351. } else if (deviceType == 2) {
  2352. $('.progress > .determinate').css('width', '20%');
  2353. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "20%"
  2354. bluetoothUpload(text, false)
  2355. }
  2356. else {
  2357. document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(Repair).then(r => {
  2358. setTimeout(function () {
  2359. r.stdout.reader.read().then(m => {
  2360. var str = Uint8ArrayToString(m.value);
  2361. //
  2362. if (str.indexOf("/bin/sh:") > -1 || str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
  2363. // uploadFilesCocoPi(file, fileOut)
  2364. $("#webadbErro").css("display", "inline-block")
  2365. // $('.progress > .determinate').css('width', 0);
  2366. // $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
  2367. // window.file_manger_modal = true
  2368. uploadFilesCocoPi(file, fileOut)
  2369. //错误处理
  2370. // document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(Repair1).then(r => {
  2371. // $("#webadbErro").css("display", "none")
  2372. // uploadFilesCocoPi(file, fileOut)
  2373. // }).catch(err => {
  2374. // })
  2375. }
  2376. else {
  2377. // 没有错误处理
  2378. $("#webadbErro").css("display", "none")
  2379. uploadFilesCocoPi(file, fileOut)
  2380. }
  2381. }).catch(n => {
  2382. console.log(n)
  2383. window.file_manger_modal = true
  2384. })
  2385. }, 100)
  2386. }).catch(err => {
  2387. console.log(err)
  2388. window.file_manger_modal = true
  2389. })
  2390. }
  2391. }
  2392. // bledevice.gatt.connected 连接状态
  2393. // bledevice.gatt.disconnect() 断开连接
  2394. // device.gatt.connect() 蓝牙连接
  2395. // 蓝牙上传
  2396. function bluetoothUpload(text, UploadOrRun) {
  2397. let value = 0
  2398. bleuploadfile("/root/user_latest_code.py", text, function (event) {
  2399. if (event == true) {
  2400. console.log("上传成功", event)
  2401. value++
  2402. if (UploadOrRun && value == 1) {
  2403. $('.progress > .determinate').css('width', '75%');
  2404. setTimeout(() => {
  2405. $('.progress > .determinate').css('width', '100%');
  2406. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
  2407. }, 500);
  2408. } else if (value == 1) {
  2409. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "50%"
  2410. $('.progress > .determinate').css('width', '50%');
  2411. setTimeout(() => {
  2412. bluetoothRun()
  2413. }, 1000)
  2414. }
  2415. }
  2416. })
  2417. }
  2418. let repl_box_content_str = ''
  2419. // 蓝牙运行
  2420. function bluetoothRun() {
  2421. blerun('/root/user_latest_code.py', function (rechex, isrun) {
  2422. //const rechex = new TextDecoder().decode(event.target.value.buffer);
  2423. let a = `<div>${rechex}</div>`
  2424. $('#repl_box_content').append(a);
  2425. repl_box_contentheight = $("#repl_box_content")[0].scrollHeight;
  2426. $("#repl_box_content").scrollTop(repl_box_contentheight);
  2427. console.log(rechex, "蓝牙运行", isrun)
  2428. if (isrun) {
  2429. $("#backHome").addClass('disabled')
  2430. } else {
  2431. $("#backHome").removeClass('disabled')
  2432. }
  2433. setTimeout(() => {
  2434. $('.progress > .determinate').css('width', '100%');
  2435. $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully
  2436. }, 300);
  2437. })
  2438. }
  2439. var getBlocksByTypeName = function (typeName) {
  2440. var blocks = blockpy.components.editor.getBlocksFromXml().getElementsByTagName("block"); // 获取工作区中的所有块
  2441. var filteredBlocks = [];
  2442. // 遍历所有块,筛选出具有指定类型的块
  2443. for (var i = 0; i < blocks.length; i++) {
  2444. if (blocks[i].getAttribute("type") === typeName) {
  2445. filteredBlocks.push(blocks[i]);
  2446. }
  2447. }
  2448. return filteredBlocks;
  2449. };
  2450. /*import os
  2451. os.system("cd root/user && mkdir model && chmod 777 *")
  2452. os.system("cd /")
  2453. os.system("rm /etc/banner")
  2454. os.system("mv /root/banner /etc/")
  2455. os.system("sync && reboot")
  2456. from evdev import InputDevice, categorize, ecodes
  2457. # 获取键盘设备
  2458. keyboard = InputDevice('/dev/input/eventX') # 替换成实际的键盘设备路径
  2459. # 获取鼠标设备
  2460. mouse = InputDevice('/dev/input/eventY') # 替换成实际的鼠标设备路径
  2461. # 读取事件
  2462. for event in keyboard.read_loop():
  2463. if event.type == ecodes.EV_KEY:
  2464. key_event = categorize(event)
  2465. if key_event.keystate == key_event.key_down:
  2466. print(f"Key pressed: {key_event.keycode}")
  2467. for event in mouse.read_loop():
  2468. if event.type == ecodes.EV_KEY:
  2469. print(f"Mouse button pressed: {event.code}")
  2470. elif event.type == ecodes.EV_REL:
  2471. if event.code == ecodes.REL_X:
  2472. print(f"Mouse X movement: {event.value}")
  2473. elif event.code == ecodes.REL_Y:
  2474. print(f"Mouse Y movement: {event.value}")
  2475. */