index.js 111 KB

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