index.js 108 KB

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