index.js 108 KB

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