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();
}, 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';
// $('.translatable_editing')[0].style.display = "none";
// $('.translatable_close_editing')[0].style.display = "inline-block"
} else {
$('#edit')[0].style.display = 'block';
// $('.translatable_editing')[0].style.display = "inline-block";
// $('.translatable_close_editing')[0].style.display = "none"
}
})
$("#webadbErro").click(() => {
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")
}
// 重启修复
})
}).catch(err => {
})
})
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();
// const codes = $(".CodeMirror-code pre");
// let target = "";
// for (let i = 0; i < codes.length; i++) {
// let line = codes[i].textContent;
// !(line.length === 1 && line.charCodeAt(0) === 8203) ? target += line : "";
// i !== codes.length - 1 ? target += "\n" : "";
// }
// return target;
}
});
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';
$("#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';
$("#blockpy-content .card-header > img.fullscreenIcon").toggleClass("hidden");
$("html").toggleClass("fullscreenMode");
setTimeout(() => $(".blockpy-toolbar > .blockpy-text")
.css("height", "90%")
.css("height", "100%"), 0);
});
// 提示全屏
// setTimeout(() => {
// // if (document.body.clientWidth < 1265) {
// // alert(CCB.str_group.alert)
// // }
// myChart = echarts.init(document.getElementById('echartsMain'));
// window.onresize = function () {
// myChart.resize();
// }
// }, 1000)
// 加载echarts
// myChart = myChart = echarts.init(document.getElementById('echartsMain'));
// window.onresize = function () {
// myChart.resize();
// }
// 点击复制分享链接
copyShare()
window.file_manger_modal = true
document.getElementById("webadb_iframe").onload = function () {
setInterval(function () {
if (document.getElementById("webadb_iframe").contentWindow.getdevice && window.file_manger_modal && !isWifiContent) {
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')
$('#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')
}
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')
$('#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')
if (reconnect) {
webadbConnect();
}
}
else if (isDevice.device != undefined && isDevice.selectdevice != undefined) {
$("#webadb_add")[0].disabled = true;
if (!!isConnect) {
$('#cnt_icon').css('display', 'inline-block')
$('#discnt_icon').css('display', 'none')
$('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.disConnect
$("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.statusbar
$("#webadb_connect")[0].disabled = false;
$('#message_file').css({ display: 'inline-block' })
$("#runCode").removeClass('disabled')
$("#uploadpy").removeClass('disabled')
$("#resetDevice").removeClass('disabled')
$("#poweroff").removeClass('disabled')
} else {
$('#webadb_connect')[0].innerHTML = Ardublockly.LOCALISED_TEXT.connectBtn;
$("#webadb_connect")[0].disabled = true;
$('#message_file').css({ display: 'none' })
}
}
}
}, 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 = `
${updateNew.blocks[i]}`
blocklLis = blocklLis + blockLi
}
$('#blockLis').append(blocklLis)
for (let i = 0; i < updateNew.example.length; i++) {
let exampleLi = `${updateNew.example[i]}`
exampleLis = exampleLis + exampleLi
}
$('#exampleLis').append(exampleLis)
for (let i = 0; i < updateNew.note.length; i++) {
let noteLi = `${updateNew.note[i]}`
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 = `${data.time}
`;
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 = `${updateData.blocks[i]}`
blocklLisOld = blocklLisOld + blockLi
}
for (let i = 0; i < updateData.example.length; i++) {
let exampleLi = `${updateData.example[i]}`
exampleLisOld = exampleLisOld + exampleLi
}
for (let i = 0; i < updateData.note.length; i++) {
let noteLi = `${updateData.note[i]}`
noteLisOld = noteLisOld + noteLi
}
leftStr = leftStr + `${time}积木样例`
noteStr = noteStr + `${time}${noteLisOld}`
}
$('#leftUpdateOld').append(leftStr)
$('#noteLisOld').append(noteStr)
// $("#root").modal("open");
setTimeout(() => {
// // if (isUpdate < 2) {
// $("#select_Example_modal").modal("close");
// $("#loadModal").modal("open");
// localStorage.setItem('isUpdate', Number(isUpdate) + 1)
// // }
}, 3000);
}
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;
// $('#ai_tt div')[0].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_thw;
// $('#ai_tt div')[1].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_thwos;
// $('#ai_tt div')[2].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_uoc;
// $('#ai_tt div')[3].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_mc;
// $('#ai_tt div')[4].innerHTML = Ardublockly.LOCALISED_TEXT.ai_modules_sor;
}
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')
} 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')
// 进行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[7].style.display = "block";
}
else if (this.id == 2) {
for (var k = 0, len = exampleList.length; k < len; k++) {
exampleList[k].style.display = "none";
}
exampleList[10].style.display = "block";
}
else if (this.id == 3) {
for (var k = 0, len = exampleList.length; k < len; k++) {
exampleList[k].style.display = "none";
}
exampleList[12].style.display = "block";
}
else if (this.id == 4) {
for (var k = 0, len = exampleList.length; k < len; k++) {
exampleList[k].style.display = "none";
}
exampleList[14].style.display = "block";
}
else if (this.id == 5) {
for (var k = 0, len = exampleList.length; k < len; k++) {
exampleList[k].style.display = "none";
}
exampleList[21].style.display = "block";
}
else if (this.id == 6) {
for (var k = 0, len = exampleList.length; k < len; k++) {
exampleList[k].style.display = "none";
}
exampleList[26].style.display = "block";
}
else {
for (var k = 0, len = exampleList.length; k < len; k++) {
exampleList[k].style.display = "none";
}
exampleList[31].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) {
console.log(txt)
if (name.split(".")[1] == "xml") {
var xmlfile = Blockly.Xml.textToDom(txt);
blockpy.components.editor.setBlocksFromXml(xmlfile);
} else {
blockpy.components.editor.codeMirror.setValue(txt);
}
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')
$('#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')
} else if (type == 'python_SourceCode') {
$('#repl_box').addClass('hidden')
// $('#python_box').removeClass('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')
} else if (type == 'serial_plotter') {
$('#repl_box').addClass('hidden')
// $('#python_box').addClass('hidden')
$('#serial_plotter_content').removeClass('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')
}
}
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", "Output", "Files", "Time", "Serial Comm.", "A.I.Board", "ExtendedFunctions", "AI", "IOT", "system"],
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);
};
}
// window.onresize = debounce(function () {
// if (document.body.clientWidth < 1265) {
// alert(CCB.str_group.alert)
// }
// }, 100, true);
// 切换数据显示方式
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 = $(`${CCB.str_group.share_loading}`)
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")
}
})
}
function enterNext(value) {
$("#select_folder").html('')
var path = getLocalStorage("path") + value;
// 获取 sd 卡的路径
saveLocalStorage("path", path + '/');
saveLocalStorage("fileAndFolder", '');
pythoncmdselect(getLocalStorage("path"), function (data) {
if (data.responseText != null) {
var arr = data.responseText.split("\n");
saveLocalStorage("fileAndFolder", arr);
var str = '';
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i].indexOf(".") != -1) {
var aa = arr[i].replace("\r", "").replace("\r", "");
str += '
';
str += '
';
str += '
';
str += '
';
}
else {
var aa = arr[i].replace("\r", "").replace("\r", "");
str += '
';
str += '
';
str += '
';
str += '
';
}
}
if ((arr.length - 1) % 4 == 1) {
str += '
';
}
else if ((arr.length - 1) % 4 == 2) {
str += '
';
}
else if ((arr.length - 1) % 4 == 3) {
str += '
';
}
str += '
';
$("#select_folder").html(str)
}
})
$("#return_folder").css("display", "inline-block");
}
function deleteFile(value) {
$("#select_folder").html('')
$('#cancle_delete').css('display', 'none');
$("#delete_folder").css('display', 'inline-block');
var path = getLocalStorage("path") + value;
saveLocalStorage("fileAndFolder", '');
// 获取 sd 卡的路径
pythoncmddel(path, function (data) {
if (data.responseText != null) {
var arr = data.responseText.split("\n");
saveLocalStorage("fileAndFolder", arr);
var str = '';
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i].indexOf(".") != -1) {
var aa = arr[i].replace("\r", "").replace("\r", "");
str += '
';
str += '
';
str += '
';
str += '
';
}
else {
var aa = arr[i].replace("\r", "").replace("\r", "");
str += '
';
str += '
';
str += '
';
str += '
';
}
}
if ((arr.length - 1) % 4 == 1) {
str += '
';
}
else if ((arr.length - 1) % 4 == 2) {
str += '
';
}
else if ((arr.length - 1) % 4 == 3) {
str += '
';
}
str += '
';
$("#select_folder").html(str)
}
})
}
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 deleteFileOrFolder() {
if (!$("#select_folder").html().isEmpty()) {
$('.deleteImg').css('display', 'block');
$('#cancle_delete').css('display', 'inline-block');
$("#delete_folder").css('display', 'none');
}
}
function cancelDeleteFileOrFolder() {
if (!$("#select_folder").html().isEmpty()) {
$('.deleteImg').css('display', 'none');
$('#cancle_delete').css('display', 'none');
$("#delete_folder").css('display', 'inline-block');
}
}
function return_pre_folder() {
$("#select_folder").html('');
var path = getLocalStorage("path").split("/").slice(0, -2).join("/") + '/';
// 获取 sd 卡的路径
saveLocalStorage("path", path);
pythoncmdselect(path, function (data) {
if (data.responseText != null) {
var arr = data.responseText.split("\n");
saveLocalStorage("fileAndFolder", arr);
var str = '';
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i].indexOf(".") != -1) {
var aa = arr[i].replace("\r", "").replace("\r", "");
str += '
';
str += '
';
str += '
';
str += '
';
}
else {
var aa = arr[i].replace("\r", "").replace("\r", "");
str += '
';
str += '
';
str += '
';
str += '
';
}
}
if ((arr.length - 1) % 4 == 1) {
str += '
';
}
else if ((arr.length - 1) % 4 == 2) {
str += '
';
}
else if ((arr.length - 1) % 4 == 3) {
str += '
';
}
str += '
';
$("#select_folder").html(str)
}
})
if (path == "/") {
$("#return_folder").css("display", "none");
}
else {
$("#return_folder").css("display", "inline-block");
}
}
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('mouseMove-top')
let divB = document.getElementById('mouseMove-bottom')
let midd = document.getElementById('left_move_right')
let left_midd = document.getElementById('py-editor')
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 = ''
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) {
document.getElementById("webadb_iframe").contentWindow.document.getElementById("usbdisconnect").click()
reconnect = false
$('#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() {
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.indexOf("/bin/sh") > -1 || str.indexOf("No such file or directory") > -1 || str.indexOf("Read-only file system") > -1)
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
}
function uploadFilesCocoPi(file, fileOut) {
document.getElementById('webadb_iframe').contentWindow.upload(file, "/tmp/").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()
}
})
})
}
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) {
isRunCodeData = e;
_data = "";
_ti = "";
serverPrint(e)
RunInterval = setInterval(() => {
serverPrint(e)
}, 50);
setTimeout(function () {
$("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
$('.progress > .determinate').css('width', '100%');
window.file_manger_modal = true
$("#runCode").removeClass('disabled')
$("#uploadpy").removeClass('disabled')
$("#resetDevice").removeClass('disabled')
$("#poweroff").removeClass('disabled')
}, 2000);
})
}
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 = "";
}, 50)
}
}).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) {
let b = _data.split('\r\n')
for (let i = 0; i <= b.length - 1; i++) {
c += `${b[i]}
`
}
$('#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(`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.KeyError}`)
}
}
}
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 isWifiContent = false
var ws = ''
var WifiContent = 'close';
// 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(`${CCB.str_group.connection_success}
`);
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(`${msg.data}
`);
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(`${CCB.str_group.connection}
`);
// connectWebsocket();
};
// 监听连接关闭
ws.onclose = () => {
$('#repl_box_content').append(`${CCB.str_group.disconnect}
`);
// 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);
}, 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("Traceback")).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("AttributeError")).split('\r\n')
$("#err-msg").text(`${errMsg}\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("Traceback ")).split('\r\n')
$("#err-msg").text(`${errMsg[0]}\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}`)
}
// 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(`${msg.data}
`);
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
}
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(`echo "" > /root/fileCfgTest && echo "" > /home/fileCfgTest`).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(`mount -o remount,rw /`).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)
}
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, "/tmp/").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()
}
})
})
}
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) {
isRunCodeData = e;
_data = "";
_ti = "";
serverPrint(e)
RunInterval = setInterval(() => {
serverPrint(e)
}, 50);
setTimeout(function () {
$("#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')
}, 2000);
}).catch(err => {
console.log('123213')
})
}
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) {
let b = _data.split('\r\n')
for (let i = 0; i <= b.length - 1; i++) {
c += `${b[i]}
`
}
$('#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(`${CCB.str_group.connection_success}
`);
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(`${msg.data}
`);
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(`${CCB.str_group.connection}
`);
// connectWebsocket();
};
// 监听连接关闭
ws.onclose = () => {
$('#repl_box_content').append(`${CCB.str_group.disconnect}
`);
// 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(`${msg.data}
`);
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("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 "" > /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("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(`echo "" > /root/fileCfgTest && echo "" > /home/fileCfgTest`).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(`mount -o remount,rw /`).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;
async function runCocoPi() {
let text = pythonnewcode || Blockly.Python.workspaceToCode(blockpy.components.editor.blockly) || blockpy.components.editor.codeMirror.getValue() || ""
if (text == "\n") {
return true
}
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 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")
let out = `import asyncio
import subprocess
import linecache
async def tailf(filename):
command = "python -u /tmp/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 {
// console.log(document.getElementById('webadb_iframe').contentWindow.getdevice().device.subprocess.shell(`echo "" > /root/fileCfgTest`))
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("/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(`mount -o remount -rw /dev/mmcblk0p4`).then(r => {
$("#webadbErro").css("display", "none")
uploadFilesCocoPi(file, fileOut)
}).catch(err => {
$('.progress > .determinate').css('width', 0);
$("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedFail
})
}
else {
// 没有错误处理
$("#webadbErro").css("display", "none")
uploadFilesCocoPi(file, fileOut)
}
}).catch(n => {
console.log(n)
})
}, 100)
}).catch(err => {
console.log(err)
})
}
}
// bledevice.gatt.connected 连接状态
// bledevice.gatt.disconnect() 断开连接
// device.gatt.connect() 蓝牙连接
// 蓝牙上传
function bluetoothUpload(text, UploadOrRun) {
let value = 0
bleuploadfile("/root/usew_latess_code.py", text, function (event) {
if (event == true) {
console.log("上传成功", event)
value++
if (UploadOrRun && value == 2) {
$('.progress > .determinate').css('width', '75%');
setTimeout(() => {
$('.progress > .determinate').css('width', '100%');
$("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "100%"
}, 500);
} else if (value == 2) {
$("#status_txt")[0].innerHTML = Ardublockly.LOCALISED_TEXT.ExecutedSuccessfully + "50%"
$('.progress > .determinate').css('width', '50%');
bluetoothRun()
}
}
})
}
let repl_box_content_str = ''
// 蓝牙运行
function bluetoothRun() {
blerun('/root/usew_latess_code.py', function (rechex, isrun) {
//const rechex = new TextDecoder().decode(event.target.value.buffer);
let a = `${rechex}
`
$('#repl_box_content').append(a);
repl_box_contentheight = $("#repl_box_content")[0].scrollHeight;
$("#repl_box_content").scrollTop(repl_box_contentheight);
console.log("蓝牙运行", 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);
})
}
/*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}")
*/