index.js 130 KB

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