12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717 |
- function initLanguage(langKey) {
- let defaultLang = 'en';
- let lang = langKey || defaultLang;
- if (defaultLang !== lang) {
- injectLanguageJsSources(lang);
- //updateLanguageText();
- }
- }
- // logout
- $("#modal_logout_btn").on("click", function () {
- // logout();
- });
- document.domain = "cocorobo.cn";
- function logout() {
- $.ajax(`${CCB.base_url}api/logout`, {
- type: "GET",
- xhrFields: {
- withCredentials: true
- },
- success: () => {
- // $('#login_iframe').attr('src', '//staging.cocorobo.hk/login/');
- appendIframe("TM_login");
- $('#TM_login').children().css("height", "820px");
- appendIframe("TM_login_Model_download_modal");
- $('#TM_login_Model_download_modal').children().css("height", "820px");
- $('#TM_login_Model_download_modal').children().css("margin-top", "-225px");
- appendIframe("TM_login_object");
- $('#TM_login_object').children().css("height", "820px");
- appendIframe("TM_login_posenet");
- $('#TM_login_posenet').children().css("height", "820px");
- appendIframe("TM_posenet_login");
- $('#TM_posenet_login').children().css("height", "820px");
- appendIframe("before_login");
- appendIframe("cloud_askLogin");
- appendIframe("TM_login_webcam_capture_modal");
- $('#TM_login_webcam_capture_modal').children().css("width", "820px");
- $('#TM_login_webcam_capture_modal').children().css("height", "820px");
- appendIframe("TM_login_gesture_recog_modal");
- $('#TM_login_gesture_recog_modal').children().css("width", "820px");
- $('#TM_login_gesture_recog_modal').children().css("height", "820px");
- appendIframe("TM_login_voice_input_modal");
- $('#TM_login_voice_input_modal').children().css("width", "820px");
- $('#TM_login_voice_input_modal').children().css("height", "820px");
- appendIframe("TM_center_game");
- $('#TM_center_game').children().css("margin-top", "-300px");
- $('#TM_center_game').children().css("height", "820px");
- Materialize.toast(CCB.str_group.success_userLogout, 4000);
- CCB.userState = false;
- $("#cloud_fileListArea").html("");
- loginModalStatus();
- $("#modal_logout_btn").addClass('blue')
- $(".svgImg").css('display', 'none');
- $(".translate-signout").css('opacity', '1')
- }
- });
- }
- // 点击语言下拉隐藏
- // document.onclick = function () {
- // $('#languages').removeClass('active');
- // $('#languages').css({ display: 'none' })
- // }
- // 点击切换语言
- // $('#nav_language').click(function (e) {
- // $('#languages').addClass('active');
- // $('#languages').css({ display: 'block', opacity: 1, position: 'absolute',top:'64px' })
- // var ev = e || window.event;
- // if (ev.stopPropagation) { //阻止冒泡,否则会触发点击空白区域的事件
- // ev.stopPropagation();
- // } else if (window.event) {
- // window.event.cancelBubble = true; //兼容IE
- // }
- // })
- function getUrlLanguage() {
- const val = location.search.match(new RegExp('[?&]lang=([^&]+)'));
- let language = val ? decodeURIComponent(val[1].replace(/\+/g, '%20')) : '';
- if (['en', 'zh-hant', 'zh-hans'].indexOf(language) < 0) return 'zh-hant';
- return language;
- };
- function injectLanguageJsSources(langKey) {
- const head = document.getElementsByTagName('head')[0];
- // Retrieve and inject Ardublockly translations synchronously
- const appLangJsLoad = document.createElement('script');
- const request = createAjaxRequest();
- const appLangJdPath = `msg/${langKey}.js`;
- try {
- request.open('GET', appLangJdPath, false);
- request.send('');
- appLangJsLoad.text = request.responseText;
- } catch (e) {
- // But still asynchronous lazy load so at least some text gets translated
- appLangJsLoad.src = appLangJdPath;
- }
- head.appendChild(appLangJsLoad);
- // Retrieve and inject Blockly translations asynchronously
- const blocklyLangJsLoad = document.createElement('script');
- blocklyLangJsLoad.src = `blockly/msg/js/${langKey}.js`;
- head.appendChild(blocklyLangJsLoad);
- };
- function createAjaxRequest() {
- let request = false;
- try {
- // Firefox, Chrome, IE7+, Opera, Safari
- request = new XMLHttpRequest();
- } catch (e) {
- // IE6 and earlier
- try {
- request = new ActiveXObject('Msxml2.XMLHTTP');
- } catch (e) {
- try {
- request = new ActiveXObject('Microsoft.XMLHTTP');
- } catch (e) {
- throw 'Your browser does not support AJAX. You will not be able to' +
- 'use all of Ardublockly features.';
- request = null;
- }
- }
- }
- return request;
- };
- function updateLanguageText() {
- for (let textId in LOCALISED_TEXT) {
- const textStrings = document.getElementsByClassName(`translate-${textId}`);
- for (let i = 0; i < textStrings.length; i++) {
- textStrings[i].innerHTML = LOCALISED_TEXT[textId];
- }
- }
- };
- function clearBlocks(cb = () => { }) {
- const length = Blockly.mainWorkspace.getAllBlocks(true).length;
- if (length < 2) {
- Blockly.mainWorkspace.clear();
- cb();
- } else {
- Blockly.confirm(
- Blockly.Msg.DELETE_ALL_BLOCKS.replace("%1", length),
- ok => {
- if (!ok) return;
- Blockly.mainWorkspace.clear();
- cb();
- }
- );
- }
- }
- function addLibButton(lang) {
- // const addLib = document.createElement("button");
- // addLib.className = "waves-effect waves-light btn blue";
- // let content = lang === 'zh-hans' ? "添加库" : lang === 'zh-hant' ? "添加庫" : "Add Library";
- // addLib.textContent = content;
- // addLib.style = `
- // position: absolute;
- // width: 88%;
- // bottom: 10px;
- // left: 50%;
- // transform: translateX(-50%);
- // `;
- // $(addLib).click(e =>
- // blockpy.components.dialog.show("Add Library", document.createElement("div")));
- // $(".blocklyToolboxDiv").append(addLib);
- }
- // /**
- // * Save blocks into local storage. Note that MSIE 11 does not support
- // * LocalStorage on file:// URLs.
- // */
- // function saveLocalStorageBlocks() {
- // if (window.sessionStorage) {
- // var xml = blockpy.components.editor.getBlocksFromXml();
- // var text = Blockly.Xml.domToText(xml);
- // localStorage.setItem("blocks", text);
- // }
- // // blockpy.components.editor.getBlocksFromXml()
- // };
- // /** Load blocks saved on loacl storage and deletes them from storage. */
- // function loadLocalStorageBlocks() {
- // // try {
- // // var loadOnce = window.localStorage.loadOnceBlocks;
- // // } catch (e) {
- // // // Firefox sometimes throws a SecurityError when accessing sessionStorage.
- // // // Restarting Firefox fixes this, so it looks like a bug.
- // // var loadOnce = null;
- // // }
- // var loadBlocks = localStorage.getItem("blocks");
- // if (loadBlocks) {
- // var xml = Blockly.Xml.textToDom(loadBlocks);
- // blockpy.components.editor.setBlocksFromXml(xml);
- // localStorage.removeItem('blocks')
- // }
- // };
- var copyCodeClipboard;
- window.onbeforeunload = window.onunload = function () {
- if ($("#mode")[0].selectedIndex == 0) {
- saveLocalStorage("type", 1);
- saveLocalStorageBlocks("pythonai-mode-blocks-xml");
- } else {
- saveLocalStorage("type", 1);
- saveLocalStorageBlocks("pythonai-mode-blocks-xml");
- }
- }
- function getJsonData(filepath) {
- return new Promise(resolve => {
- $.getJSON(filepath, data => resolve(data));
- });
- }
- var isRunCodeData = '';
- var RunInterval = '';
- window.onload = async function () {
- $("#copyright_middle")[0].innerText = new Date().getFullYear()
- var url = window.location.hash.substring(1);
- // if (url) {
- // document.getElementById('ipAddress').value = 'ws://' + url;
- // }
- $('.dropdown-trigger').dropdown();
- setTimeout(() => $('.modal').modal(), 0);
- blockpy = new BlockPy({
- blocklyPath: "blockly/",
- attachmentPoint: document.getElementById("blockpy-div"),
- instructor:
- !getQueryParams()["instructor"] ||
- getQueryParams()["instructor"] == "true",
- developer: true,
- editor: getQueryParams()["mode"] || "Split",
- urls: {
- }
- });
- // ready();
- var size = calculate_size($("#term")[0]);
- term = new Terminal({
- cols: size[0],
- rows: size[1],
- useStyle: true,
- screenKeys: true,
- cursorBlink: false
- });
- term.open(document.getElementById("term"));
- //show_https_warning();
- $(".filled-in")[0].onclick = function () {
- var _chi = $(".filled-in")[0];
- var _par = $(".filled-in")[0].parentNode;
- if (!_chi.checked) {
- _par.children[1].className = 'filled-in_nocheked translatable_Adapter_fill_connected';
- _par.children[1].innerHTML = CCB.str_group.Adapter_fill_connected;
- } else {
- _par.children[1].className = 'translatable_Adapter_connected';
- _par.children[1].innerHTML = CCB.str_group.Adapter_connected;
- };
- }
- setTimeout(() => {
- cocoblockly();
- document.getElementsByTagName("svg")[0].focus()
- }, 0);
- $('.blockpy-toolbar-download').on(
- "click", () => export_data(
- pythonnewcode || Blockly.Python.workspaceToCode(blockpy.components.editor.blockly) || blockpy.components.editor.codeMirror.getValue(), '.py', 0
- )
- );
- // uploadpy
- document.getElementById('uploadpy').onclick = async function () {
- // decounce(uploadpyCocoPi(), 1000)
- uploadpyCocoPi()
- }
- // runCode
- document.getElementById('runCode').onclick = async function () {
- // decounce(runCocoPi(), 1000)
- runCocoPi()
- }
- const uploadXmlButton = $('#pyFileImport > input');
- uploadXmlButton.change(function () {
- var fr = new FileReader();
- var files = uploadXmlButton[0].files;
- const file = files[0];
- Ardublockly.alertExampleMessage(
- '', Ardublockly.getLocalStr('loadBlockBody'),
- true, {});
- fr.onload = function (e) {
- var pyInnerHTML = e.target.result;
- blockpy.components.editor.codeMirror.setValue(pyInnerHTML);
- };
- fr.readAsText(file);
- setTimeout(() => {
- $('#loading').css({ 'display': 'none' });
- $('#example_alert').modal('close');
- }, 300)
- uploadXmlButton.val("");
- });
- $('.blockpy-toolbar-upload').click(e => $('#pyFileImport > input').click());
- fanyi();
- selectOnload();
- styled()
- $('#toggle-button').click(() => {
- if ($('#toggle-button')[0].checked) {
- $('.edit')[0].style.display = 'none';
- // $('.edit')[1].style.display = 'none';
- // $('.translatable_editing')[0].style.display = "none";
- // $('.translatable_close_editing')[0].style.display = "inline-block"
- } else {
- $('.edit')[0].style.display = 'block';
- // $('.edit')[1].style.display = 'block';
- // $('.translatable_editing')[0].style.display = "inline-block";
- // $('.translatable_close_editing')[0].style.display = "none"
- }
- })
- // toggle-button-Connect
- $('#toggle-button-Connect').click(() => {
- console.log($('#toggle-button-Connect')[0].checked)
- if ($('#toggle-button-Connect')[0].checked) {
- // $("#toggle-button-Connect")[0].checked = true
- localStorage.setItem("SwitchConnect", true)
- switch_connect = true
- $('.circle_text')[0].innerText = _lang == "zh-hans" ? "自动" : _lang == "zh-hant" ? "自動" : "AT"
- } else {
- // $("#toggle-button-Connect")[0].checked = false
- localStorage.setItem("SwitchConnect", false)
- switch_connect = false
- $('.circle_text')[0].innerText = _lang == "zh-hans" ? "手动" : _lang == "zh-hant" ? "手動" : "MT"
- }
- })
- $('#toggle-button1').click(() => {
- if ($('#toggle-button1')[0].checked) {
- $('#image_transmission_canvas')[0].style.display = 'none';
- // $('.translatable_editing')[0].style.display = "none";
- // $('.translatable_close_editing')[0].style.display = "inline-block"
- } else {
- $('#image_transmission_canvas')[0].style.display = 'block';
- // $('.translatable_editing')[0].style.display = "inline-block";
- // $('.translatable_close_editing')[0].style.display = "none"
- }
- })
- $("#webadbErro").click(() => {
- window.file_manger_modal = false
- let webadb_document = document.getElementById('webadb_iframe').contentWindow.getdevice()
- webadb_document.device.subprocess.shell(Repair).then(function (e) {
- e.stdout.reader.read().then(function (m) {
- var str = Uint8ArrayToString(m.value);
- if (str.indexOf("/bin/sh") > -1 || str.indexOf("Read-only file system") > -1) {
- webadb_document.device.subprocess.shell("reboot").then(s => {
- $("#webadbErro").css("display", "none")
- })
- } else {
- $("#webadbErro").css("display", "none")
- }
- setTimeout(() => {
- window.file_manger_modal = true
- })
- // 重启修复
- })
- }).catch(err => {
- window.file_manger_modal = true
- })
- })
- const _lang = getUrlLanguage();
- // 判断从python blcokly 跳转过来是ai或者iot
- if (window.location.search.indexOf('name=1') > -1 || window.location.search.indexOf('id=ai') > -1) {
- $("#mode")[0].selectedIndex = 1;
- $("#mode")[0].onchange();
- $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
- history.pushState(null, null, '//x.cocorobo.cn/?lang=' + _lang);
- selectmode($("#mode")[0], true);
- // document.getElementById("list").getElementsByTagName("li")[1].onclick();
- }
- else if (window.location.search.indexOf('name=0') > -1 || window.location.search.indexOf('id=iot') > -1) {
- $("#mode")[0].selectedIndex = 0;
- $("#mode")[0].onchange();
- $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.iot_module;
- history.pushState(null, null, '//x.cocorobo.cn/?lang=' + _lang);
- selectmode($("#mode")[0], true);
- // document.getElementById("list").getElementsByTagName("li")[0].onclick();
- }
- else {
- if (getLocalStorage("type") == 1) {
- $("#mode")[0].selectedIndex = 1;
- $("#mode")[0].onchange();
- $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
- selectmode($("#mode")[0], true);
- // document.getElementById("list").getElementsByTagName("li")[1].onclick();
- } else {
- $("#mode")[0].selectedIndex = 0;
- $("#mode")[0].onchange();
- $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.iot_module;
- selectmode($("#mode")[0], true);
- // document.getElementById("list").getElementsByTagName("li")[0].onclick();
- }
- }
- $('#white-box').css('display', 'none');
- const copyCodeClipboard = new ClipboardJS(".copy_code", {
- text: function () {
- return blockpy.components.editor.codeMirror.getValue();
- }
- });
- copyCodeClipboard.on("success", () => copyCodeToast(2000));
- mouseMove();
- const copyCodeToast = (function (lang) {
- let toast = null,
- timeout = null;
- const content = lang === 'zh-hans' ? "复制成功" :
- lang === 'zh-hant' ? "複製成功" : "Copy Successfully";
- return function (ms) {
- if (toast) {
- toast.dismiss();
- clearTimeout(timeout);
- }
- toast = Materialize.toast(content, ms);
- timeout = setTimeout(() => toast = timeout = null, ms);
- };
- })(_lang);
- $("#delete-all").click(() => clearBlocks());
- $("#screenshot").click(() => Blockly.captureDialog_());
- $("#clearOutput").click(() => $(".blockpy-printer").html(""));
- $("#resetAll").click(() => clearBlocks(() => $(".blockpy-printer").html("")));
- // $("#lang-tool").click(() => $("#side-lang-trigger > a").dropdown('open'));
- // $("#file-tool").click(() => $("#side-file-trigger > a").dropdown('open'));
- $("#blockpy-content > .blockpy-editor img.fullscreenIcon").click(e => {
- $(e.currentTarget.parentNode).toggleClass("fullscreen");
- $('.edit')[0].style.display = 'none';
- // $('.edit')[1].style.display = 'none';
- $("#blockpy-content > .blockpy-editor img.fullscreenIcon").toggleClass("hidden");
- $("html").toggleClass("fullscreenMode");
- setTimeout(function () {
- Blockly.svgResize(blockpy.components.editor.blockly);
- Blockly.svgResize(Blockly.mainWorkspace);
- }, 100)
- });
- $("#blockpy-content .card-header > img.fullscreenIcon").click(e => {
- $(e.currentTarget.parentNode.parentNode).toggleClass("fullscreen");
- $('.edit')[0].style.display = 'block';
- // $('.edit')[1].style.display = 'block';
- $("#blockpy-content .card-header > img.fullscreenIcon").toggleClass("hidden");
- $("html").toggleClass("fullscreenMode");
- setTimeout(() => $(".blockpy-toolbar > .blockpy-text")
- .css("height", "90%")
- .css("height", "100%"), 0);
- });
- let browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
- if (browserWidth < 500) {
- $('.mobileSwitch')[0].style.display = "block"
- $('#py-editor')[0].style.display = "none"
- // $("#IP")[0].style.display = "block"
- }
- // if (document.getElementById("v831_img_save")) {
- // document.getElementById("v831_img_save").onclick = function (e) {
- // console.log(this,e)
- // console.log("v831_img_save 被点击")
- // };
- // }
- // 点击复制分享链接
- copyShare()
- // 监听本地存储中是否自动连接
- if (localStorage.getItem("SwitchConnect") == "true" || localStorage.getItem("SwitchConnect") == null) {
- $("#toggle-button-Connect")[0].checked = true
- switch_connect = true
- $('.circle_text')[0].innerText = _lang == "zh-hans" ? "自动" : _lang == "zh-hant" ? "自動" : "AT"
- } else {
- $("#toggle-button-Connect")[0].checked = false
- switch_connect = false
- $('.circle_text')[0].innerText = _lang == "zh-hans" ? "手动" : _lang == "zh-hant" ? "手動" : "MT"
- }
- window.file_manger_modal = true
- document.getElementById("webadb_iframe").onload = function () {
- setInterval(function () {
- if (document.getElementById("webadb_iframe").contentWindow.getdevice && window.file_manger_modal && deviceType == 0) {
- isDevice = document.getElementById("webadb_iframe").contentWindow.getdevice();
- isConnect = document.getElementById("webadb_iframe").contentWindow.isconnect()
- if (isDevice.device == undefined && isDevice.selectdevice == undefined) {
- $("#webadb_connect")[0].disabled = true;
- $("#webadb_add")[0].disabled = false;
- $("#runCode").addClass('disabled')
- $("#uploadpy").addClass('disabled')
- $("#resetDevice").addClass('disabled')
- $("#backHome").addClass('disabled')
- $("#poweroff").addClass('disabled')
- $("#OneClickUpgradeId").addClass("disabled")
- $("#CocoPiUpgrades").addClass("disabled")
- $('#message_file').css({ display: 'none' })
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusNotConn
- $('.progress > .determinate').css('width', 0);
- $('#cnt_icon').css('display', 'none')
- $('#discnt_icon').css('display', 'inline-block')
- $('#select-connected').attr("disabled", false)
- }
- else if (isDevice.device == undefined && isDevice.selectdevice != undefined) {
- $("#webadb_connect")[0].disabled = false;
- $("#webadb_add")[0].disabled = false;
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusNotConn
- $("#runCode").addClass('disabled')
- $("#uploadpy").addClass('disabled')
- $("#resetDevice").addClass('disabled')
- $("#backHome").addClass('disabled')
- $("#poweroff").addClass('disabled')
- $("#OneClickUpgradeId").addClass("disabled")
- $("#CocoPiUpgrades").addClass("disabled")
- $('#message_file').css({ display: 'none' })
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
- $('.progress > .determinate').css('width', 0);
- $('#cnt_icon').css('display', 'none')
- $('#discnt_icon').css('display', 'inline-block')
- $('#select-connected').attr("disabled", false);
- if (reconnect && switch_connect) {
- webadbConnect();
- }
- }
- else if (isDevice.device != undefined && isDevice.selectdevice != undefined) {
- $("#webadb_add")[0].disabled = true;
- if (!!isConnect) {
- $('#select-connected').attr("disabled", true)
- $('#cnt_icon').css('display', 'inline-block')
- $('#discnt_icon').css('display', 'none')
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.disConnect
- $("#webadb_connect")[0].disabled = false;
- $('#message_file').css({ display: 'inline-block' })
- $("#runCode").removeClass('disabled')
- $("#uploadpy").removeClass('disabled')
- $("#resetDevice").removeClass('disabled')
- $("#poweroff").removeClass('disabled')
- $("#OneClickUpgradeId").removeClass("disabled")
- $("#CocoPiUpgrades").removeClass("disabled")
- if (autoContent) {
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusbar
- }
- } else {
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
- $("#webadb_connect")[0].disabled = true;
- $('#message_file').css({ display: 'none' })
- }
- }
- } else if (deviceType == 2) {
- // console.log("bledevice",bledevice)
- if (bledevice && bledevice.gatt && bledevice.gatt.connected) {
- $('#select-connected').attr("disabled", true)
- $('#cnt_icon').css('display', 'inline-block')
- $('#discnt_icon').css('display', 'none')
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.disConnect
- $("#webadb_connect")[0].disabled = false;
- $('#message_file').css({ display: 'inline-block' })
- $("#runCode").removeClass('disabled')
- $("#uploadpy").removeClass('disabled')
- $("#resetDevice").addClass('disabled')
- $("#poweroff").addClass('disabled')
- $("#OneClickUpgradeId").removeClass("disabled")
- $("#CocoPiUpgrades").removeClass("disabled")
- if ($("#status_txt")[0].innerHTML == Ardublockly.LOCALISED_TEXT.statusNotConn) {
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusbar
- }
- } else {
- $("#webadb_add")[0].disabled = false;
- $("#runCode").addClass('disabled')
- $("#uploadpy").addClass('disabled')
- $("#resetDevice").addClass('disabled')
- // $("#backHome").removeClass('disabled')
- $("#poweroff").addClass('disabled')
- $("#OneClickUpgradeId").addClass("disabled")
- $("#CocoPiUpgrades").addClass("disabled")
- $('#message_file').css({ display: 'none' })
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusNotConn
- $('.progress > .determinate').css('width', 0);
- $('#cnt_icon').css('display', 'none')
- $('#discnt_icon').css('display', 'inline-block')
- $('#select-connected').attr("disabled", false)
- if (bledevice && bledevice.id) {
- $("#webadb_connect")[0].disabled = false;
- }
- }
- }
- }, 1000)
- }
- // 加载更新提示框
- let updateData = await getJsonData('./update.json');
- // 最新更新你内容
- let updateNew = _lang == "zh-hans" ? updateData.updateNew.zhHans : _lang == "zh-hant" ? updateData.updateNew.zhHant : updateData.updateNew.en;
- let isUpdate = localStorage.getItem('isUpdate') || 0
- let blocklLis = "";
- let exampleLis = "";
- let noteLis = ""
- for (let i = 0; i < updateNew.blocks.length; i++) {
- let blockLi = `<li>${updateNew.blocks[i]}</li>`
- blocklLis = blocklLis + blockLi
- }
- $('#blockLis').append(blocklLis)
- for (let i = 0; i < updateNew.example.length; i++) {
- let exampleLi = `<li>${updateNew.example[i]}</li>`
- exampleLis = exampleLis + exampleLi
- }
- $('#exampleLis').append(exampleLis)
- for (let i = 0; i < updateNew.note.length; i++) {
- let noteLi = `<li>${updateNew.note[i]}</li>`
- noteLis = noteLis + noteLi
- }
- $('#noteLis').append(noteLis)
- $(".updateTime")[0].innerHTML = updateData.updateNew.time
- // 历史更新
- let updateDataOld = updateData.updateOld
- let leftStr = ''
- let noteStr = ''
- for (let i = 0; i < updateDataOld.length; i++) {
- let data = updateDataOld[i]
- let time = `<h5>${data.time}</h5>`;
- let updateData = _lang == "zh-hans" ? data.zhHans : _lang == "zh-hant" ? data.zhHant : data.en;
- let blocklLisOld = ''
- let exampleLisOld = ''
- let noteLisOld = ''
- for (let i = 0; i < updateData.blocks.length; i++) {
- let blockLi = `<li>${updateData.blocks[i]}</li>`
- blocklLisOld = blocklLisOld + blockLi
- }
- for (let i = 0; i < updateData.example.length; i++) {
- let exampleLi = `<li>${updateData.example[i]}</li>`
- exampleLisOld = exampleLisOld + exampleLi
- }
- for (let i = 0; i < updateData.note.length; i++) {
- let noteLi = `<li>${updateData.note[i]}</li>`
- noteLisOld = noteLisOld + noteLi
- }
- leftStr = leftStr + `${time}<li><span>${Ardublockly.LOCALISED_TEXT.updateblock}<ul class="updateContent">${blocklLisOld}</ul></li><li>${Ardublockly.LOCALISED_TEXT.updateexample}<ul class="updateContent">${exampleLisOld}</ul></li>`
- noteStr = noteStr + `${time}${noteLisOld}`
- }
- $('#leftUpdateOld').append(leftStr)
- $('#noteLisOld').append(noteStr)
- // $("#root").modal("open");
- }
- function styled() {
- if (window.location.search.indexOf("en") > -1) {
- $(".downbox-style").css({ width: '280px', marginLeft: '-100px' }),
- $(".HarxA1").css({ left: "calc(100% - 610px)" });
- $('#aaa .HarxA1').addClass('HarxA1_style')
- // $(".container-bottom").css("height","390px")
- $(".modelDownloadItemTitle").css("marginTop", "15px");
- $(".vision_category").css("marginTop", "15px");
- $(".model_download_modal_column").css("height", "435px");
- $(".modelDownloadItemDesc").css("height", "110px");
- }
- }
- function fanyi() {
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn
- $('.ModeSelect')[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_Example;
- $('.ModeBox')[0].children[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.artificial_intelligence_textbook_program;
- $('.Hardware9 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.third_grade;
- $('.ModeBox ul')[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.recorded_voice_command;
- $('.ModeBox ul')[0].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.voice_recognition_lamp_stand;
- $('.Hardware4n div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.four_grade;
- $('.ModeBox ul')[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_aifr;
- $('.ModeBox ul')[1].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aiaor;
- $('.Hardware5 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.fifth_grade;
- $('.ModeBox ul')[2].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.recorded_voice_command;
- $('.ModeBox ul')[2].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.intelligent_curtain;
- $('.ModeBox ul')[2].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.fruit_picking_robot;
- $('.ModeBox ul')[2].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.fntelligent_inspection_robot;
- $('.Hardware6 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.sixth_grade;
- $('.ModeBox ul')[3].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.intelligent_traffic_lights;
- $('.ModeBox ul')[3].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.seeing_eye_necklace;
- $('.ModeBox ul')[3].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.code_package_sorting_robot;
- $('.ModeBox ul')[3].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.unmanned_circulation_car;
- $('.Hardware7 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.seventh_grade;
- $('.ModeBox ul')[4].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.face_recognition_electronic_police;
- $('.Hardware8 div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.eighth_grade;
- $('.ModeBox ul')[5].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.payment_platform;
- $('.ModeBox')[0].children[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_Basics;
- $('.ModeBox ul')[6].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_sbcb;
- $('.ModeBox ul')[6].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_sbcsl;
- $('.ModeBox ul')[6].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_tacl;
- $('.ModeBox ul')[6].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_ba;
- $('.ModeBox ul')[6].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_desl;
- $('.ModeBox ul')[6].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_tdsl;
- $('.ModeBox ul')[6].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_ha;
- $('.ModeBox ul')[6].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_ssl;
- $('.ModeBox ul')[6].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_ldliv;
- $('.ModeBox')[0].children[2].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_imefc;
- $('.ModeBox ul')[7].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_uls;
- $('.ModeBox ul')[7].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_umdm;
- $('.ModeBox ul')[7].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_uoglls;
- $('.ModeBox ul')[7].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_auogsm;
- $('.ModeBox ul')[7].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_ctsotem;
- $('.ModeBox ul')[7].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_thwos;
- $('.ModeBox ul')[7].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_sdla;
- $('.ModeBox ul')[7].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_line;
- $('.ModeBox ul')[7].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_bccs;
- $('.ModeBox ul')[7].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_stepCounter;
- $('.ModeBox ul')[7].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_stepCounter_1;
- $('.ModeBox ul')[7].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_bluetooth_send;
- $('.ModeBox ul')[7].children[12].innerHTML = Ardublockly.LOCALISED_TEXT.select_bluetooth_receive;
- $('.ModeBox')[0].children[3].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_ionc;
- $('.ModeBox ul')[8].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_btsldtc;
- $('.ModeBox ul')[8].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_ktsedti;
- $('.ModeBox ul')[8].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_btoldalua;
- $('.ModeBox ul')[8].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_tsedtc;
- $('.ModeBox ul')[8].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_toedaluatc;
- $('.ModeBox ul')[8].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_ewhadtnocd;
- $('.ModeBox ul')[8].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_ledss;
- $('.ModeBox ul')[8].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_ledac;
- $('.ModeBox ul')[8].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_ctwn;
- $('.ModeBox ul')[8].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_bssbms;
- $('.ModeBox ul')[8].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_bsrbmc;
- $('.ModeBox ul')[8].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_wrcbms;
- $('.ModeBox ul')[8].children[12].innerHTML = Ardublockly.LOCALISED_TEXT.select_wrcbmr;
- $('.ModeBox ul')[8].children[13].innerHTML = Ardublockly.LOCALISED_TEXT.select_snt;
- $('.ModeBox ul')[8].children[14].innerHTML = Ardublockly.LOCALISED_TEXT.select_dwsdat;
- $('.ModeBox')[0].children[4].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_work_u;
- $('.ModeBox ul')[9].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_middle_led;
- $('.ModeBox ul')[9].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_all_led;
- $('.ModeBox ul')[9].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_liu_led;
- $('.ModeBox ul')[9].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_warning;
- $('.ModeBox ul')[9].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_music;
- $('.ModeBox ul')[9].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_button_open;
- $('.ModeBox ul')[9].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_touch_open;
- $('.ModeBox ul')[9].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_button_close;
- $('.ModeBox ul')[9].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_control_LED;
- $('.ModeBox ul')[9].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_sensor_LED;
- $('.ModeBox ul')[9].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_humidity_alarm;
- $('.ModeBox')[0].children[5].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_work_d;
- $('.ModeBox ul')[10].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_shaking_LED;
- // $('.ModeBox ul')[4].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_connect_wifi;
- $('.ModeBox ul')[10].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_show_statement;
- $('.ModeBox ul')[10].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_establish_WiFi;
- $('.ModeBox ul')[10].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_download_lighting;
- $('.ModeBox ul')[10].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_controlling_servo;
- $('.ModeBox ul')[10].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_move_servo;
- $('.ModeBox ul')[10].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_button_controlling_servo;
- $('.ModeBox ul')[10].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_face_recognition_door;
- $('.ModeBox ul')[10].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_speech_recognition_car;
- $('.ModeBox ul')[10].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_gyro_control_robot;
- $('.ModeBox ul')[10].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_gesture_recognition_robot;
- $('.ModeBox ul')[10].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_speech_recogniton_lamp;
- $('.ModeBox')[0].children[6].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_smmlc;
- $('.ModeBox ul')[11].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.basis_face_Intelligent;
- $('.ModeBox ul')[11].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_gcaerhk;
- $('.ModeBox ul')[11].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_frs;
- $('.ModeBox ul')[11].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_ors;
- $('.ModeBox ul')[11].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_fr;
- $('.ModeBox ul')[11].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_or;
- $('.ModeBox ul')[11].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_srd;
- $('.ModeBox ul')[11].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_srt;
- $('.ModeBox ul')[11].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_mhdr;
- $('.ModeBox')[0].children[7].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_ambc;
- $('.ModeBox ul')[12].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_bcsc;
- $('.ModeBox ul')[12].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_kcpccs;
- $('.ModeBox ul')[12].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_kcpficc;
- $('.ModeBox ul')[12].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_bccs;
- $('.ModeBox ul')[12].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_mc;
- $('.ModeBox ul')[12].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_sor;
- $('.ModeBox ul')[12].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_sdla;
- $('.ModeBox')[0].children[8].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_amefc;
- $('.ModeBox ul')[13].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_auls;
- $('.ModeBox ul')[13].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aumdm;
- $('.ModeBox ul')[13].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_auogsm;
- $('.ModeBox ul')[13].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_actsotem;
- $('.ModeBox ul')[13].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_greedy_snake;
- $('.ModeBox')[0].children[9].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_amvc;
- $('.ModeBox ul')[14].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_bctbotci;
- $('.ModeBox ul')[14].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aca;
- $('.ModeBox ul')[14].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_rqc;
- $('.ModeBox ul')[14].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_lhbl;
- $('.ModeBox ul')[14].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_fgr;
- $('.ModeBox ul')[14].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_fgaat;
- $('.ModeBox')[0].children[10].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_av;
- $('.ModeBox ul')[15].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.paly_video;
- $('.ModeBox ul')[15].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.paly_music;
- $('.ModeBox ul')[15].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.recording_camera;
- $('.ModeBox ul')[15].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.microphone_sound_analysis;
- $('.ModeBox')[0].children[11].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_teacher;
- $('.ModeBox ul')[16].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_thw;
- $('.ModeBox ul')[16].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_thwos;
- $('.ModeBox ul')[16].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_uoc;
- $('.ModeBox ul')[16].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_mc;
- $('.ModeBox ul')[16].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_sor;
- $('.ModeBox')[0].children[12].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_teacher2;
- $('.ModeBox ul')[17].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_aiaor;
- $('.ModeBox ul')[17].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aifr;
- $('.ModeBox ul')[17].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_aica;
- $('.ModeBox ul')[17].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_aisrc;
- $('.ModeBox ul')[17].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_aisrr;
- $('.ModeBox ul')[17].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_aiaa;
- $('.ModeBox')[0].children[13].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_teachingcases;
- $('.ModeBox ul')[18].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ex1_servo;
- $('.ModeBox ul')[18].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ex2_Ultrasound;
- // $('.ModeBox ul')[12].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ex3_RangeFinder;
- // $('.ModeBox ul')[12].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ex4_LightStrip;
- // $('.ModeBox ul')[12].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.ex5_Microbit;
- // $('.ModeBox ul')[12].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.ex6_MicrobitFace;
- // $('.ModeBox ul')[12].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.ex7_Door;
- $('.ModeBox ul')[18].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ex4_LightStrip
- $('.ModeBox ul')[18].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ex5_Microbit;
- $('.ModeBox ul')[18].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.ex6_MicrobitFace;
- $('.ModeBox ul')[18].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.ex7_Door;
- $('.ModeBox')[0].children[14].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_wc;
- $('.ModeBox ul')[19].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_smaa;
- $('.ModeBox ul')[19].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ai_gc;
- $('.ModeBox ul')[19].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ai_wsb;
- $('.ModeBox')[0].children[15].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_ad;
- $('.ModeBox ul')[20].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_trsr;
- $('.ModeBox ul')[20].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tpl2;
- $('.ModeBox ul')[20].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tpll;
- $('.ModeBox ul')[20].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tph;
- $('.ModeBox')[0].children[16].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm;
- $('.ModeBox ul')[21].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm_iot_send;
- $('.ModeBox ul')[21].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm_ai_get;
- $('.ModeBox ul')[21].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm_ai_send;
- $('.ModeBox ul')[21].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.serial_comm_iot_get;
- $('.ModeBox1')[0].children[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.artificial_intelligence_textbook_program;
- $('.Hardware9 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.third_grade;
- $('.ModeBox1 ul')[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.recorded_voice_command;
- $('.ModeBox1 ul')[0].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.voice_recognition_lamp_stand;
- $('.Hardware4n div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.four_grade;
- $('.ModeBox1 ul')[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_aifr;
- $('.ModeBox1 ul')[1].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_aiaor;
- $('.Hardware5 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.fifth_grade;
- $('.ModeBox1 ul')[2].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.recorded_voice_command;
- $('.ModeBox1 ul')[2].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.intelligent_curtain;
- $('.ModeBox1 ul')[2].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.fruit_picking_robot;
- $('.ModeBox1 ul')[2].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.fntelligent_inspection_robot;
- $('.Hardware6 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.sixth_grade;
- $('.ModeBox1 ul')[3].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.intelligent_traffic_lights;
- $('.ModeBox1 ul')[3].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.seeing_eye_necklace;
- $('.ModeBox1 ul')[3].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.code_package_sorting_robot;
- $('.ModeBox1 ul')[3].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.unmanned_circulation_car;
- $('.Hardware7 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.seventh_grade;
- $('.ModeBox1 ul')[4].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.face_recognition_electronic_police;
- $('.Hardware8 div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.eighth_grade;
- $('.ModeBox1 ul')[5].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.payment_platform;
- $('.ModeBox1')[0].children[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_Basics;
- $('.ModeBox1 ul')[6].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_sbcb;
- $('.ModeBox1 ul')[6].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_sbcsl;
- $('.ModeBox1 ul')[6].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_tacl;
- $('.ModeBox1 ul')[6].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_ba;
- $('.ModeBox1 ul')[6].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_desl;
- $('.ModeBox1 ul')[6].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_tdsl;
- $('.ModeBox1 ul')[6].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_ha;
- $('.ModeBox1 ul')[6].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_ssl;
- $('.ModeBox1 ul')[6].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_ldliv;
- $('.ModeBox1')[0].children[2].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_imefc;
- $('.ModeBox1 ul')[7].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_uls;
- $('.ModeBox1 ul')[7].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_umdm;
- $('.ModeBox1 ul')[7].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_uoglls;
- $('.ModeBox1 ul')[7].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_auogsm;
- $('.ModeBox1 ul')[7].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_ctsotem;
- $('.ModeBox1 ul')[7].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_thwos;
- $('.ModeBox1 ul')[7].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_sdla;
- $('.ModeBox1 ul')[7].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_line;
- $('.ModeBox1 ul')[7].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_bccs;
- $('.ModeBox1 ul')[7].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_stepCounter;
- $('.ModeBox1 ul')[7].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_stepCounter_1;
- $('.ModeBox1 ul')[7].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_bluetooth_send;
- $('.ModeBox1 ul')[7].children[12].innerHTML = Ardublockly.LOCALISED_TEXT.select_bluetooth_receive;
- $('.ModeBox1')[0].children[3].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_ionc;
- $('.ModeBox1 ul')[8].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_btsldtc;
- $('.ModeBox1 ul')[8].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_ktsedti;
- $('.ModeBox1 ul')[8].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_btoldalua;
- $('.ModeBox1 ul')[8].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_tsedtc;
- $('.ModeBox1 ul')[8].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_toedaluatc;
- $('.ModeBox1 ul')[8].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_ewhadtnocd;
- $('.ModeBox1 ul')[8].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_ledss;
- $('.ModeBox1 ul')[8].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_ledac;
- $('.ModeBox1 ul')[8].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_ctwn;
- $('.ModeBox1 ul')[8].children[9].innerHTML = Ardublockly.LOCALISED_TEXT.select_bssbms;
- $('.ModeBox1 ul')[8].children[10].innerHTML = Ardublockly.LOCALISED_TEXT.select_bsrbmc;
- $('.ModeBox1 ul')[8].children[11].innerHTML = Ardublockly.LOCALISED_TEXT.select_wrcbms;
- $('.ModeBox1 ul')[8].children[12].innerHTML = Ardublockly.LOCALISED_TEXT.select_wrcbmr;
- $('.ModeBox1 ul')[8].children[13].innerHTML = Ardublockly.LOCALISED_TEXT.select_snt;
- $('.ModeBox1 ul')[8].children[14].innerHTML = Ardublockly.LOCALISED_TEXT.select_dwsdat;
- $('.ModeBox1')[0].children[4].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.select_smmlc;
- $('.ModeBox1 ul')[9].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.basis_face_Intelligent;
- $('.ModeBox1 ul')[9].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.select_gcaerhk;
- $('.ModeBox1 ul')[9].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.select_frs;
- $('.ModeBox1 ul')[9].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.select_ors;
- $('.ModeBox1 ul')[9].children[4].innerHTML = Ardublockly.LOCALISED_TEXT.select_fr;
- $('.ModeBox1 ul')[9].children[5].innerHTML = Ardublockly.LOCALISED_TEXT.select_or;
- $('.ModeBox1 ul')[9].children[6].innerHTML = Ardublockly.LOCALISED_TEXT.select_srd;
- $('.ModeBox1 ul')[9].children[7].innerHTML = Ardublockly.LOCALISED_TEXT.select_srt;
- $('.ModeBox1 ul')[9].children[8].innerHTML = Ardublockly.LOCALISED_TEXT.select_mhdr;
- $('.ModeBox1')[0].children[5].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_ad;
- $('.ModeBox1 ul')[10].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_trsr;
- $('.ModeBox1 ul')[10].children[1].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tpl2;
- $('.ModeBox1 ul')[10].children[2].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tpll;
- $('.ModeBox1 ul')[10].children[3].innerHTML = Ardublockly.LOCALISED_TEXT.ai_tph;
- // $('#uploadFiles')[0].innerHTML = Ardublockly.LOCALISED_TEXT.uploadFiles;
- $("#sketch_name").val(Ardublockly.LOCALISED_TEXT.sketch_name);
- // $('#runCode')[0].innerHTML = Ardublockly.LOCALISED_TEXT.runCode;
- // $('#uploadFiles')[0].innerHTML = Ardublockly.LOCALISED_TEXT.uploadFiles;
- // $('#resetMainUI')[0].innerHTML = Ardublockly.LOCALISED_TEXT.resetMainUI;
- $('#select_dropdown')[0].value = Ardublockly.LOCALISED_TEXT.select_dropdown;
- // $('#iot_modules')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
- $(".qiehuanbtn")[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.a_csm;
- $("#localsssssaveOrOpen")[0].children[0].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.a_butvmi;
- $("#localsssssaveOrOpen")[0].children[1].children[0].innerHTML = Ardublockly.LOCALISED_TEXT.a_buartlp;
- }
- var deviceType = 0 // 0有线;1无线;2蓝牙
- function selectOnload() {
- $('.select-connected')[0].onchange = function () {
- var a = $('.select-connected')[0].selectedIndex;
- deviceType = a
- if (a == 0) {
- $('#Serial_Interaction').css("display", 'inline-block')
- $('#IP').css('display', 'none')
- $("#SwitchConnect").css('display', 'inline-block')
- } else if (a == 2) {
- // console.log("蓝牙")webadb_add
- // deviceType = 2
- $('#Serial_Interaction').css("display", 'none')
- $('#IP').css('display', 'none')
- }
- else {
- // deviceType = 1
- $('#Serial_Interaction').css("display", 'none')
- $('#IP').css('display', 'block')
- $("#SwitchConnect").css('display', 'none')
- // 进行socket 连接
- }
- }
- $('.selectMode_input')[0].parentNode.onclick = function (e) {
- $('.MouduleBox')[0].style.cssText = 'display:block';
- }
- $('.ModeSelectBox')[0].onclick = function (e) {
- U.UF.EV.stopBubble();
- // $('.ModeSelect')[0].className = 'ModeSelect active';
- $("#select_Example_modal").modal("open")
- }
- $('#update_log')[0].onclick = function (e) {
- $("#loadModal").modal("open")
- }
- $('#model_download_modal')[0].onclick = function (e) {
- $("#select_Model_download_modal").modal("open")
- }
- var modelsItems = document.getElementsByClassName("modelDownloadItemTitle");
- var modelsItemDescs = document.getElementsByClassName("modelDownloadItemDesc");
- for (var i = 0, len = modelsItems.length; i < len; i++) {
- modelsItems[i].title = modelsItems[i].innerHTML;
- }
- for (var i = 0, len = modelsItemDescs.length; i < len; i++) {
- modelsItemDescs[i].title = modelsItemDescs[i].innerHTML;
- }
- // var items = document.getElementById("list").getElementsByTagName("li");
- //获取5个内容盒子;
- var divs = document.getElementById("item").getElementsByTagName("div");
- var examples = document.getElementById("item").getElementsByTagName("li");
- var divs_type = document.getElementById("item_1").getElementsByTagName("div");
- var examples_type = document.getElementById("item_1").getElementsByTagName("li");
- var exampleList = document.getElementById("example").getElementsByClassName("con");
- // if (items.length != divs.length) {
- // return;
- // }
- for (var i = 0, len = examples.length; i < len; i++) {
- examples[i].id = i;
- examples[i].onclick = function () {
- for (var j = 0, len = examples.length; j < len; j++) {
- examples[j].className = "container-middle-noactive arrow";
- divs_type[j].style.display = "none";
- }
- for (var k = 0, len = examples_type.length; k < len; k++) {
- examples_type[k].className = "container-middle-1-noactive arrow";
- exampleList[k].style.display = "none";
- }
- this.className = "container-middle-active arrow_active";
- divs_type[this.id].getElementsByTagName("li")[0].className = "container-middle-1-active arrow_active";
- divs_type[this.id].style.display = "block";
- if (this.id == 0) {
- for (var k = 0, len = exampleList.length; k < len; k++) {
- exampleList[k].style.display = "none";
- }
- exampleList[0].style.display = "block";
- }
- else if (this.id == 1) {
- for (var k = 0, len = exampleList.length; k < len; k++) {
- exampleList[k].style.display = "none";
- }
- exampleList[8].style.display = "block";
- }
- else if (this.id == 2) {
- for (var k = 0, len = exampleList.length; k < len; k++) {
- exampleList[k].style.display = "none";
- }
- exampleList[11].style.display = "block";
- }
- else if (this.id == 3) {
- for (var k = 0, len = exampleList.length; k < len; k++) {
- exampleList[k].style.display = "none";
- }
- exampleList[13].style.display = "block";
- }
- else if (this.id == 4) {
- for (var k = 0, len = exampleList.length; k < len; k++) {
- exampleList[k].style.display = "none";
- }
- exampleList[15].style.display = "block";
- }
- else if (this.id == 5) {
- for (var k = 0, len = exampleList.length; k < len; k++) {
- exampleList[k].style.display = "none";
- }
- exampleList[22].style.display = "block";
- }
- else if (this.id == 6) {
- for (var k = 0, len = exampleList.length; k < len; k++) {
- exampleList[k].style.display = "none";
- }
- exampleList[27].style.display = "block";
- }
- else {
- for (var k = 0, len = exampleList.length; k < len; k++) {
- exampleList[k].style.display = "none";
- }
- exampleList[32].style.display = "block";
- }
- }
- }
- for (var i = 0, len = examples_type.length; i < len; i++) {
- examples_type[i].id = i;
- examples_type[i].onclick = function () {
- for (var k = 0, len = examples_type.length; k < len; k++) {
- examples_type[k].className = "container-middle-1-noactive arrow";
- exampleList[k].style.display = "none";
- }
- this.className = "container-middle-1-active arrow_active";
- exampleList[this.id].style.display = "block";
- }
- }
- likeclose($('.selectMode_input')[0].parentNode, $('.MouduleBox')[0], '', '');
- likeclose($('.ModeSelect')[0].children[0], $('.ModeSelect')[0], 1, 'ModeSelect');
- likeclose($('#bar_ai img')[0], $('.MouduleBox')[1], '', '');
- likeclose($('#bar_t img')[0], $('#ai_tt')[0], '', '');
- var MChild = $('.MouduleBox')[0].children;
- var tchild = $('.MouduleBox')[1].children;
- for (var i = 0; i < MChild.length; i++) {
- tchild[i].onclick = MChild[i].onclick = function (e) {
- window.event ? window.event.cancelBubble = true : e.stopPropagation()
- var e = e.target;
- if (e.parentElement.children[2] && e.parentElement.children[2].children.length > 0) { } else {
- if (e.innerHTML == Ardublockly.LOCALISED_TEXT.iot_module) {
- $("#mode")[0].selectedIndex = 0;
- $("#mode")[0].onchange();
- $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.iot_module;
- // document.getElementById("list").getElementsByTagName("li")[0].onclick();
- }
- else if (e.innerHTML == Ardublockly.LOCALISED_TEXT.ai_module) {
- $("#mode")[0].selectedIndex = 1;
- $("#mode")[0].onchange();
- $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
- // document.getElementById("list").getElementsByTagName("li")[1].onclick();
- }
- $('.MouduleBox')[0].style.display = 'none';
- $('.MouduleBox')[1].style.display = 'none';
- $('#ai_tt')[0].style.display = 'none';
- }
- }
- }
- for (var i = 0; i < $('.ModeBox')[0].children.length; i++) {
- $('.ModeBox')[0].children[i].onclick = function (e) {
- window.event ? window.event.cancelBubble = true : e.stopPropagation()
- }
- }
- for (var i = 0; i < $('.ModeBox1')[0].children.length; i++) {
- $('.ModeBox1')[0].children[i].onclick = function (e) {
- window.event ? window.event.cancelBubble = true : e.stopPropagation()
- }
- }
- $("#repl_delete")[0].onclick = function () {
- $("#repl_box_content")[0].innerHTML = "";
- }
- }
- function clickLoadingExample(name) {
- console.log(name)
- $('#select_Example_modal').modal('close');
- Ardublockly.alertExampleMessage(
- '',
- Ardublockly.getLocalStr('loadBlockBody'),
- true, {});
- readTxt("src/python/" + name, function (txt) {
- if (name.split(".")[1] == "xml") {
- var xmlfile = Blockly.Xml.textToDom(txt);
- blockpy.components.editor.setBlocksFromXml(xmlfile);
- } else {
- blockpy.components.editor.codeMirror.setValue(txt);
- }
- saveLocalStorageBlocks("pythonai-mode-blocks-xml");
- setTimeout(() => {
- $('#loading').css({ 'display': 'none' });
- $('#example_alert').modal('close');
- }, 300)
- });
- }
- function readTxt(url, fun) {
- var xhr = new XMLHttpRequest();
- xhr.open('get', url, true);
- xhr.send();
- xhr.onreadystatechange = function () {
- if (xhr.readyState == 4 && xhr.status == 200) {
- fun(xhr.responseText)
- }
- };
- }
- function serialSwich(type) {
- if (type == 'Serial_Interaction') {
- $('#python_box').addClass('hidden')
- $('#repl_box').removeClass('hidden')
- $('#help_document').addClass('hidden')
- $('#serial_plotter_content').addClass('hidden')
- $('#repl_delete').addClass('hidden')
- document.getElementById('repl_delete').style.display = 'none';
- $('#python_SourceCode').removeClass('switch_select')
- $('#python_SourceCode').addClass('switch_box1')
- $('#Serial_Interaction').removeClass('switch_box1')
- $('#Serial_Interaction').addClass('switch_select')
- $('#serial_plotter').removeClass('switch_select')
- $('#serial_plotter').addClass('switch_box1')
- $('#help_documents').removeClass('switch_select')
- $('#help_documents').addClass('switch_box1')
- } else if (type == 'python_SourceCode') {
- $('#repl_box').addClass('hidden')
- $('#python_box').removeClass('hidden')
- $('#help_document').addClass('hidden')
- $('#serial_plotter_content').addClass('hidden')
- $('#repl_delete').addClass('hidden')
- document.getElementById('repl_delete').style.display = 'none';
- $('#Serial_Interaction').removeClass('switch_select')
- $('#Serial_Interaction').addClass('switch_box1')
- $('#python_SourceCode').removeClass('switch_box1')
- $('#python_SourceCode').addClass('switch_select')
- $('#serial_plotter').removeClass('switch_select')
- $('#serial_plotter').addClass('switch_box1')
- $('#help_documents').removeClass('switch_select')
- $('#help_documents').addClass('switch_box1')
- saveLocalStorageBlocks('pythonai-mode-blocks-xml')
- setTimeout(function () {
- blockpy.components.editor.updateTextFromModel();
- blockpy.components.editor.updateText()
- blockpy.components.editor.unhighlightLines()
- var text = localStorage.getItem('pythonai-mode-blocks-xml')
- var xmlfile = Blockly.Xml.textToDom(text);
- blockpy.components.editor.setBlocksFromXml(xmlfile);
- }, 100)
- } else if (type == 'serial_plotter') {
- $('#repl_box').addClass('hidden')
- $('#python_box').addClass('hidden')
- $('#help_document').addClass('hidden')
- $('#serial_plotter_content').removeClass('hidden')
- $('#help_documents').addClass('hidden')
- document.getElementById('repl_delete').style.display = 'inline-block';
- $('#Serial_Interaction').removeClass('switch_select')
- $('#Serial_Interaction').addClass('switch_box1')
- $('#python_SourceCode').removeClass('switch_select')
- $('#python_SourceCode').addClass('switch_box1')
- $('#serial_plotter').removeClass('switch_box1')
- $('#serial_plotter').addClass('switch_select')
- $('#help_documents').removeClass('switch_select')
- $('#help_documents').addClass('switch_box1')
- } else if (type == 'help_document') {
- $('#repl_box').addClass('hidden')
- $('#python_box').addClass('hidden')
- $('#serial_plotter_content').addClass('hidden')
- $('#help_document').removeClass('hidden')
- $('#repl_delete').addClass('hidden')
- document.getElementById('repl_delete').style.display = 'none';
- $('#Serial_Interaction').removeClass('switch_select')
- $('#Serial_Interaction').addClass('switch_box1')
- $('#python_SourceCode').removeClass('switch_select')
- $('#python_SourceCode').addClass('switch_box1')
- $('#serial_plotter').removeClass('switch_select')
- $('#serial_plotter').addClass('switch_box1')
- $('#help_documents').removeClass('switch_box1')
- $('#help_documents').addClass('switch_select')
- }
- }
- function qiehuanjjj(ele, _container) {
- $("body")[0].addEventListener('click', function (e) {
- if (ele != e.target) {
- _container.className = 'dropdown-content';
- }
- })
- }
- function likeclose(ele, _container, type, _className) {
- $("body")[0].addEventListener('click', function (e) {
- if (ele != e.target && e.target.parentNode != ele) {
- if (type == 1) {
- _container.className = _className;
- } else {
- _container.style.display = 'none'
- }
- }
- })
- }
- function export_data(data, postfix, is_firefox) {
- let url = new Blob([data], { type: 'text/plain' });
- let download_link = URL.createObjectURL(url);
- let a = document.createElement('a');
- a.style = "display:none";
- a.href = download_link;
- a.download = "user_latest_code" + postfix;
- if (is_firefox) {
- document.body.appendChild(a);
- a.click();
- setTimeout(() => document.body.removeChild(a), 100);
- } else
- a.click();
- // URL.revokeObjectURL(download_link);
- // IE edge need a short delay before revoke virtual download link
- setTimeout(() => URL.revokeObjectURL(download_link), 100);
- }
- // 积木生成
- function selectmode(sel, isload) {
- // var _type = 1;
- // if (sel.selectedIndex == 0 && (_type != 0 || isload === true)) {
- saveLocalStorageBlocks("pythonmc-mode-blocks-xml");
- saveLocalStorage("type", 1);
- // $("#changeRunCuploadFilesode").css("display", "inline-block");
- // $("#resetMainUIBtn").css("display", "inline-block");
- blockpy.setAssignment(
- // settings
- {},
- // assignment
- {
- modules: {
- added: ["Decisions", "Iteration", "Calculation", "Variables", "Values", "Lists", "Functions", "Logic", "Loops", "Math", "Text", "Dictionary", "Tuples", "Set", "Functionsa", "Files", "Time", "Serial Comm.", "A.I.Board", "ExtendedFunctions", "AI", "IOT", "system", "ExtendedFunction", "Third_party_Sensor"],
- removed: ['MainBoard']
- }
- },
- // programs
- {
- __main__: ""
- }
- );
- loadLocalStorageBlocks("pythonai-mode-blocks-xml")
- // }
- }
- function getQueryParams() {
- try {
- url = window.location.href;
- query_str = url.substr(url.indexOf("?") + 1, url.length - 1);
- r_params = query_str.split("&");
- params = {};
- for (i in r_params) {
- param = r_params[i].split("=");
- params[param[0]] = param[1];
- }
- return params;
- } catch (e) {
- return {};
- }
- }
- // onresize 多次执行解决办法
- var debounce = function (func, threshold, execAsap) {
- var timeout;
- return function debounced() {
- var obj = this, args = arguments;
- function delayed() {
- if (!execAsap)
- func.apply(obj, args);
- timeout = null;
- };
- if (timeout)
- clearTimeout(timeout);
- else if (execAsap)
- func.apply(obj, args);
- timeout = setTimeout(delayed, threshold || 100);
- };
- }
- // 切换数据显示方式
- var myChart = "";
- function switchSerial(type) {
- if (type == 2) {
- document.getElementById('image_transmission').style.display = 'none';
- document.getElementById('repl_box_content').style.display = 'block';
- // document.getElementById('repl_box_content').innerHTML = ""
- document.getElementsByClassName('translatable_image_transmission')[0].classList.remove("serial-active")
- document.getElementsByClassName('translatable_serial_plotter')[1].classList.add("serial-active")
- } else {
- document.getElementById('image_transmission').style.display = 'block';
- document.getElementById('repl_box_content').style.display = 'none';
- document.getElementsByClassName('translatable_image_transmission')[0].classList.add("serial-active")
- document.getElementsByClassName('translatable_serial_plotter')[1].classList.remove("serial-active")
- // document.getElementById('repl_box_content').innerHTML = ""
- }
- }
- // 点击下载文件
- function fileDownload(url, name) {
- var nowA = document.createElement('a');
- nowA.setAttribute('href', url);
- nowA.setAttribute('download', name);
- nowA.style.display = 'none';
- document.body.appendChild(nowA);
- nowA.click();
- document.body.removeChild(nowA);
- }
- // 点击复制分享链接
- function copyShare() {
- $('#cloudBtn-shares').click(() => {
- if (CCB.userState) {
- let time = 10000
- var $toastContent = $(`<span id="abc">${CCB.str_group.share_loading}</span>`)
- Materialize.toast($toastContent, time, "shareUrl")
- let fileNmae = new Date().getTime()
- $.ajax(`${CCB.base_url}blockx/`, {
- type: "POST",
- xhrFields: {
- withCredentials: true
- },
- data: {
- filename: fileNmae,
- xml: Ardublockly.generateXml()
- },
- success: (res) => {
- let fileobject = {
- filenameId: res.filename,
- filename: fileNmae,
- time: getCurrentDate(),
- timestamp: (new Date()).valueOf()
- };
- CCB.cloudFileList.push(fileobject);
- CCB.selectCloudFile = filename;
- var id = U.UF.C.queryString("Qd");
- var url = window.location.href + '&Qd=' + res.filename;
- if (id) {
- url = window.location.href.replace(/Qd=[0-9a-zA-Z_]+/g, "Qd=" + res.filename);
- }
- let flag = copyText(url);
- // time = 3000;
- // document.getElementById('abc').innerHTML = flag ? CCB.str_group.share_success : CCB.str_group.share_fail
- // setTimeout(function () {
- Materialize.toast(flag ? CCB.str_group.share_success : CCB.str_group.share_fail, 3000, "shareUrl")
- //}, time)
- },
- error: () => {
- $("#cloud_modal_preload").css("display", "none");
- // time = 4000;
- // Materialize.toast(CCB.str_group.error_uploadFile, 4000);
- // document.getElementById('abc').style.display = CCB.str_group.error_uploadFile
- setTimeout(function () {
- Materialize.toast(CCB.str_group.error_uploadFile, 4000)
- }, time)
- }
- });
- } else {
- Materialize.toast(CCB.str_group.requestLogin, 3000);
- $("#login_modal").modal("open")
- }
- })
- }
- String.prototype.isEmpty = function () {
- var s1 = this.replace(/[\r\n]/g, '').replace(/[ ]/g, ''),
- s2 = (s1 == '') ? true : false;
- return s2;
- };
- function isInArray(str, value) {
- var arr = str.split(",");
- for (var i = 0; i < arr.length; i++) {
- if (value === arr[i].replace("\r", "").replace("\r", "")) {
- return true;
- }
- }
- return false;
- }
- function uploadSuccess(data) {
- console.log(data);
- }
- function toHref_own(href) {
- window.open(href + "&lang=" + localStorage.getItem("handPyLanguage"), "_blank");
- }
- function toHref(href) {
- window.open(href + "/?lang=" + localStorage.getItem("handPyLanguage"), "_blank");
- }
- function select_Module(module) {
- if (module == 'AI_module') {
- $('#AI_module').addClass("moduleActive");
- $('#IoT_module').removeClass("moduleActive");
- }
- else {
- $('#IoT_module').addClass("moduleActive");
- $('#AI_module').removeClass("moduleActive");
- }
- }
- function selectModule_confirm() {
- if ($("#AI_module").attr('class') == "moduleActive") {
- $("#mode")[0].selectedIndex = 1;
- $("#mode")[0].onchange();
- $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.ai_module;
- // document.getElementById("list").getElementsByTagName("li")[1].onclick();
- $("#selectModule").modal('close');
- $('#IoT_module').removeClass("moduleActive");
- $('#AI_module').removeClass("moduleActive");
- }
- else if ($("#IoT_module").attr('class') == "moduleActive") {
- $("#mode")[0].selectedIndex = 0;
- $("#mode")[0].onchange();
- $('.selectMode_input')[0].value = Ardublockly.LOCALISED_TEXT.iot_module;
- // document.getElementById("list").getElementsByTagName("li")[0].onclick();
- $("#selectModule").modal('close');
- $('#IoT_module').removeClass("moduleActive");
- $('#AI_module').removeClass("moduleActive");
- }
- }
- function mouseMove() {
- // 拖拉改变右侧上下块的高度
- let PC = document.getElementById('mouseMove')
- let divA = document.getElementById('py-editor')
- let divB = document.getElementById('mouseMove-bottom')
- let midd = document.getElementById('left_move_right')
- let left_midd = document.getElementById('blocks_content')
- let right = document.getElementById('sss')
- // $('#mouseMove').click()
- // window.addEventListener('mousemove', function () {
- PC.onmousedown = function (ev) {
- $('#wabadb_iframe_model').removeClass('hidden')
- // 鼠标按下坐标
- let pX1 = ev.clientX
- let pY1 = ev.clientY
- // 得到两个 div 的高度
- let heightA = divA.clientHeight
- let heightB = divB.clientHeight
- // divB.style.height = '300px'
- document.onmousemove = function (ev) {
- // document.onmousedown = new Function("return false");
- // document.onmouseup = new Function("return true");
- // 鼠标移动是坐标
- let pX2 = ev.clientX
- let pY2 = ev.clientY
- // 计算出鼠标上下移动的距离
- let Y = pY2 - pY1
- if (heightB - Y > 5 && heightA + Y > 60) {
- divB.style.height = heightB - Y + 'px'
- divA.style.height = heightA + Y + 'px'
- }
- }
- //清除
- document.onmouseup = function (ev) {
- $('#wabadb_iframe_model').addClass('hidden')
- document.onmousemove = null;
- document.onmouseup = null;
- }
- }
- midd.onmousedown = function (ev) {
- $('#wabadb_iframe_model').removeClass('hidden')
- let pX1 = ev.clientX
- let pY1 = ev.clientY
- // 得到两个 div 的宽度
- let widthA = left_midd.clientWidth
- let widthB = right.clientWidth
- // divB.style.height = '300px'
- document.onmousemove = function (ev) {
- // 鼠标移动是坐标
- let pX2 = ev.clientX
- let pY2 = ev.clientY
- // 计算出鼠标左右移动的距离
- let Y = pX2 - pX1
- if (Number(widthB - Y) > 425 && widthA + Y > 135) {
- left_midd.style.width = widthA + Y + 'px'
- right.style.width = widthB - Y + 'px'
- // Ardublockly.toogleToolbox()
- setTimeout(function () {
- Blockly.svgResize(blockpy.components.editor.blockly);
- Blockly.svgResize(Blockly.mainWorkspace);
- }, 100)
- }
- }
- //清除
- document.onmouseup = function (ev) {
- $('#wabadb_iframe_model').addClass('hidden')
- document.onmousemove = null;
- document.onmouseup = null;
- }
- }
- // })
- }
- var reconnect = true
- document.addEventListener("visibilitychange", function () {
- // console.log(document.visibilityState);
- if (document.visibilityState == "hidden") {
- console.log('隐藏');
- reconnect = false
- } else if (document.visibilityState == "visible") {
- console.log('显示')
- reconnect = true
- }
- });
- let isWebadb = ''
- let isDevice = ''
- let isConnect = ''
- var bluetoothDevice = ''
- async function addWebadb() {
- if (deviceType == 1) {
- // $("#webadb_connect")[0].disabled = false;
- if ($('#IP').val().length > 0) {
- $('#wifi_process').modal('open');
- console.log(`${$('#IP').val()}:5678`)
- if (window.location.href.split("://")[0] === "https") {
- $("#getIpLink").html(`https://${$('#IP').val()}:5678`)
- } else {
- $("#getIpLink").html(`http://${$('#IP').val()}:5678`)
- }
- } else {
- alert(CCB.str_group.ipAddress)
- }
- // console.log(window.location.origin.indexOf("https"))
- }
- else if (deviceType == 2) {
- bluetoothDevice = await requestDevice();
- }
- else {
- document.getElementById("webadb_iframe").contentWindow.document.getElementById("usbadd").click();
- }
- }
- window.addEventListener('storage', function (e) {
- if (e.key === 'ctc-msg' && !!isConnect) {
- console.log("断开当前页面连接")
- document.getElementById("webadb_iframe").contentWindow.document.getElementById("usbdisconnect").click()
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn
- }
- });
- let autoContent = true
- function addWebadbCorsPage() {
- let dat = new Date()
- window.localStorage.setItem("ctc-msg", JSON.stringify(dat))
- }
- // webadb 连接
- async function webadbConnect() {
- if (deviceType == 1) {
- if ($('#webadb_connect')[0].innerHTML == Ardublockly.LOCALISED_TEXT.connectBtn) {
- connectWebsocket()
- } else {
- ws.close()
- }
- } else if (deviceType == 2) {
- if (bledevice.gatt.connected) {
- bledevice.gatt.disconnect()
- } else {
- bleconnect()
- }
- }
- else {
- await addWebadbCorsPage()
- if (!!isConnect) {
- reconnect = false
- document.getElementById("webadb_iframe").contentWindow.document.getElementById("usbdisconnect").click()
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn
- } else {
- serialSwich('Serial_Interaction')
- document.getElementById("webadb_iframe").contentWindow.document.getElementById("usbconnect").click()
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.disConnect
- autoContent = true
- reconnect = true
- await connectTest()
- }
- }
- }
- function connectTest() {
- // let fileCfgTest = `{ echo "" > /etc/wifi/fileCfgTest && echo "" > /root/fileCfgTest && echo "" > /home/fileCfgTest && echo "" > /tmp/fileCfgTest; } || { sync; fsck.ext4 -y /dev/root; (mount -o remount,rw -n /dev/root / ; mount -o remount,rw -n /dev/mmcblk0p4 / ; mount -o remount,rw -n /dev/mmcblk0p4 /mnt/UDISK ; mount -o remount,rw -n / / ; mount -o remount,rw -n /root / ; ) ; sync ; }`
- setTimeout(() => {
- let webadb_document = document.getElementById('webadb_iframe').contentWindow.getdevice()
- webadb_document.device.subprocess.shell(Repair).then(res => {
- res.stdout.reader.read().then(m => {
- var str = Uint8ArrayToString(m.value);
- console.log(str)
- if (str.indexOf("/bin/sh") > -1 || str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
- $("#webadbErro").css("display", "inline-block")
- // webadb_document.device.subprocess.shell(`mount -o remount,rw /`)
- }
- })
- })
- }, 1000)
- }
- function systemCommand(com) {
- if (deviceType == 1) {
- sendWebsocket(`import os
- os.system("${com}")`, 'run')
- setTimeout(() => {
- ws.close()
- }, 200)
- } else {
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(com).then(function (e) {
- e.stdout.reader.read().then(function (e) {
- // 重启或关机
- $("#webadbErro").css("display", "none")
- })
- }).catch(err => {
- })
- }
- }
- function backHome() {
- if (deviceType == 1) {
- // ws.send(`import os
- // os.system("rm /tmp/disable")`,"run")
- } else if (deviceType == 2) {
- blestop(function (event) {
- console.log("蓝牙结束程序", event)
- })
- }
- else {
- if (isRunCodeData) {
- isRunCodeData.kill().then(() => {
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`rm /tmp/disable`).then(function (e) {
- isRunCodeData = e;
- })
- })
- } else {
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`rm /tmp/disable`).then(function (e) {
- isRunCodeData = e;
- })
- }
- }
- $("#backHome").addClass('disabled')
- }
- // 点击切换更新记录
- function switchUpdate(type) {
- if (type == '1') {
- $('.update-old').css({ display: 'none' })
- $('.update-new').css({ display: 'block' })
- } else {
- $('.update-old').css({ display: 'block' })
- $('.update-new').css({ display: 'none' })
- }
- }
- function Uint8ArrayToString(fileData) {
- const Utf8Decoder = new TextDecoder();
- return Utf8Decoder.decode(fileData);
- // var dataString = "";
- // for (var i = 0; i < fileData.length; i++) {
- // dataString += String.fromCharCode(fileData[i]);
- // }
- // return dataString
- }
- async function fileBlobLoad(text, name, type) {
- // 这么写是因为文件转换是异步任务
- transToFile = async (blob, fileName, fileType) => {
- return new window.File([blob], fileName, { type: fileType })
- }
- let outBlob = new Blob([text], { type: "text/plain;charset=utf-8" })
- const data = await transToFile(outBlob, name, type);
- return data
- }
- function uploadFilesCocoPi(file, fileOut) {
- document.getElementById('webadb_iframe').contentWindow.upload(file, "/root/").then(s => {
- document.getElementById('webadb_iframe').contentWindow.upload(fileOut, "/root/").then(res => {
- $('.progress > .determinate').css('width', '50%');
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "50%"
- clearInterval(RunInterval);
- if (isRunCodeData) {
- isRunCodeData.kill().then(() => {
- run_user_lastet_code()
- })
- }
- else {
- run_user_lastet_code()
- }
- }).catch(err => {
- window.file_manger_modal = true
- })
- }).catch(err => {
- window.file_manger_modal = true
- })
- }
- function run_user_lastet_code() {
- canvasImg = $("#image_transmission_canvas")[0].getContext("2d")
- canImage = new Image();
- //
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`(echo '' > /root/output.log ; touch /tmp/disable) && python -u /root/out.py; `).then(function (e) {
- $("#webadbErro").css("display", "none")
- isRunCodeData = e;
- _data = "";
- _ti = "";
- serverPrint(e)
- RunInterval = setInterval(() => {
- serverPrint(e)
- }, 50);
- setTimeout(function () {
- $("#webadbErro").css("display", "none")
- window.file_manger_modal = true
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
- $('.progress > .determinate').css('width', '100%');
- $("#runCode").removeClass('disabled')
- $("#uploadpy").removeClass('disabled')
- $("#resetDevice").removeClass('disabled')
- $("#poweroff").removeClass('disabled')
- window.file_manger_modal = true
- }, 2000);
- }).catch(err => {
- window.file_manger_modal = true
- })
- }
- var _data = "";
- var _ti;
- var canvasImg = "";
- var canImage = "";
- function serverPrint(e) {
- e.stdout.reader.read().then(function (e) {
- if (e.value) {
- clearTimeout(_ti);
- _data += Uint8ArrayToString(e.value);
- _ti = setTimeout(function () {
- showServal(_data)
- _data = "";
- }, 10)
- }
- }).catch(err => {
- $('.progress > .determinate').css('width', 0);
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
- })
- if (isRunCodeData) {
- if (isRunCodeData.stdout.readable._state != 'readable') {
- $('#backHome').addClass('disabled')
- clearInterval(RunInterval)
- backHome()
- }
- else {
- $('#backHome').removeClass('disabled')
- }
- }
- }
- function showServal(_data) {
- if (_data.indexOf('data:image/jpg;base64') > -1) {
- try {
- canImage.src = _data;
- canImage.onload = () => {
- canvasImg.drawImage(canImage, 0, 0, 300, 150)
- }
- }
- catch (e) {
- }
- } else {
- let errMsg = ""
- let errData = ""
- let c = ''
- if (_data.indexOf(`camera`) == -1 && _data.length < 500) {
- if (_data.indexOf("/bin/sh:") > -1 || _data.indexOf("No such file or directory") > -1 || _data.indexOf("Read-only file system") > -1) {
- $("#webadbErro").css("display", "inline-block")
- }
- let b = _data.split('\r\n')
- for (let i = 0; i <= b.length - 1; i++) {
- c += `<div>${b[i]}</div>`
- }
- $('#repl_box_content').append(c);
- repl_box_contentheight = $("#repl_box_content")[0].scrollHeight;
- $("#repl_box_content").scrollTop(repl_box_contentheight);
- }
- if (_data.indexOf(`NameError`) > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_pv}`)
- } else if (_data.indexOf("IndentationError") > -1 || _data.indexOf("SyntaxError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_unindent}`)
- } else if (_data.indexOf("IndexError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.IndexError}`)
- } else if (_data.indexOf("AttributeError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.AttributeError}`)
- } else if (_data.indexOf("TypeError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_unindent}`)
- } else if (_data.indexOf("KeyError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.KeyError}`)
- } else if (_data.indexOf("Read-only file system:") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.OsError}`)
- } else if (_data.indexOf("FileNotFoundError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.ENOEN}`)
- } else if (_data.indexOf(`File "/tmp/event"`) > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_unindent}`)
- }
- }
- }
- var repl_box_contentheight = 0
- function getQrCode() {
- document.getElementById("codeImg").innerHTML = ""
- let browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
- let qrCode = ""
- if (browserWidth < 500) {
- qrCode = new QRCode(document.getElementById("codeImg"), {
- width: 150,
- height: 150
- })
- } else {
- qrCode = new QRCode(document.getElementById("codeImg"), {
- width: 200,
- height: 200
- })
- }
- let SSID = $('#SSID').val()
- let PASS = $('#PAS').val()
- if (SSID == "" && PASS == "") {
- alert(Ardublockly.LOCALISED_TEXT.SSIDPWD)
- return
- }
- console.log(`SSID:${SSID};PASS:${PASS}`)
- qrCode.makeCode(`SSID:${SSID};PASS:${PASS}`)
- }
- var ws = ''
- var WifiContent = 'close';
- let ifconfig = "wifi_get_connection_info_test 1 > /root/event.log &";
- // let ifconfig = `import os
- // cmd = "wifi_get_connection_info_test 1"
- // res = os.popen(cmd).read()
- // print("res",res)
- // `
- function connectWebsocket(type) {
- ws = new WebSocket(`wss://${$('#IP').val()}:5678`);
- WifiContent = type
- ws.onopen = () => {
- // console.log('连接服务端WebSocket成功');
- $('#repl_box_content').append(`<div>${CCB.str_group.connection_success}</div>`);
- serialSwich('serial_plotter')
- $("#runCode").removeClass('disabled')
- $("#uploadpy").removeClass('disabled')
- $("#resetDevice").removeClass('disabled')
- $("#poweroff").removeClass('disabled')
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.disConnect
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusbar
- $('#cnt_icon').css('display', 'inline-block')
- $('#discnt_icon').css('display', 'none')
- $('#select-connected').attr("disabled", true)
- setTimeout(() => {
- //sendWebsocket(ifconfig,"run")
- ws.send(ifconfig)
- }, 1000)
- };
- // 监听服务端消息(接收消息)
- ws.onmessage = (msg) => {
- $('#repl_box_content').append(`<div>${msg.data}</div>`);
- repl_box_contentheight = $("#repl_box_content")[0].scrollHeight;
- $("#repl_box_content").scrollTop(repl_box_contentheight);
- };
- // 监听连接失败
- ws.onerror = () => {
- // console.log('连接失败,正在重连...');
- $('.progress > .determinate').css('width', '0');
- $('#repl_box_content').append(`<div>${CCB.str_group.connection}</div>`);
- // connectWebsocket();
- };
- // 监听连接关闭
- ws.onclose = () => {
- $('#repl_box_content').append(`<div>${CCB.str_group.disconnect}</div>`);
- // console.log('连接关闭');
- $('#cnt_icon').css('display', 'none')
- $('#discnt_icon').css('display', 'inline-block')
- $('#select-connected').attr("disabled", false)
- setTimeout(() => {
- $("#webadb_connect")[0].disabled = false;
- $("#webadb_add")[0].disabled = false;
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusNotConn
- $("#runCode").addClass('disabled')
- $("#uploadpy").addClass('disabled')
- $("#resetDevice").addClass('disabled')
- $("#backHome").addClass('disabled')
- $("#poweroff").addClass('disabled')
- $('#message_file').css({ display: 'none' })
- $('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
- $('.progress > .determinate').css('width', 0);
- $("status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
- }, 500)
- };
- };
- function sendWebsocket(file, type) {
- canvasImg = $("#image_transmission_canvas")[0].getContext("2d")
- canImage = new Image()
- // console.log(file)
- // ws.send('ls')
- // ws.send(`echo '${file}' > user_latest_code.py && ln -sf /root/user_latest_code.py /tmp/event && touch /tmp/disable && python /tmp/event`)
- if (type == "run") {
- 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`)
- } else {
- ws.send(`echo '${file}' > /root/user_latest_code.py`)
- }
- ws.onmessage = (msg) => {
- if (msg.data.indexOf('data:image/jpg;base64') > -1) {
- try {
- canImage.src = msg.data;
- canImage.onload = () => {
- canvasImg.drawImage(canImage, 0, 0, 300, 150)
- }
- }
- catch (e) {
- }
- } else {
- if (_data.indexOf(`NameError`) > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
- $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_pv}`)
- } else if (_data.indexOf("IndentationError") > -1 || _data.indexOf("SyntaxError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
- $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.error_unindent}`)
- } else if (_data.indexOf("IndexError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
- $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.IndexError}`)
- } else if (_data.indexOf("AttributeError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
- $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.AttributeError}`)
- } else if (_data.indexOf("TypeError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
- $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${errMsg[1]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.TypeError}`)
- } else if (_data.indexOf("KeyError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- let errMsg = _data.slice(_data.indexOf(`File "/tmp/event", line`)).split('\r\n')
- $("#err-msg").text(`${errMsg[0]}\n${errMsg[1]}\n${errMsg[2]}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.KeyError}`)
- } else if (_data.indexOf("Read-only file system:") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.OsError}`)
- } else if (_data.indexOf("FileNotFoundError") > -1) {
- setTimeout(() => {
- $("#error-btn").css("display", "block")
- $('.card-reveal').css({ 'display': 'block', 'transform': 'translateY(-100%)', 'padding': '8px 13px' });
- }, 500)
- errMsg = _data.split('\r\n')
- for (let i = 0; i <= errMsg.length - 1; i++) {
- errData += `${errMsg[i]}\n`
- }
- $("#err-msg").text(`${errData}\n${CCB.str_group.errSol}\n${Ardublockly.LOCALISED_TEXT.ENOEN}`)
- }
- // modName ,tag,branch,commit,author
- 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
- if (!a) {
- $('#repl_box_content').append(`<div>${msg.data}</div>`);
- repl_box_contentheight = $("#repl_box_content")[0].scrollHeight;
- $("#repl_box_content").scrollTop(repl_box_contentheight);
- }
- // $('.progress > .determinate').css('width', '100%');
- }
- // $("#backHome").removeClass('disabled')
- $('.progress > .determinate').css('width', '100%');
- };
- // setTimeout(function () {
- $('.progress > .determinate').css('width', '100%');
- $("#runCode").removeClass('disabled')
- $("#uploadpy").removeClass('disabled')
- $("#resetDevice").removeClass('disabled')
- $("#poweroff").removeClass('disabled')
- // }, 2000);
- }
- function mobileSwitchMode(type) {
- if (type == 'python') {
- $('.mobileSwitch')[0].style.display = "block"
- $('.mobileSwitch')[1].style.display = "none"
- $('#blocks_content')[0].style.display = "block"
- $('#py-editor')[0].style.display = "none"
- $('#sss')[0].style.height = 'fit-content'
- } else {
- $('.mobileSwitch')[1].style.display = "block"
- $('.mobileSwitch')[0].style.display = "none"
- $('#blocks_content')[0].style.display = "none"
- $('#py-editor')[0].style.display = "block"
- $('#sss')[0].style.height = '100%'
- }
- setTimeout(function () {
- blockpy.components.editor.updateTextFromModel();
- blockpy.components.editor.updateText()
- blockpy.components.editor.unhighlightLines()
- var text = localStorage.getItem('pythonai-mode-blocks-xml')
- var xmlfile = Blockly.Xml.textToDom(text);
- blockpy.components.editor.setBlocksFromXml(xmlfile);
- }, 100)
- }
- function linkOkay() {
- $("#webadb_connect")[0].disabled = false;
- console.log(`https://${$('#IP').val()}:5678`)
- if (window.location.href.split("://")[0] === "https") {
- window.open(`https://${$('#IP').val()}:5678`, '_blank');
- } else {
- window.open(`http://${$('#IP').val()}:5678`, '_blank');
- }
- $('#wifi_process').modal('close');
- }
- // 跨网页复制
- document.addEventListener("paste", function (event) {
- if ((event.clipboardData || event.originalEvent)) {
- var clipboardData = (event.clipboardData || window.clipboardData);
- var val = clipboardData.getData('text');
- // console.log(Blockly.Xml.workspaceToDom(blockpy.components.editor.blockly))
- // let a = val.substr(0,7)+val.substr(44,val.length)
- let c = Blockly.Xml.textToDom(val)
- Blockly.clipboardSource_ = blockpy.components.editor.blockly
- Blockly.clipboardSource_.paste(c)
- // event.preventDefault();
- }
- });
- function loadingXml(result_xml) {
- var success = Ardublockly.replaceBlocksfromXml(result_xml);
- if (!success) {
- Ardublockly.alertMessage(Ardublockly.getLocalStr('ErrorBlockTitle'), Ardublockly.getLocalStr('ErrorBlockBody'), false);
- }
- }
- function getLoadXmlStr() {
- var xml = Blockly.Xml.workspaceToDom(blockpy.components.editor.blockly);
- var XmlStr = Blockly.Xml.domToText(xml);
- return XmlStr
- }
- // 一键更新固件
- async function OneClickUpgrade() {
- let text = `import os
- os.system("cd root/user && mkdir model && chmod 777 *")
- os.system("cd /")
- os.system("rm /etc/banner")
- os.system("mv /root/banner /etc/")
- os.system("sync && reboot")
- `
- let strText = `import os
- import sys
- import traceback
- import logging
- logger = logging.getLogger()
- logger.setLevel(logging.INFO)
- file_handler = logging.FileHandler('/root/output.log')
- file_handler.setLevel(logging.INFO)
- formatter = logging.Formatter('%(message)s')
- file_handler.setFormatter(formatter)
- logger.addHandler(file_handler)
- def log_output(*args, **kwargs):
- output = ' '.join(map(str, args))
- logger.info(output.strip(), **kwargs)
- sys.stderr.write = sys.stdout.write = log_output
- os.close(1)
- os.close(2)
- try:
- source_code = r'''${text}
- '''
- exec(source_code)
- except Exception as e:
- error_info = traceback.format_exc()
- print(error_info)
- `;
- //let textContain =
- // console.log(strText)
- let file = await fileBlobLoad(strText, "event", "text/plain")
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`echo "" > /root/fileCfgTest`).then(r => {
- setTimeout(function () {
- window.file_manger_modal = true
- r.stdout.reader.read().then(m => {
- var str = Uint8ArrayToString(m.value);
- if (str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
- //错误处理
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`mount -o remount -rw /dev/mmcblk0p4`).then(r => {
- uploadFilesCocoPi(file, "")
- }).catch(err => {
- $('.progress > .determinate').css('width', 0);
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
- })
- }
- else {
- // 没有错误处理
- uploadFilesCocoPi(file, "")
- }
- }).catch(n => {
- console.log(n)
- })
- }, 100)
- }).catch(err => {
- console.log(err)
- })
- }
- // 一键更新CocoPi文件
- async function CocoPiUpgrades() {
- // const appLangJsLoad = document.createElement('script');
- const request = createAjaxRequest();
- const appLangJdPath = `CocoPi.js`;
- try {
- request.open('GET', appLangJdPath, false);
- request.send('');
- let file = await fileBlobLoad(request.responseText, "CocoPi.py", "text/plain")
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`echo "" > /etc/wifi/fileCfgTest && echo "" > /root/fileCfgTest && echo "" > /home/fileCfgTest && echo "" > /tmp/fileCfgTest`).then(r => {
- setTimeout(function () {
- window.file_manger_modal = true
- r.stdout.reader.read().then(m => {
- var str = Uint8ArrayToString(m.value);
- if (str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
- //错误处理
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`mount -o remount -rw /dev/mmcblk0p4`).then(r => {
- uploadFilesCocoPi("", file)
- }).catch(err => {
- $('.progress > .determinate').css('width', 0);
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
- })
- }
- else {
- // 没有错误处理
- uploadFilesCocoPi("", file)
- }
- }).catch(n => {
- console.log(n)
- })
- }, 100)
- }).catch(err => {
- console.log(err)
- })
- // appLangJsLoad.text = request.responseText;
- } catch (e) {
- // But still asynchronous lazy load so at least some text gets translated
- // appLangJsLoad.src = appLangJdPath;
- }
- }
- const decounce = function (fn, delay) {
- let timer = null
- return function () {
- const context = this
- let args = arguments
- clearTimeout(timer) // 每次调用debounce函数都会将前一次的timer清空,确保只执行一次
- timer = setTimeout(() => {
- fn.apply(context, args)
- }, delay)
- }
- }
- function uploadpyCocoPi() {
- $('.progress > .determinate').css('width', 0);
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution
- setTimeout(async () => {
- window.file_manger_modal = false
- $("#runCode").addClass('disabled')
- $("#uploadpy").addClass('disabled')
- $("#resetDevice").addClass('disabled')
- $("#poweroff").addClass('disabled')
- $("#backHome").addClass('disabled')
- // 上传
- let text = pythonnewcode || Blockly.Python.workspaceToCode(blockpy.components.editor.blockly) || blockpy.components.editor.codeMirror.getValue()
- // 开始上传
- let textContain = fileBlobLoad(text, "user_latest_code.py", "text/plain")
- if (deviceType == 1) {
- sendWebsocket(text, 'upload')
- } else if (deviceType == 2) {
- $('.progress > .determinate').css('width', '50%');
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "50%"
- bluetoothUpload(text, true)
- }
- else {
- // 转换完成后可以将file对象传给接口
- textContain.then((res) => {
- let file = res;
- // window.stateapi.upload(file,"/root/")
- $('.progress > .determinate').css('width', '50%');
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "50%"
- setTimeout(() => {
- if (file) {
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(Repair).then(r => {
- setTimeout(function () {
- r.stdout.reader.read().then(m => {
- var str = Uint8ArrayToString(m.value);
- if (str.indexOf("/bin/sh:") > -1 || str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
- $("#webadbErro").css("display", "inline-block")
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`rm /root/user_latest_code.py`).then(s => {
- //错误处理
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(Repair1).then(r => {
- $("#webadbErro").css("display", "none")
- document.getElementById('webadb_iframe').contentWindow.upload(file, "/root/").then(s => {
- $('.progress > .determinate').css('width', '100%');
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
- })
- }).catch(err => {
- $('.progress > .determinate').css('width', 0);
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
- })
- })
- }
- else {
- $("#webadbErro").css("display", "none")
- // 没有错误处理
- document.getElementById('webadb_iframe').contentWindow.upload(file, "/root/").then(s => {
- $('.progress > .determinate').css('width', '100%');
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
- })
- }
- }).catch(n => {
- console.log(n)
- })
- }, 100)
- }).catch(err => {
- console.log(err)
- })
- } else {
- $('.progress > .determinate').css('width', 0);
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
- }
- window.file_manger_modal = true
- $("#runCode").removeClass('disabled')
- $("#uploadpy").removeClass('disabled')
- $("#resetDevice").removeClass('disabled')
- $("#poweroff").removeClass('disabled')
- }, 500)
- })
- }
- }, 1000)
- }
- 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) ; } ; `
- var Repair1 = Repair;
- //`mount -o remount -rw /dev/mmcblk0p4 && fsck.ext4 -p /dev/root && mount -o remount -o rw /dev/root && mount -o remount,rw -n / && mount -o remount,rw -n /home && mount -o remount,rw -n /root && sleep 1;`
- async function runCocoPi() {
- let text = pythonnewcode || Blockly.Python.workspaceToCode(blockpy.components.editor.blockly) || blockpy.components.editor.codeMirror.getValue() || ""
- if (text == "\n") {
- return true
- }
- text = `import time
- from maix import *
- import gc
- import os
- import sys
- sys.path.append('/root/')
- from CocoPi import BUTTON
- from CocoPi import stm8s
- from CocoPi import multiFuncGpio
- from CocoPi import singleRgb
- from CocoPi import LED
- gc.enable()
- gc.collect()
- iic_slaver=stm8s()
- iic_slaver.clear()
- PIXEL_LED1= multiFuncGpio(0,0)
- PIXEL_LED2= multiFuncGpio(1,0)
- PIXEL_LED1.pixelInit_()
- PIXEL_LED2.pixelInit_()
- time.sleep(0.1)
- L1=singleRgb()
- L1.setColor(0,0,0)
- L1.show()
- time.sleep(0.2)
- L2=LED()
- L2.out(0)
- del iic_slaver
- del PIXEL_LED1
- del PIXEL_LED2
- del L1
- del L2
- ${text}`
- window.file_manger_modal = false
- autoContent = false
- $("#runCode").addClass('disabled')
- $("#uploadpy").addClass('disabled')
- $("#resetDevice").addClass('disabled')
- $("#poweroff").addClass('disabled')
- $("#backHome").addClass('disabled')
- $('.progress > .determinate').css('width', 0);
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution
- $("#error-btn").css("display", "none")
- let strText = `import traceback
- import logging
- import sys
- import os
- import time
- logger = logging.getLogger()
- logger.setLevel(logging.INFO)
- file_handler = logging.FileHandler('/root/output.log')
- file_handler.setLevel(logging.INFO)
- formatter = logging.Formatter('%(message)s')
- file_handler.setFormatter(formatter)
- logger.addHandler(file_handler)
- def log_output(*args, **kwargs):
- output = ' '.join(map(str, args))
- logger.info(output.strip(), **kwargs)
- sys.stderr.write = sys.stdout.write = log_output
- os.close(1)
- os.close(2)
- try:
- source_code = r'''${text}
- '''
- exec(source_code)
- except Exception as e:
- error_info = traceback.format_exc()
- print(error_info)
- `;
- //let textContain =
- // console.log(strText)
- let file = await fileBlobLoad(strText, "event", "text/plain")
- let out = `import asyncio
- import subprocess
- import linecache
- async def tailf(filename):
- command = "python -u /root/event"
- process = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
- print("")
- while True:
- await asyncio.sleep(0.03)
- try:
- linecache.clearcache()
- logarr = linecache.getlines(filename)[-20:]
- if len(logarr) == 0:
- if process.poll() is None:
- continue
- else:
- return
- open(filename, 'w').close()
- print("".join(logarr).strip())
- except asyncio.TimeoutError:
- pass
- filename = "/root/output.log"
- loop = asyncio.get_event_loop()
- loop.run_until_complete(tailf(filename))
- loop.close()
- `
- let fileOut = await fileBlobLoad(out, "out.py", "text/plain")
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution
- if (deviceType == 1) {
- // 无线连接
- sendWebsocket(text, 'run')
- $('.progress > .determinate').css('width', '50%');
- // $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "50%"
- } else if (deviceType == 2) {
- $('.progress > .determinate').css('width', '20%');
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.InExecution + "20%"
- bluetoothUpload(text, false)
- }
- else {
- document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(Repair).then(r => {
- setTimeout(function () {
- r.stdout.reader.read().then(m => {
- var str = Uint8ArrayToString(m.value);
- //
- if (str.indexOf("/bin/sh:") > -1 || str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1) {
- // uploadFilesCocoPi(file, fileOut)
- $("#webadbErro").css("display", "inline-block")
- // $('.progress > .determinate').css('width', 0);
- // $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
- // window.file_manger_modal = true
- uploadFilesCocoPi(file, fileOut)
- //错误处理
- // document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(Repair1).then(r => {
- // $("#webadbErro").css("display", "none")
- // uploadFilesCocoPi(file, fileOut)
- // }).catch(err => {
- // })
- }
- else {
- // 没有错误处理
- $("#webadbErro").css("display", "none")
- uploadFilesCocoPi(file, fileOut)
- }
- }).catch(n => {
- console.log(n)
- window.file_manger_modal = true
- })
- }, 100)
- }).catch(err => {
- console.log(err)
- window.file_manger_modal = true
- })
- }
- }
- // bledevice.gatt.connected 连接状态
- // bledevice.gatt.disconnect() 断开连接
- // device.gatt.connect() 蓝牙连接
- // 蓝牙上传
- function bluetoothUpload(text, UploadOrRun) {
- let value = 0
- bleuploadfile("/root/user_latest_code.py", text, function (event) {
- if (event == true) {
- console.log("上传成功", event)
- value++
- if (UploadOrRun && value == 1) {
- $('.progress > .determinate').css('width', '75%');
- setTimeout(() => {
- $('.progress > .determinate').css('width', '100%');
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
- }, 500);
- } else if (value == 1) {
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "50%"
- $('.progress > .determinate').css('width', '50%');
- setTimeout(() => {
- bluetoothRun()
- }, 1000)
- }
- }
- })
- }
- let repl_box_content_str = ''
- // 蓝牙运行
- function bluetoothRun() {
- blerun('/root/user_latest_code.py', function (rechex, isrun) {
- //const rechex = new TextDecoder().decode(event.target.value.buffer);
- let a = `<div>${rechex}</div>`
- $('#repl_box_content').append(a);
- repl_box_contentheight = $("#repl_box_content")[0].scrollHeight;
- $("#repl_box_content").scrollTop(repl_box_contentheight);
- console.log(rechex, "蓝牙运行", isrun)
- if (isrun) {
- $("#backHome").addClass('disabled')
- } else {
- $("#backHome").removeClass('disabled')
- }
- setTimeout(() => {
- $('.progress > .determinate').css('width', '100%');
- $("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully
- }, 300);
- })
- }
- var switch_connect = false
- // 切换是否自动连接
- function SwitchConnect() {
- console.log($("#SwitchConnectInput")[0].checked)
- if ($("#SwitchConnectInput")[0].checked) {
- $("#SwitchConnectInput")[0].checked = true
- localStorage.setItem("SwitchConnect", true)
- switch_connect = true
- } else {
- $("#SwitchConnectInput")[0].checked = false
- localStorage.setItem("SwitchConnect", false)
- switch_connect = false
- }
- }
- var getBlocksByTypeName = function (typeName) {
- var blocks = blockpy.components.editor.getBlocksFromXml().getElementsByTagName("block"); // 获取工作区中的所有块
- var filteredBlocks = [];
- // 遍历所有块,筛选出具有指定类型的块
- for (var i = 0; i < blocks.length; i++) {
- if (blocks[i].getAttribute("type") === typeName) {
- filteredBlocks.push(blocks[i]);
- }
- }
- return filteredBlocks;
- };
- /*import os
- os.system("cd root/user && mkdir model && chmod 777 *")
- os.system("cd /")
- os.system("rm /etc/banner")
- os.system("mv /root/banner /etc/")
- os.system("sync && reboot")
- from evdev import InputDevice, categorize, ecodes
- # 获取键盘设备
- keyboard = InputDevice('/dev/input/eventX') # 替换成实际的键盘设备路径
- # 获取鼠标设备
- mouse = InputDevice('/dev/input/eventY') # 替换成实际的鼠标设备路径
- # 读取事件
- for event in keyboard.read_loop():
- if event.type == ecodes.EV_KEY:
- key_event = categorize(event)
- if key_event.keystate == key_event.key_down:
- print(f"Key pressed: {key_event.keycode}")
- for event in mouse.read_loop():
- if event.type == ecodes.EV_KEY:
- print(f"Mouse button pressed: {event.code}")
- elif event.type == ecodes.EV_REL:
- if event.code == ecodes.REL_X:
- print(f"Mouse X movement: {event.value}")
- elif event.code == ecodes.REL_Y:
- print(f"Mouse Y movement: {event.value}")
- */
|