index.js 110 KB

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