From e0929fb90e2d2b27d98aceea5e1b86b038359159 Mon Sep 17 00:00:00 2001 From: Gordon Williams Date: Wed, 1 Feb 2023 08:47:48 +0000 Subject: [PATCH 01/53] Tweaks to maybe make this work --- apps/boot/bootupdate.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/boot/bootupdate.js b/apps/boot/bootupdate.js index 72eb4afab..f8fab16a1 100644 --- a/apps/boot/bootupdate.js +++ b/apps/boot/bootupdate.js @@ -37,10 +37,10 @@ if (s.log>=2) { // logging to file boot += `_DBGLOG=require("Storage").open("log.txt","a"); `; } if (s.blerepl===false) { // If not programmable, force terminal off Bluetooth - if (s.log>=2) boot += `_DBGLOG=require("Storage").open("log.txt","a"); -LoopbackB.on('data',function(d) {_DBGLOG.write(d);Terminal.write(d);}); + if (s.log>=2) { boot += `_DBGLOG=require("Storage").open("log.txt","a");`; +LoopbackB.on('data',function(d) {_DBGLOG.write(d);${(s.log==3)?"Terminal.write(d);":""}}); LoopbackA.setConsole(true);\n`; - else if (s.log==1||s.log==3) boot += `Terminal.setConsole(true);\n`; // if showing debug, force REPL onto terminal + } else if (s.log==1) boot += `Terminal.setConsole(true);\n`; // if showing debug, force REPL onto terminal else boot += `E.setConsole(null,{force:true});\n`; // on new (2v05+) firmware we have E.setConsole which allows a 'null' console /* If not programmable add our own handler for Bluetooth data to allow Gadgetbridge commands to be received*/ From 07f83d50df9d24d1d1da07693d7853e20987ea33 Mon Sep 17 00:00:00 2001 From: Gordon Williams Date: Wed, 1 Feb 2023 08:48:56 +0000 Subject: [PATCH 02/53] one more tweak --- apps/boot/bootupdate.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/boot/bootupdate.js b/apps/boot/bootupdate.js index f8fab16a1..4e4af928d 100644 --- a/apps/boot/bootupdate.js +++ b/apps/boot/bootupdate.js @@ -58,7 +58,7 @@ Bluetooth.on('line',function(l) { });\n`; } else { if (s.log>=2) boot += `_DBGLOG=require("Storage").open("log.txt","a"); -LoopbackB.on('data',function(d) {_DBGLOG.write(d);Terminal.write(d);}); +LoopbackB.on('data',function(d) {_DBGLOG.write(d);${(s.log==3)?"Terminal.write(d);":""}}); if (!NRF.getSecurityStatus().connected) LoopbackA.setConsole();\n`; else if (s.log==1||s.log==3) boot += `if (!NRF.getSecurityStatus().connected) Terminal.setConsole();\n`; // if showing debug, put REPL on terminal (until connection) else boot += `Bluetooth.setConsole(true);\n`; // else if no debug, force REPL to Bluetooth From 6befce43e50ec5853b7759985496072862827a4c Mon Sep 17 00:00:00 2001 From: Gordon Williams Date: Wed, 1 Feb 2023 08:56:42 +0000 Subject: [PATCH 03/53] oops --- apps/boot/bootupdate.js | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/apps/boot/bootupdate.js b/apps/boot/bootupdate.js index 4e4af928d..d929b26a0 100644 --- a/apps/boot/bootupdate.js +++ b/apps/boot/bootupdate.js @@ -33,11 +33,8 @@ if (s.ble!==false) { } } // settings.log 0-off, 1-display, 2-log, 3-both -if (s.log>=2) { // logging to file - boot += `_DBGLOG=require("Storage").open("log.txt","a"); -`; -} if (s.blerepl===false) { // If not programmable, force terminal off Bluetooth - if (s.log>=2) { boot += `_DBGLOG=require("Storage").open("log.txt","a");`; +if (s.blerepl===false) { // If not programmable, force terminal off Bluetooth + if (s.log>=2) { boot += `_DBGLOG=require("Storage").open("log.txt","a"); LoopbackB.on('data',function(d) {_DBGLOG.write(d);${(s.log==3)?"Terminal.write(d);":""}}); LoopbackA.setConsole(true);\n`; } else if (s.log==1) boot += `Terminal.setConsole(true);\n`; // if showing debug, force REPL onto terminal @@ -60,7 +57,7 @@ Bluetooth.on('line',function(l) { if (s.log>=2) boot += `_DBGLOG=require("Storage").open("log.txt","a"); LoopbackB.on('data',function(d) {_DBGLOG.write(d);${(s.log==3)?"Terminal.write(d);":""}}); if (!NRF.getSecurityStatus().connected) LoopbackA.setConsole();\n`; - else if (s.log==1||s.log==3) boot += `if (!NRF.getSecurityStatus().connected) Terminal.setConsole();\n`; // if showing debug, put REPL on terminal (until connection) + else if (s.log==1) boot += `if (!NRF.getSecurityStatus().connected) Terminal.setConsole();\n`; // if showing debug, put REPL on terminal (until connection) else boot += `Bluetooth.setConsole(true);\n`; // else if no debug, force REPL to Bluetooth } // we just reset, so BLE should be on. From c3f11f90d5ff5acab328b1a88214b1ad2a94c756 Mon Sep 17 00:00:00 2001 From: Erik Andresen Date: Thu, 2 Feb 2023 18:39:08 +0100 Subject: [PATCH 04/53] sched: add interface.html - Edit or delete existing events, add new - Add events from iCalendar file --- apps/sched/interface.html | 223 ++++++++++++++++++++++++++++++++++++++ apps/sched/metadata.json | 1 + 2 files changed, 224 insertions(+) create mode 100644 apps/sched/interface.html diff --git a/apps/sched/interface.html b/apps/sched/interface.html new file mode 100644 index 000000000..366e597a2 --- /dev/null +++ b/apps/sched/interface.html @@ -0,0 +1,223 @@ + + + + + + + + + +

Manage dated events

+ +
+ +
+ + + + + + + + + + + +
DateSummary
+ +
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+ + + + + diff --git a/apps/sched/metadata.json b/apps/sched/metadata.json index 2a1b0f8ca..42c3aaa12 100644 --- a/apps/sched/metadata.json +++ b/apps/sched/metadata.json @@ -10,6 +10,7 @@ "provides_modules" : ["sched"], "default" : true, "readme": "README.md", + "interface": "interface.html", "storage": [ {"name":"sched.boot.js","url":"boot.js"}, {"name":"sched.js","url":"sched.js"}, From 6b5fee29aff57101bc8ba8997d2274c3ed62d42c Mon Sep 17 00:00:00 2001 From: thyttan <6uuxstm66@mozmail.com⁩> Date: Thu, 2 Feb 2023 21:40:34 +0100 Subject: [PATCH 05/53] back button for settings main menu --- apps/powermanager/ChangeLog | 1 + apps/powermanager/metadata.json | 2 +- apps/powermanager/settings.js | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/powermanager/ChangeLog b/apps/powermanager/ChangeLog index a83e8c676..06f38d399 100644 --- a/apps/powermanager/ChangeLog +++ b/apps/powermanager/ChangeLog @@ -3,3 +3,4 @@ 0.03: Use default Bangle formatter for booleans 0.04: Remove calibration with current voltage (Calibrate->Auto) as it is now handled by settings app Allow automatic calibration on every charge longer than 3 hours +0.05: Add back button to settings menu. diff --git a/apps/powermanager/metadata.json b/apps/powermanager/metadata.json index 0777feee3..456831aa9 100644 --- a/apps/powermanager/metadata.json +++ b/apps/powermanager/metadata.json @@ -2,7 +2,7 @@ "id": "powermanager", "name": "Power Manager", "shortName": "Power Manager", - "version": "0.04", + "version": "0.05", "description": "Allow configuration of warnings and thresholds for battery charging and display.", "icon": "app.png", "type": "bootloader", diff --git a/apps/powermanager/settings.js b/apps/powermanager/settings.js index 9eeb29e00..fe4719275 100644 --- a/apps/powermanager/settings.js +++ b/apps/powermanager/settings.js @@ -23,6 +23,7 @@ '': { 'title': 'Power Manager' }, + "< Back" : back, 'Monotonic percentage': { value: !!settings.forceMonoPercentage, onchange: v => { From 6c8eb8e11d01526974a87fc21eb8228d21d7caf8 Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 10:48:15 +1300 Subject: [PATCH 06/53] Create app.js --- tempgraph/app.js | 395 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 395 insertions(+) create mode 100644 tempgraph/app.js diff --git a/tempgraph/app.js b/tempgraph/app.js new file mode 100644 index 000000000..a0bb3016b --- /dev/null +++ b/tempgraph/app.js @@ -0,0 +1,395 @@ +// Temperature Graph +// BangleJS Script + +Bangle.setBarometerPower(true,"tempgraph"); +Bangle.loadWidgets(); +var wids=WIDGETS; +var widsOn=true; +var rm=null; +var gt=null; +var dg=null; +var Layout=require("Layout"); +var C=true; +var temp,tempMode,readErrCnt,watchButton2; + +var graph=require("Storage").readJSON("tempgraph.json",true); +if(graph==undefined) { + graph=[]; +} + +var timesData=[ + // dur=duration, u=time units, d=divisions on graph, s=seconds per unit. + {dur:10,u:"Mins",d:5,s:60}, + {dur:20,u:"Mins",d:4,s:60}, + {dur:30,u:"Mins",d:3,s:60}, + {dur:40,u:"Mins",d:4,s:60}, + {dur:1,u:"Hr",d:4,s:3600}, + {dur:2,u:"Hrs",d:4,s:3600}, + {dur:3,u:"Hrs",d:3,s:3600}, + {dur:4,u:"Hrs",d:4,s:3600}, + {dur:6,u:"Hrs",d:6,s:3600}, + {dur:8,u:"Hrs",d:4,s:3600}, + {dur:12,u:"Hrs",d:6,s:3600}, + {dur:16,u:"Hrs",d:4,s:3600}, + {dur:20,u:"Hrs",d:5,s:3600}, + {dur:1,u:"Day",d:4,s:3600}, + {dur:2,u:"Days",d:4,s:86400}, + {dur:3,u:"Days",d:3,s:86400}, + {dur:4,u:"Days",d:4,s:86400}, + {dur:5,u:"Days",d:5,s:86400}, + {dur:6,u:"Days",d:6,s:86400}, + {dur:7,u:"Days",d:7,s:86400} +]; +var times=[]; +for(n=0;n{ + temp=p.temperature; + if(tempMode=="drawGraph"&&graph.length>0&&Math.abs(graph[graph.length-1].temp-temp)>10&&readErrCnt<2){ + // A large change in temperature may be a reading error. ie. A 0C or less reading after + // a 20C reading. So if this happens, the reading is repeated up to 2 times to hopefully + // skip such errors. + readErrCnt++; + print("readErrCnt "+readErrCnt); + return; + } + clearInterval(gt); + readErrCnt=0; + switch (tempMode){ + case "showTemp": + showT(); + break; + case "drawGraph": + var date=new Date(); + var dateStr=require("locale").date(date).trim(); + var hrs=date.getHours(); + var mins=date.getMinutes(); + var secs=date.getSeconds(); + graph.push({ + temp:temp, + date:dateStr, + hrs:hrs, + mins:mins, + secs:secs + }); + if(graph.length==1){ + graph[0].dur=durInd; + } + require("Storage").writeJSON("tempgraph.json", graph); + if(graph.length==150){ + clearInterval(dg); + } + drawG(); + } + }); +} + +function getTemp(){ + readErrCnt=0; + gt = setInterval(getT,800); +} + +function setButton(){ + var watchButton=setWatch(function(){ + clearInterval(gt); + clearInterval(dg); + clearWatch(watchButton); + Bangle.removeListener("touch",screenTouch); + openMenu(); + },BTN); + Bangle.on('touch',screenTouch); +} + +function setButton2(){ + watchButton2=setWatch(function(){ + clearWatch(watchButton2); + openMenu(); + },BTN); +} + +function zPad(n){ + return n.toString().padStart(2,0); +} + +function screenTouch(n,ev){ + if(ev.y>23&&ev.y<152){ + C=C==false; + drawG(false); + } +} + +function drawG(){ + function cf(t){ + if(C){ + return t; + } + return getF(t); + } + drawWids(); + var top=1; + var bar=21; + var barBot=175-22; + if(widsOn){ + top=25; + bar=bar+24; + barBot=barBot-24; + } + var low=graph[0].temp; + var hi=low; + for(n=0;nt){ + low=t; + } + if(hi10){ + div=5; + } + if(C){ + g.setColor(1,0,0); + }else{ + g.setColor(0,0,1); + } + var step=(barBot-bar)/((tempHi-tempLow)/div); + for(n=0;nexit()}, + ],lazy:true + }); + drawWids(); + messageLO.render(); +} + +function showT(){ + tempLO.lab1.label=tempLO.lab3.label; + tempLO.lab2.label=tempLO.lab4.label; + tempLO.lab3.label=tempLO.lab5.label; + tempLO.lab4.label=tempLO.lab6.label; + tempLO.lab5.label=temp.toFixed(2)+"C"; + tempLO.lab6.label=getF(temp).toFixed(2)+"F"; + tempLO.render(); +} + +function exit(){ + clearWatch(watchButton2); + openMenu(); +} + +function showTemp(){ + tempMode="showTemp"; + setButton2(); + tempLO=new Layout({ + type:"v",c:[ + {type:"h",c:[ + {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab1"}, + {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab2"} + ]}, + {type:"h",c:[ + {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab3"}, + {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab4"} + ]}, + {type:"h",c:[ + {type:"txt",pad:5,col:"#f00",font:"6x8:2",label:" ",id:"lab5"}, + {type:"txt",pad:5,col:"#00f",font:"6x8:2",label:" ",id:"lab6"} + ]}, + {type:"h",c:[ + {type:"btn",pad:2,font:"6x8:2",label:"Temp",cb:l=>getTemp()}, + {type:"btn",pad:2,font:"6x8:2",label:"Exit",cb:l=>exit()} + ]} + ] + },{lazy:true}); + tempLO.render(); + getTemp(); +} + +var menu={ + "":{ + "title":" Temp. Graph" + }, + + "Widgets":{ + value:widsOn, + format:vis=>vis?"Hide":"Show", + onchange:vis=>{ + widsOn=vis; + refreshMenu(); + } + }, + + "Duration":{ + value:times.indexOf(duration), + min:0,max:times.length-1,step:1,wrap:true, + format:tim=>times[tim], + onchange:(dur)=>{ + duration=times[dur]; + } + }, + + "Draw Graph":function(){ + E.showMenu(); + drawGraph(); + }, + + "Show Graph" : function(){ + E.showMenu(); + if(graph.length>0){ + showGraph(); + }else{ + message("No graph to\nshow as no\ngraph has been\ndrawn yet."); + } + }, + + "Save Graph" : function(){ + E.showMenu(); + if(graph.length>0){ + saveGraph(); + }else{ + message("No graph to\nsave as no\ngraph has been\ndrawn yet."); + } + }, + + "Save Data" : function(){ + E.showMenu(); + if(graph.length>0){ + saveData(); + }else{ + message("No data to\nsave as no\ngraph has been\ndrawn yet."); + } + }, + + "Show Temp":function(){ + E.showMenu(); + showTemp(); + } +}; + +openMenu(); From a77b4cf233e4c8f879c005e32efbeaf05263e5db Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 10:54:02 +1300 Subject: [PATCH 07/53] Add files via upload --- tempgraph/ChangeLog | 2 ++ tempgraph/README.md | 35 +++++++++++++++++++++++++++++++++++ tempgraph/metadata.json | 18 ++++++++++++++++++ tempgraph/screenshot_1.png | Bin 0 -> 3320 bytes tempgraph/screenshot_2.png | Bin 0 -> 4186 bytes tempgraph/screenshot_3.png | Bin 0 -> 3480 bytes 6 files changed, 55 insertions(+) create mode 100644 tempgraph/ChangeLog create mode 100644 tempgraph/README.md create mode 100644 tempgraph/metadata.json create mode 100644 tempgraph/screenshot_1.png create mode 100644 tempgraph/screenshot_2.png create mode 100644 tempgraph/screenshot_3.png diff --git a/tempgraph/ChangeLog b/tempgraph/ChangeLog new file mode 100644 index 000000000..58dd75a19 --- /dev/null +++ b/tempgraph/ChangeLog @@ -0,0 +1,2 @@ +0.01: 3/Feb/2023 Added 'Temperature Graph' app to depository. + diff --git a/tempgraph/README.md b/tempgraph/README.md new file mode 100644 index 000000000..e104c41e0 --- /dev/null +++ b/tempgraph/README.md @@ -0,0 +1,35 @@ +# Temperature Graph + +**Temperature Graph** (tempgraph) is a Bangle.js 2 app for recording graphs of the temperature for various time periods from 10 minutes to 7 days long. It samples the watch's temperature sensor 150 times while creating a graph, regardless of the time period selected. + +### Menu Options +* **Widgets** Toggles the watch's widgets on and off. With them off gives you a bigger graph when viewing it. + +* **Duration** Select the time period for drawing the graph, from 10 minutes to 7 days long. + +* **Draw Graph** Draws the graph. + * Tapping the screen toggles the graph between Celsius (red) and Fahrenheit (blue). + * Pressing the watch button takes you back to the menu. **Note:** While the graph can still be viewed after returning to the menu, you can't continue recording it if you had returned to the menu before the time period was up. The graph is saved in the watch though so it's still there the next time you start the app. + +![](screenshot_1.png) +![](screenshot_2.png) +![](screenshot_3.png) + +* **Show Graph** Shows the last drawn graph. + * Tapping the screen toggles the graph between Celsius (red) and Fahrenheit (blue). + * Pressing the watch button takes you back to the menu. + +* **Save Graph** Sends a screengrab of the graph to the Espruino Web IDE from where you can save it as you would any image on a webpage. + +* **Save Data** Sends a CSV file of the graph's temperature data to the Espruino Web IDE where you can save it for further use. I suggest you use the Espruino Web IDE's Terminal Logger (selected in the IDE's Settings/General) to record the data as it's sent. This is the easiest way to save it as a text file. + +* **Show Temp** Shows the current temperature. + +### Note +Using the watch in a normal fashion can raise the temperature it's sensing to quite a few degrees above the surrounding temperature and it may take half an hour or so to drop to close to the surrounding temperature. After that it seems to give quite accurate readings, assuming the thermometer I've been comparing it to is itself reasonably accurate. So best to load the app then not touch the watch for half an hour before starting a recording. This is assuming you're not wearing the app and are just using it to record the temperature where you've put the watch. You could of course wear it and it'll still draw a graph, which might also be useful. + +### Creator +Carl Read ([mail](mailto:cread98@orcon.net.nz), [github](https://github.com/CarlR9)) + +#### License +[MIT License](LICENSE) diff --git a/tempgraph/metadata.json b/tempgraph/metadata.json new file mode 100644 index 000000000..f714c1eef --- /dev/null +++ b/tempgraph/metadata.json @@ -0,0 +1,18 @@ +{ "id": "tempgraph", + "name": "Temperature Graph", + "shortName":"Temp Graph", + "version":"0.01", + "description": "An app for recording the temperature for time periods ranging from 10 minutes to 7 days.", + "icon": "app.png", + "type": "tool", + "tags": "temperature,tempgraph,graph", + "supports" : ["BANGLEJS2"], + "readme": "README.md", + "storage": [ + {"name":"tempgraph.app.js","url":"app.js"} + ], + "data": [ + {"name":"tempgraph.json"} + ], + "screenshots": [{"url":"screenshot_1.png"},{"url":"screenshot_2.png"},{"url":"screenshot_3.png"}] +} diff --git a/tempgraph/screenshot_1.png b/tempgraph/screenshot_1.png new file mode 100644 index 0000000000000000000000000000000000000000..7395f289695fd5be8a03d97b8644f55cc29072db GIT binary patch literal 3320 zcmc&%c|4Tu8h*_pJ0(S9`$$TK>`RF3Ya+5w(IETUSevn=P$GL-Bg7!fjD+4g*~@OM zGqeZ^qm1U831`&#zVpZV`}>_g-uL27D5p%~=j{Mo|6#qT;hC6L3H=B#aSZ=-rYbK6xno$72nqPjb;DfH3MrYnLP#894q}Y@ugiEoZdW|BYZ9Lv|iQ< zwaI6^acXnYOx!eL%5GcT@umv_K6y&aiJFQk!#VSU?H$6)_WBO0P$x-3cpE&q>4BL5 zd$y;}fnr>$3aB)1jfwi=`)B2Nh|*9y@PiiI6wuh81kCm&907aYS&L+n0dK0L%~Rh- z*pUKy`>Weqx(|bt_?jG^5D|ILYeVHWO;N!J3;yPXmaIECbEk=Ni){s{DI=ZBm*p$= z{X6Z`xBHYmA`}t%LeRD)XV1l{sSv{$J`l%6gvw{IbR|OJ4@FzEs63Ai2tnp#|M{^L=yN-GEnwnd+I!20t zq{Vc^c;PuCMzA+#rTId;=ok1@bwzVw6EU5tVN*L*gOx1F3G0bHNK={{)}Dy*9uM(g zFQJYenODA#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>N?rMBzE%(6*(LDgvWbpEMNrUpJl1eK~$xyvqFelldzHm>5{<*XkkT{tZ@2JSzYI literal 0 HcmV?d00001 diff --git a/tempgraph/screenshot_2.png b/tempgraph/screenshot_2.png new file mode 100644 index 0000000000000000000000000000000000000000..68d0ea236c6a513868c69eae8a5e51f995fad9f4 GIT binary patch literal 4186 zcmd6rS5p%Vu!fV+f)JXZhNg&sNC!cs_by5mLW>eWdhZYux<~}1DFTruDuf<-2}Pv| z3PPw!K%_Tm0R%aGGw0&`gmbaGGdsJp&)&QpMmMm zePzRf!+8J(nCWQ(Du#Gh001^l18oh9P=}4Y7d2~*7qnf^&h)UNUroiG*dSRPqATVN ztK;j|SMC^rRpw7l|5CTe&rY(((3}YF|A@ zZS1Y>yX%UeliP$JCO&SG^179^sbMz`eBv(CT^1<;eLPvWBdiYy+c414quD0H%u32Dsil0v3AFGNU<_1QeXdw6sB!!gVKk>FY^p)d7tb;dYJ>&d#IN)+ zdj@gWDYRD!xvv^6c|6a6{?m>+2msgyT##7%4Mdtu?<#tzODoG=Eq1|T~{@w z>5!mdP*--l`jnauD1sLfH=yw=DB~)WbO~q98g)e%sAR zwuX7Htc*=1>qiAcNOIR)ctLNUT0Yv=$k|S}WvEz|2kOB1NArn`VP#l1u-`BVr<_SR?%vH9rm& zJXpx4GEA%SR%-bZXjQ932FP-?^tMS(gY32_YD*3CUSh03$!9re^B_bj@iPX=5BHF; ze^6yPN6}q(1EQ#zD`odFY14f-GnRusa5kh^-nw(0fWahBvoTQYxt?5c@Gwie$+Ie~ z29f?WYf$C10`zQO8qt5(ajfKLn#wl^mQE~?cbz^%sw|kO>QWeQ3X#$$-{4eDt` z1C1Njr2Uk89cDBQCo@w|`HX4!>Fz$M-A~TR6K~B@m?Ep>wKX>MXDa>En`QwvW-`j7 z()!XKbr(e2c17eB#t{ z&Lljg%3PHlwg#(4s#~Z-=m*|gYW^e^O=`7NWDlF(|4zXh-gMI%DCbaLDW!ipY$~{$ zo4xdkVG5_76+i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PYZRd1wD)WR+V9l zopf38>nT+i?B#Hk6MXSMk7W-#P9ZiLByo8UKiSPFt=GlU{EQ5i#{w&Trw`=c6w2YJ zzK=(+U0+a68IKxaQn$fL zp!*e|1l0O-k>nhZ8AfDX=l!QML?Ya(!FHl@*TgD}6KCRF8jHwwVyC;)omR%r|!MK_-;peZojjW)feT2 z$yu;KA|8o@K*WgHL%)WiP!{X9izB_e>moe{Rqn}6(cCOIqX_=+ zea8euZgN5{H7D`wa>4TZZfj8i)Tbk`gijiRq-foZ)CxruA9rc1#yPV{fDoL!Ebzzm{w$S zosE2A59t#FLs#qo5A)Jy`@hgEAj)LYus1qw;{fvL_(XJSAl2YcZ=V=$t*#q@Sc*IR z27gB<$S2oSzmeN~mwFswRUzdvq)i?je-`yOiFRtn|r2W9ITbLB0 zJl(StGn1neJ@5~MVGMsH5i$#|;vQ(a7}_h7irKek7*{@`UB8ruHzS@Z+}FY~6)bAx zX=Iz#aSY={_7eW%Xl*--{Tvz8L zUHT}6clZ?X@}eQY^UcFT9;1A_WJ<);p!HYy2#Si-!{J4gL7e%(g?IgIt*abUCS#b_ z5mSPr1NcV8qxXh36%7Z4eSOp4e|k7yaS?U>Y z)xMHw8F3Cj%jNP4H@%x}I~wUr+CiRy>3++vanXZfU@p_n_voXq)-f|93q*+l^1=TB Di-xj= literal 0 HcmV?d00001 From 7b68a37391be112b364caa3da7f793c283898848 Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 11:05:06 +1300 Subject: [PATCH 08/53] Update README.md --- tempgraph/README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tempgraph/README.md b/tempgraph/README.md index e104c41e0..de4a0af59 100644 --- a/tempgraph/README.md +++ b/tempgraph/README.md @@ -11,10 +11,6 @@ * Tapping the screen toggles the graph between Celsius (red) and Fahrenheit (blue). * Pressing the watch button takes you back to the menu. **Note:** While the graph can still be viewed after returning to the menu, you can't continue recording it if you had returned to the menu before the time period was up. The graph is saved in the watch though so it's still there the next time you start the app. -![](screenshot_1.png) -![](screenshot_2.png) -![](screenshot_3.png) - * **Show Graph** Shows the last drawn graph. * Tapping the screen toggles the graph between Celsius (red) and Fahrenheit (blue). * Pressing the watch button takes you back to the menu. @@ -25,6 +21,11 @@ * **Show Temp** Shows the current temperature. +### Screenshots +![](screenshot_1.png) +![](screenshot_2.png) +![](screenshot_3.png) + ### Note Using the watch in a normal fashion can raise the temperature it's sensing to quite a few degrees above the surrounding temperature and it may take half an hour or so to drop to close to the surrounding temperature. After that it seems to give quite accurate readings, assuming the thermometer I've been comparing it to is itself reasonably accurate. So best to load the app then not touch the watch for half an hour before starting a recording. This is assuming you're not wearing the app and are just using it to record the temperature where you've put the watch. You could of course wear it and it'll still draw a graph, which might also be useful. From ff40b61747f8894710d85bf41e36e9f29282b74c Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 11:16:05 +1300 Subject: [PATCH 09/53] Delete tempgraph directory --- tempgraph/ChangeLog | 2 - tempgraph/README.md | 36 ---- tempgraph/app.js | 395 ------------------------------------- tempgraph/metadata.json | 18 -- tempgraph/screenshot_1.png | Bin 3320 -> 0 bytes tempgraph/screenshot_2.png | Bin 4186 -> 0 bytes tempgraph/screenshot_3.png | Bin 3480 -> 0 bytes 7 files changed, 451 deletions(-) delete mode 100644 tempgraph/ChangeLog delete mode 100644 tempgraph/README.md delete mode 100644 tempgraph/app.js delete mode 100644 tempgraph/metadata.json delete mode 100644 tempgraph/screenshot_1.png delete mode 100644 tempgraph/screenshot_2.png delete mode 100644 tempgraph/screenshot_3.png diff --git a/tempgraph/ChangeLog b/tempgraph/ChangeLog deleted file mode 100644 index 58dd75a19..000000000 --- a/tempgraph/ChangeLog +++ /dev/null @@ -1,2 +0,0 @@ -0.01: 3/Feb/2023 Added 'Temperature Graph' app to depository. - diff --git a/tempgraph/README.md b/tempgraph/README.md deleted file mode 100644 index de4a0af59..000000000 --- a/tempgraph/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# Temperature Graph - -**Temperature Graph** (tempgraph) is a Bangle.js 2 app for recording graphs of the temperature for various time periods from 10 minutes to 7 days long. It samples the watch's temperature sensor 150 times while creating a graph, regardless of the time period selected. - -### Menu Options -* **Widgets** Toggles the watch's widgets on and off. With them off gives you a bigger graph when viewing it. - -* **Duration** Select the time period for drawing the graph, from 10 minutes to 7 days long. - -* **Draw Graph** Draws the graph. - * Tapping the screen toggles the graph between Celsius (red) and Fahrenheit (blue). - * Pressing the watch button takes you back to the menu. **Note:** While the graph can still be viewed after returning to the menu, you can't continue recording it if you had returned to the menu before the time period was up. The graph is saved in the watch though so it's still there the next time you start the app. - -* **Show Graph** Shows the last drawn graph. - * Tapping the screen toggles the graph between Celsius (red) and Fahrenheit (blue). - * Pressing the watch button takes you back to the menu. - -* **Save Graph** Sends a screengrab of the graph to the Espruino Web IDE from where you can save it as you would any image on a webpage. - -* **Save Data** Sends a CSV file of the graph's temperature data to the Espruino Web IDE where you can save it for further use. I suggest you use the Espruino Web IDE's Terminal Logger (selected in the IDE's Settings/General) to record the data as it's sent. This is the easiest way to save it as a text file. - -* **Show Temp** Shows the current temperature. - -### Screenshots -![](screenshot_1.png) -![](screenshot_2.png) -![](screenshot_3.png) - -### Note -Using the watch in a normal fashion can raise the temperature it's sensing to quite a few degrees above the surrounding temperature and it may take half an hour or so to drop to close to the surrounding temperature. After that it seems to give quite accurate readings, assuming the thermometer I've been comparing it to is itself reasonably accurate. So best to load the app then not touch the watch for half an hour before starting a recording. This is assuming you're not wearing the app and are just using it to record the temperature where you've put the watch. You could of course wear it and it'll still draw a graph, which might also be useful. - -### Creator -Carl Read ([mail](mailto:cread98@orcon.net.nz), [github](https://github.com/CarlR9)) - -#### License -[MIT License](LICENSE) diff --git a/tempgraph/app.js b/tempgraph/app.js deleted file mode 100644 index a0bb3016b..000000000 --- a/tempgraph/app.js +++ /dev/null @@ -1,395 +0,0 @@ -// Temperature Graph -// BangleJS Script - -Bangle.setBarometerPower(true,"tempgraph"); -Bangle.loadWidgets(); -var wids=WIDGETS; -var widsOn=true; -var rm=null; -var gt=null; -var dg=null; -var Layout=require("Layout"); -var C=true; -var temp,tempMode,readErrCnt,watchButton2; - -var graph=require("Storage").readJSON("tempgraph.json",true); -if(graph==undefined) { - graph=[]; -} - -var timesData=[ - // dur=duration, u=time units, d=divisions on graph, s=seconds per unit. - {dur:10,u:"Mins",d:5,s:60}, - {dur:20,u:"Mins",d:4,s:60}, - {dur:30,u:"Mins",d:3,s:60}, - {dur:40,u:"Mins",d:4,s:60}, - {dur:1,u:"Hr",d:4,s:3600}, - {dur:2,u:"Hrs",d:4,s:3600}, - {dur:3,u:"Hrs",d:3,s:3600}, - {dur:4,u:"Hrs",d:4,s:3600}, - {dur:6,u:"Hrs",d:6,s:3600}, - {dur:8,u:"Hrs",d:4,s:3600}, - {dur:12,u:"Hrs",d:6,s:3600}, - {dur:16,u:"Hrs",d:4,s:3600}, - {dur:20,u:"Hrs",d:5,s:3600}, - {dur:1,u:"Day",d:4,s:3600}, - {dur:2,u:"Days",d:4,s:86400}, - {dur:3,u:"Days",d:3,s:86400}, - {dur:4,u:"Days",d:4,s:86400}, - {dur:5,u:"Days",d:5,s:86400}, - {dur:6,u:"Days",d:6,s:86400}, - {dur:7,u:"Days",d:7,s:86400} -]; -var times=[]; -for(n=0;n{ - temp=p.temperature; - if(tempMode=="drawGraph"&&graph.length>0&&Math.abs(graph[graph.length-1].temp-temp)>10&&readErrCnt<2){ - // A large change in temperature may be a reading error. ie. A 0C or less reading after - // a 20C reading. So if this happens, the reading is repeated up to 2 times to hopefully - // skip such errors. - readErrCnt++; - print("readErrCnt "+readErrCnt); - return; - } - clearInterval(gt); - readErrCnt=0; - switch (tempMode){ - case "showTemp": - showT(); - break; - case "drawGraph": - var date=new Date(); - var dateStr=require("locale").date(date).trim(); - var hrs=date.getHours(); - var mins=date.getMinutes(); - var secs=date.getSeconds(); - graph.push({ - temp:temp, - date:dateStr, - hrs:hrs, - mins:mins, - secs:secs - }); - if(graph.length==1){ - graph[0].dur=durInd; - } - require("Storage").writeJSON("tempgraph.json", graph); - if(graph.length==150){ - clearInterval(dg); - } - drawG(); - } - }); -} - -function getTemp(){ - readErrCnt=0; - gt = setInterval(getT,800); -} - -function setButton(){ - var watchButton=setWatch(function(){ - clearInterval(gt); - clearInterval(dg); - clearWatch(watchButton); - Bangle.removeListener("touch",screenTouch); - openMenu(); - },BTN); - Bangle.on('touch',screenTouch); -} - -function setButton2(){ - watchButton2=setWatch(function(){ - clearWatch(watchButton2); - openMenu(); - },BTN); -} - -function zPad(n){ - return n.toString().padStart(2,0); -} - -function screenTouch(n,ev){ - if(ev.y>23&&ev.y<152){ - C=C==false; - drawG(false); - } -} - -function drawG(){ - function cf(t){ - if(C){ - return t; - } - return getF(t); - } - drawWids(); - var top=1; - var bar=21; - var barBot=175-22; - if(widsOn){ - top=25; - bar=bar+24; - barBot=barBot-24; - } - var low=graph[0].temp; - var hi=low; - for(n=0;nt){ - low=t; - } - if(hi10){ - div=5; - } - if(C){ - g.setColor(1,0,0); - }else{ - g.setColor(0,0,1); - } - var step=(barBot-bar)/((tempHi-tempLow)/div); - for(n=0;nexit()}, - ],lazy:true - }); - drawWids(); - messageLO.render(); -} - -function showT(){ - tempLO.lab1.label=tempLO.lab3.label; - tempLO.lab2.label=tempLO.lab4.label; - tempLO.lab3.label=tempLO.lab5.label; - tempLO.lab4.label=tempLO.lab6.label; - tempLO.lab5.label=temp.toFixed(2)+"C"; - tempLO.lab6.label=getF(temp).toFixed(2)+"F"; - tempLO.render(); -} - -function exit(){ - clearWatch(watchButton2); - openMenu(); -} - -function showTemp(){ - tempMode="showTemp"; - setButton2(); - tempLO=new Layout({ - type:"v",c:[ - {type:"h",c:[ - {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab1"}, - {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab2"} - ]}, - {type:"h",c:[ - {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab3"}, - {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab4"} - ]}, - {type:"h",c:[ - {type:"txt",pad:5,col:"#f00",font:"6x8:2",label:" ",id:"lab5"}, - {type:"txt",pad:5,col:"#00f",font:"6x8:2",label:" ",id:"lab6"} - ]}, - {type:"h",c:[ - {type:"btn",pad:2,font:"6x8:2",label:"Temp",cb:l=>getTemp()}, - {type:"btn",pad:2,font:"6x8:2",label:"Exit",cb:l=>exit()} - ]} - ] - },{lazy:true}); - tempLO.render(); - getTemp(); -} - -var menu={ - "":{ - "title":" Temp. Graph" - }, - - "Widgets":{ - value:widsOn, - format:vis=>vis?"Hide":"Show", - onchange:vis=>{ - widsOn=vis; - refreshMenu(); - } - }, - - "Duration":{ - value:times.indexOf(duration), - min:0,max:times.length-1,step:1,wrap:true, - format:tim=>times[tim], - onchange:(dur)=>{ - duration=times[dur]; - } - }, - - "Draw Graph":function(){ - E.showMenu(); - drawGraph(); - }, - - "Show Graph" : function(){ - E.showMenu(); - if(graph.length>0){ - showGraph(); - }else{ - message("No graph to\nshow as no\ngraph has been\ndrawn yet."); - } - }, - - "Save Graph" : function(){ - E.showMenu(); - if(graph.length>0){ - saveGraph(); - }else{ - message("No graph to\nsave as no\ngraph has been\ndrawn yet."); - } - }, - - "Save Data" : function(){ - E.showMenu(); - if(graph.length>0){ - saveData(); - }else{ - message("No data to\nsave as no\ngraph has been\ndrawn yet."); - } - }, - - "Show Temp":function(){ - E.showMenu(); - showTemp(); - } -}; - -openMenu(); diff --git a/tempgraph/metadata.json b/tempgraph/metadata.json deleted file mode 100644 index f714c1eef..000000000 --- a/tempgraph/metadata.json +++ /dev/null @@ -1,18 +0,0 @@ -{ "id": "tempgraph", - "name": "Temperature Graph", - "shortName":"Temp Graph", - "version":"0.01", - "description": "An app for recording the temperature for time periods ranging from 10 minutes to 7 days.", - "icon": "app.png", - "type": "tool", - "tags": "temperature,tempgraph,graph", - "supports" : ["BANGLEJS2"], - "readme": "README.md", - "storage": [ - {"name":"tempgraph.app.js","url":"app.js"} - ], - "data": [ - {"name":"tempgraph.json"} - ], - "screenshots": [{"url":"screenshot_1.png"},{"url":"screenshot_2.png"},{"url":"screenshot_3.png"}] -} diff --git a/tempgraph/screenshot_1.png b/tempgraph/screenshot_1.png deleted file mode 100644 index 7395f289695fd5be8a03d97b8644f55cc29072db..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3320 zcmc&%c|4Tu8h*_pJ0(S9`$$TK>`RF3Ya+5w(IETUSevn=P$GL-Bg7!fjD+4g*~@OM zGqeZ^qm1U831`&#zVpZV`}>_g-uL27D5p%~=j{Mo|6#qT;hC6L3H=B#aSZ=-rYbK6xno$72nqPjb;DfH3MrYnLP#894q}Y@ugiEoZdW|BYZ9Lv|iQ< zwaI6^acXnYOx!eL%5GcT@umv_K6y&aiJFQk!#VSU?H$6)_WBO0P$x-3cpE&q>4BL5 zd$y;}fnr>$3aB)1jfwi=`)B2Nh|*9y@PiiI6wuh81kCm&907aYS&L+n0dK0L%~Rh- z*pUKy`>Weqx(|bt_?jG^5D|ILYeVHWO;N!J3;yPXmaIECbEk=Ni){s{DI=ZBm*p$= z{X6Z`xBHYmA`}t%LeRD)XV1l{sSv{$J`l%6gvw{IbR|OJ4@FzEs63Ai2tnp#|M{^L=yN-GEnwnd+I!20t zq{Vc^c;PuCMzA+#rTId;=ok1@bwzVw6EU5tVN*L*gOx1F3G0bHNK={{)}Dy*9uM(g zFQJYenODA#Q)$(46$>WGV zc@AUJSuP+B=J1GV&i&MuUnqez9z53}D?dWynXfc7)KGCmWg(ti`dLZ%dOsK6(O0b9 zi?j0JL+XDJey9nVjYLY-WgVA?E>b2*eI$S=de(urKb+Ug(ep#=B~KO^i@T8Jv_5Bt&1w`_eio?uO}^Xh(~P2VJmm_NX&Vc1Lxm&RnGH!8h@Z{GV#zLT}b(Bjru-Dzg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}soG0}ZUA))X;NGST4{hq-m}^vdeffSHox0iU07M6OrsAs$`gofch{Ed#kQ zID6V#NPwMIopRRq(9d2=jxh$?Uds-2d#md9t^!MMqD93l|-vfgx7KT z!po_VW)_slIscF{@=m1)W11u4>{xd~p&0FPj3WtIzO*?Xo@yCgW|208<3=kTQWCS_RGAxU__kBhfvWde&TDtAT?(@o@b#xrdOz-Zo-}o-2U}D%e!ImGa$1zcOHr zTZ}eC`{5~&1+4EiQ8}m+dkGw9IHjk&i2|BLeGKbSY;v)mnYd9%w2k(M3ua2T7v$s> zpCHv2Oa-smUB9LmVIgaEmW1K~HR7YF_)!0Gex7>Y;sNGWt=Q$fLZQGpb&*ma%B-NZ zeOT%Z!H|LAD66}O5DN9Xj-NJAXjG;~tzK75wL2W#sLr*nS-Jj!e4rFgDdDM?7f>q& z^8iDIvHfo84djD&#&jR*!|y@P^0yYYHeKuCnu?^$Kh|o#M?Xd&Pc&&y$PBM_HG31M zRky1{E-JgdaJfbd80TG1f%vZKp;a#jzuR)fM~hLH;3F?0^k=fRhl#O7jat0lxJ~UJ zntXM}W?qC{ry?io?5!gBQ&%1R{tAROiRHz{nG{&dTI!97SpknTY)3=25G&*imiBwo z+;HRmj6=oBm0|8-ticWb>$&J|e;rv55#sk-g(jT^I8#R>R9OQj7KJ?B=q<$6cd>6h zZXBw=^^$5^cestb+TxGo?=!7QxnysZNTxJji289(|y5(K>LD z&JQ>7sTkOD)rqPlWb4)kEREHbtNAVek;Bs-@-p2;i_(UA4HzmK7GR?k$+0K~`Q-Ld zF-DDID=S{%=K3Ph-H+3pH`>N?rMBzE%(6*(LDgvWbpEMNrUpJl1eK~$xyvqFelldzHm>5{<*XkkT{tZ@2JSzYI diff --git a/tempgraph/screenshot_2.png b/tempgraph/screenshot_2.png deleted file mode 100644 index 68d0ea236c6a513868c69eae8a5e51f995fad9f4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4186 zcmd6rS5p%Vu!fV+f)JXZhNg&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9izB_e>moe{Rqn}6(cCOIqX_=+ zea8euZgN5{H7D`wa>4TZZfj8i)Tbk`gijiRq-foZ)CxruA9rc1#yPV{fDoL!Ebzzm{w$S zosE2A59t#FLs#qo5A)Jy`@hgEAj)LYus1qw;{fvL_(XJSAl2YcZ=V=$t*#q@Sc*IR z27gB<$S2oSzmeN~mwFswRUzdvq)i?je-`yOiFRtn|r2W9ITbLB0 zJl(StGn1neJ@5~MVGMsH5i$#|;vQ(a7}_h7irKek7*{@`UB8ruHzS@Z+}FY~6)bAx zX=Iz#aSY={_7eW%Xl*--{Tvz8L zUHT}6clZ?X@}eQY^UcFT9;1A_WJ<);p!HYy2#Si-!{J4gL7e%(g?IgIt*abUCS#b_ z5mSPr1NcV8qxXh36%7Z4eSOp4e|k7yaS?U>Y z)xMHw8F3Cj%jNP4H@%x}I~wUr+CiRy>3++vanXZfU@p_n_voXq)-f|93q*+l^1=TB Di-xj= From 230625ae7830acc595f43f8e6e87b792f59e3e4e Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 11:18:27 +1300 Subject: [PATCH 10/53] Create app.js --- apps/tempgraph/app.js | 395 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 395 insertions(+) create mode 100644 apps/tempgraph/app.js diff --git a/apps/tempgraph/app.js b/apps/tempgraph/app.js new file mode 100644 index 000000000..a0bb3016b --- /dev/null +++ b/apps/tempgraph/app.js @@ -0,0 +1,395 @@ +// Temperature Graph +// BangleJS Script + +Bangle.setBarometerPower(true,"tempgraph"); +Bangle.loadWidgets(); +var wids=WIDGETS; +var widsOn=true; +var rm=null; +var gt=null; +var dg=null; +var Layout=require("Layout"); +var C=true; +var temp,tempMode,readErrCnt,watchButton2; + +var graph=require("Storage").readJSON("tempgraph.json",true); +if(graph==undefined) { + graph=[]; +} + +var timesData=[ + // dur=duration, u=time units, d=divisions on graph, s=seconds per unit. + {dur:10,u:"Mins",d:5,s:60}, + {dur:20,u:"Mins",d:4,s:60}, + {dur:30,u:"Mins",d:3,s:60}, + {dur:40,u:"Mins",d:4,s:60}, + {dur:1,u:"Hr",d:4,s:3600}, + {dur:2,u:"Hrs",d:4,s:3600}, + {dur:3,u:"Hrs",d:3,s:3600}, + {dur:4,u:"Hrs",d:4,s:3600}, + {dur:6,u:"Hrs",d:6,s:3600}, + {dur:8,u:"Hrs",d:4,s:3600}, + {dur:12,u:"Hrs",d:6,s:3600}, + {dur:16,u:"Hrs",d:4,s:3600}, + {dur:20,u:"Hrs",d:5,s:3600}, + {dur:1,u:"Day",d:4,s:3600}, + {dur:2,u:"Days",d:4,s:86400}, + {dur:3,u:"Days",d:3,s:86400}, + {dur:4,u:"Days",d:4,s:86400}, + {dur:5,u:"Days",d:5,s:86400}, + {dur:6,u:"Days",d:6,s:86400}, + {dur:7,u:"Days",d:7,s:86400} +]; +var times=[]; +for(n=0;n{ + temp=p.temperature; + if(tempMode=="drawGraph"&&graph.length>0&&Math.abs(graph[graph.length-1].temp-temp)>10&&readErrCnt<2){ + // A large change in temperature may be a reading error. ie. A 0C or less reading after + // a 20C reading. So if this happens, the reading is repeated up to 2 times to hopefully + // skip such errors. + readErrCnt++; + print("readErrCnt "+readErrCnt); + return; + } + clearInterval(gt); + readErrCnt=0; + switch (tempMode){ + case "showTemp": + showT(); + break; + case "drawGraph": + var date=new Date(); + var dateStr=require("locale").date(date).trim(); + var hrs=date.getHours(); + var mins=date.getMinutes(); + var secs=date.getSeconds(); + graph.push({ + temp:temp, + date:dateStr, + hrs:hrs, + mins:mins, + secs:secs + }); + if(graph.length==1){ + graph[0].dur=durInd; + } + require("Storage").writeJSON("tempgraph.json", graph); + if(graph.length==150){ + clearInterval(dg); + } + drawG(); + } + }); +} + +function getTemp(){ + readErrCnt=0; + gt = setInterval(getT,800); +} + +function setButton(){ + var watchButton=setWatch(function(){ + clearInterval(gt); + clearInterval(dg); + clearWatch(watchButton); + Bangle.removeListener("touch",screenTouch); + openMenu(); + },BTN); + Bangle.on('touch',screenTouch); +} + +function setButton2(){ + watchButton2=setWatch(function(){ + clearWatch(watchButton2); + openMenu(); + },BTN); +} + +function zPad(n){ + return n.toString().padStart(2,0); +} + +function screenTouch(n,ev){ + if(ev.y>23&&ev.y<152){ + C=C==false; + drawG(false); + } +} + +function drawG(){ + function cf(t){ + if(C){ + return t; + } + return getF(t); + } + drawWids(); + var top=1; + var bar=21; + var barBot=175-22; + if(widsOn){ + top=25; + bar=bar+24; + barBot=barBot-24; + } + var low=graph[0].temp; + var hi=low; + for(n=0;nt){ + low=t; + } + if(hi10){ + div=5; + } + if(C){ + g.setColor(1,0,0); + }else{ + g.setColor(0,0,1); + } + var step=(barBot-bar)/((tempHi-tempLow)/div); + for(n=0;nexit()}, + ],lazy:true + }); + drawWids(); + messageLO.render(); +} + +function showT(){ + tempLO.lab1.label=tempLO.lab3.label; + tempLO.lab2.label=tempLO.lab4.label; + tempLO.lab3.label=tempLO.lab5.label; + tempLO.lab4.label=tempLO.lab6.label; + tempLO.lab5.label=temp.toFixed(2)+"C"; + tempLO.lab6.label=getF(temp).toFixed(2)+"F"; + tempLO.render(); +} + +function exit(){ + clearWatch(watchButton2); + openMenu(); +} + +function showTemp(){ + tempMode="showTemp"; + setButton2(); + tempLO=new Layout({ + type:"v",c:[ + {type:"h",c:[ + {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab1"}, + {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab2"} + ]}, + {type:"h",c:[ + {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab3"}, + {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab4"} + ]}, + {type:"h",c:[ + {type:"txt",pad:5,col:"#f00",font:"6x8:2",label:" ",id:"lab5"}, + {type:"txt",pad:5,col:"#00f",font:"6x8:2",label:" ",id:"lab6"} + ]}, + {type:"h",c:[ + {type:"btn",pad:2,font:"6x8:2",label:"Temp",cb:l=>getTemp()}, + {type:"btn",pad:2,font:"6x8:2",label:"Exit",cb:l=>exit()} + ]} + ] + },{lazy:true}); + tempLO.render(); + getTemp(); +} + +var menu={ + "":{ + "title":" Temp. Graph" + }, + + "Widgets":{ + value:widsOn, + format:vis=>vis?"Hide":"Show", + onchange:vis=>{ + widsOn=vis; + refreshMenu(); + } + }, + + "Duration":{ + value:times.indexOf(duration), + min:0,max:times.length-1,step:1,wrap:true, + format:tim=>times[tim], + onchange:(dur)=>{ + duration=times[dur]; + } + }, + + "Draw Graph":function(){ + E.showMenu(); + drawGraph(); + }, + + "Show Graph" : function(){ + E.showMenu(); + if(graph.length>0){ + showGraph(); + }else{ + message("No graph to\nshow as no\ngraph has been\ndrawn yet."); + } + }, + + "Save Graph" : function(){ + E.showMenu(); + if(graph.length>0){ + saveGraph(); + }else{ + message("No graph to\nsave as no\ngraph has been\ndrawn yet."); + } + }, + + "Save Data" : function(){ + E.showMenu(); + if(graph.length>0){ + saveData(); + }else{ + message("No data to\nsave as no\ngraph has been\ndrawn yet."); + } + }, + + "Show Temp":function(){ + E.showMenu(); + showTemp(); + } +}; + +openMenu(); From 862494a0d7d2967643cd59c766c0dbb58d3c9dca Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 11:19:47 +1300 Subject: [PATCH 11/53] Add files via upload --- apps/tempgraph/ChangeLog | 2 ++ apps/tempgraph/README.md | 36 ++++++++++++++++++++++++++++++++ apps/tempgraph/app.png | Bin 0 -> 6941 bytes apps/tempgraph/metadata.json | 18 ++++++++++++++++ apps/tempgraph/screenshot_1.png | Bin 0 -> 3320 bytes apps/tempgraph/screenshot_2.png | Bin 0 -> 4186 bytes apps/tempgraph/screenshot_3.png | Bin 0 -> 3480 bytes 7 files changed, 56 insertions(+) create mode 100644 apps/tempgraph/ChangeLog create mode 100644 apps/tempgraph/README.md create mode 100644 apps/tempgraph/app.png create mode 100644 apps/tempgraph/metadata.json create mode 100644 apps/tempgraph/screenshot_1.png create mode 100644 apps/tempgraph/screenshot_2.png create mode 100644 apps/tempgraph/screenshot_3.png diff --git a/apps/tempgraph/ChangeLog b/apps/tempgraph/ChangeLog new file mode 100644 index 000000000..58dd75a19 --- /dev/null +++ b/apps/tempgraph/ChangeLog @@ -0,0 +1,2 @@ +0.01: 3/Feb/2023 Added 'Temperature Graph' app to depository. + diff --git a/apps/tempgraph/README.md b/apps/tempgraph/README.md new file mode 100644 index 000000000..de4a0af59 --- /dev/null +++ b/apps/tempgraph/README.md @@ -0,0 +1,36 @@ +# Temperature Graph + +**Temperature Graph** (tempgraph) is a Bangle.js 2 app for recording graphs of the temperature for various time periods from 10 minutes to 7 days long. It samples the watch's temperature sensor 150 times while creating a graph, regardless of the time period selected. + +### Menu Options +* **Widgets** Toggles the watch's widgets on and off. With them off gives you a bigger graph when viewing it. + +* **Duration** Select the time period for drawing the graph, from 10 minutes to 7 days long. + +* **Draw Graph** Draws the graph. + * Tapping the screen toggles the graph between Celsius (red) and Fahrenheit (blue). + * Pressing the watch button takes you back to the menu. **Note:** While the graph can still be viewed after returning to the menu, you can't continue recording it if you had returned to the menu before the time period was up. The graph is saved in the watch though so it's still there the next time you start the app. + +* **Show Graph** Shows the last drawn graph. + * Tapping the screen toggles the graph between Celsius (red) and Fahrenheit (blue). + * Pressing the watch button takes you back to the menu. + +* **Save Graph** Sends a screengrab of the graph to the Espruino Web IDE from where you can save it as you would any image on a webpage. + +* **Save Data** Sends a CSV file of the graph's temperature data to the Espruino Web IDE where you can save it for further use. I suggest you use the Espruino Web IDE's Terminal Logger (selected in the IDE's Settings/General) to record the data as it's sent. This is the easiest way to save it as a text file. + +* **Show Temp** Shows the current temperature. + +### Screenshots +![](screenshot_1.png) +![](screenshot_2.png) +![](screenshot_3.png) + +### Note +Using the watch in a normal fashion can raise the temperature it's sensing to quite a few degrees above the surrounding temperature and it may take half an hour or so to drop to close to the surrounding temperature. After that it seems to give quite accurate readings, assuming the thermometer I've been comparing it to is itself reasonably accurate. So best to load the app then not touch the watch for half an hour before starting a recording. This is assuming you're not wearing the app and are just using it to record the temperature where you've put the watch. You could of course wear it and it'll still draw a graph, which might also be useful. + +### Creator +Carl Read ([mail](mailto:cread98@orcon.net.nz), [github](https://github.com/CarlR9)) + +#### License +[MIT License](LICENSE) diff --git a/apps/tempgraph/app.png b/apps/tempgraph/app.png new file mode 100644 index 0000000000000000000000000000000000000000..1ae347ac837d8366797f532b8d304dc77802fd02 GIT binary patch literal 6941 zcmZ9RRZtvIv#keba0~7X1PksyFv#G+Eod0rC3t|~4ud-h1b26L4-g3M?j8u?x zJT{>|_-nX!K3m*tw5UTwcLV5{EX(@&#mfN`cHS=i>-zX)%??Q z+B6xZCFe5Y)Rx^la^L6LUm8c$woNwumnB2C@<*(j^jbB`-JjkoHG#lh zoNvTUE*$3B_C-!z@QJQPR9^{H11^YjBJHSNi8=cP(qFjWP`IsgZ#kYc7R#=>bS%dc zsd)?whTOt#k{aD$vW6<7Heli)!9rE|Ajz(F5W%cqAW3VqDB0ks;fMR)N{XnhLsRR% zp>=Ihs-aEej>Ou-jD?!`!;h1ie(b)_1Bvq^-(o~22U5Q0nGI#YaxH&`R=;chgTYqS zaLrmSQR!LvRK74FI_~el?^ek~eDmCO3*(niJ(>-{7Xq5|vco!ix1sETGKRGoQ$xON zsf1Za^Z;UZ9bRw@Z;T!m=97)R-o8z{;JCky;F~}3r!dL-Y=XHLl2lFeHoMl1v-_Y0 zxizvu2P7!bShj65pvlswv30pA$))q;1x@I&UbpD=I{Ne63?-1yu&q5X?WcZr4o`~3 z0Ad}%GOz6$8MeWg8Rv4m=VSio!$%E@=XSpL8MMpSu>-`#A=Ve*PcfoKgG5t5i5KR1 z1)1s|SHF$2{Y<&7nI!x=ciSWGt-UDHvg$KTK~>sGpeeVho-5(fT-zQ0EFfS>%fTbXj0rZ;!s|#GWl~xkMH9xD zZy-$@duK@|{JELz$8n-$&8<7PWu{wAqS;yl1X&YiSXsXJi>lLLG|{j2Qg*%2c&}P) zw|`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sP3>Q_~zeHrf_swTZE7DmWFt+1TqYhm{haDv7=#r;>n+C{M9(b`R;H^}*en zzT=xWsKVXO0tBaXbanX55~|@KrqZAOLJ(Jiz@mIuPaNB`5Kff}$BA2V`PbgH@~>`v zrGG(j-JPdgrtz*3f|Jq^?NaMc!a+J6nqqFBh$CxoQAfSPE3(?tVKLiYy}b=wvDFL^ z{ar&V8Oz+dF5*x%gfcLGRGlx-6xl8&?bgbZswcA%2-hDy)*k_+*S>bA_o zJ}o#YB}M63OC1l08|j~m;mXyCKF<5KItTU91qCza&6Wl=7mMMWrpdhnjRa_z3VLwH z3uRTGge$QMj;^q9X~z8)YhDs%m59}Be$_*Ro>1{%R5o#Y@eFB?z#D=~C!A&KoH zcS|nZS{>t;essR5DlLWm4NG$A%AL2%oO?vygDkTXq4QjX$*K-(;`8QSc^;f8h(I`XRyiE3X)YYdeSj zeL^NkMt>^DdyBV@k(Ao$UKmPaImZW;!}%u1)1@wM%0C_?9i3g{DnOix>5GL|*{g}) zwZzXM>?m;VEx+^NGU5zI(xdr{iBfXA2`z@yE?l|G%pXs=1Op z1n~Nwm)}_o|K|Xm74+Qz01k%#1cFzQq~|{q%^j*Di*|s32IR!YGpYXq03e7$Az&@* z^)rL5v3@S}4mRI|+pTNI0Ldl|UE=G?O!i=D=FkSO+~Oa}f#`@UVVkJ{9JV59gtVZ zKu)R`x^KN{`VoM%!iC)s7;=h49>W_UOpdPkZ+F)9U86+;uL`5_Nh+N+xqhaMd_cP)mQb=HxEs*r#B=GwKQdCYjthwR2G9@(^Bl6{1% V5(kw?=U-<5P+3(-m9%N_e*t{e8WjKl literal 0 HcmV?d00001 diff --git a/apps/tempgraph/metadata.json b/apps/tempgraph/metadata.json new file mode 100644 index 000000000..f714c1eef --- /dev/null +++ b/apps/tempgraph/metadata.json @@ -0,0 +1,18 @@ +{ "id": "tempgraph", + "name": "Temperature Graph", + "shortName":"Temp Graph", + "version":"0.01", + "description": "An app for recording the temperature for time periods ranging from 10 minutes to 7 days.", + "icon": "app.png", + "type": "tool", + "tags": "temperature,tempgraph,graph", + "supports" : ["BANGLEJS2"], + "readme": "README.md", + "storage": [ + {"name":"tempgraph.app.js","url":"app.js"} + ], + "data": [ + {"name":"tempgraph.json"} + ], + "screenshots": [{"url":"screenshot_1.png"},{"url":"screenshot_2.png"},{"url":"screenshot_3.png"}] +} diff --git a/apps/tempgraph/screenshot_1.png b/apps/tempgraph/screenshot_1.png new file mode 100644 index 0000000000000000000000000000000000000000..7395f289695fd5be8a03d97b8644f55cc29072db GIT binary patch literal 3320 zcmc&%c|4Tu8h*_pJ0(S9`$$TK>`RF3Ya+5w(IETUSevn=P$GL-Bg7!fjD+4g*~@OM zGqeZ^qm1U831`&#zVpZV`}>_g-uL27D5p%~=j{Mo|6#qT;hC6L3H=B#aSZ=-rYbK6xno$72nqPjb;DfH3MrYnLP#894q}Y@ugiEoZdW|BYZ9Lv|iQ< zwaI6^acXnYOx!eL%5GcT@umv_K6y&aiJFQk!#VSU?H$6)_WBO0P$x-3cpE&q>4BL5 zd$y;}fnr>$3aB)1jfwi=`)B2Nh|*9y@PiiI6wuh81kCm&907aYS&L+n0dK0L%~Rh- z*pUKy`>Weqx(|bt_?jG^5D|ILYeVHWO;N!J3;yPXmaIECbEk=Ni){s{DI=ZBm*p$= z{X6Z`xBHYmA`}t%LeRD)XV1l{sSv{$J`l%6gvw{IbR|OJ4@FzEs63Ai2tnp#|M{^L=yN-GEnwnd+I!20t zq{Vc^c;PuCMzA+#rTId;=ok1@bwzVw6EU5tVN*L*gOx1F3G0bHNK={{)}Dy*9uM(g zFQJYenODA#Q)$(46$>WGV zc@AUJSuP+B=J1GV&i&MuUnqez9z53}D?dWynXfc7)KGCmWg(ti`dLZ%dOsK6(O0b9 zi?j0JL+XDJey9nVjYLY-WgVA?E>b2*eI$S=de(urKb+Ug(ep#=B~KO^i@T8Jv_5Bt&1w`_eio?uO}^Xh(~P2VJmm_NX&Vc1Lxm&RnGH!8h@Z{GV#zLT}b(B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t z!}o08G}soG0}ZUA))X;NGST4{hq-m}^vdeffSHox0iU07M6OrsAs$`gofch{Ed#kQ zID6V#NPwMIopRRq(9d2=jxh$?Uds-2d#md9t^!MMqD93l|-vfgx7KT z!po_VW)_slIscF{@=m1)W11u4>{xd~p&0FPj3WtIzO*?Xo@yCgW|208<3=kTQWCS_RGAxU__kBhfvWde&TDtAT?(@o@b#xrdOz-Zo-}o-2U}D%e!ImGa$1zcOHr zTZ}eC`{5~&1+4EiQ8}m+dkGw9IHjk&i2|BLeGKbSY;v)mnYd9%w2k(M3ua2T7v$s> zpCHv2Oa-smUB9LmVIgaEmW1K~HR7YF_)!0Gex7>Y;sNGWt=Q$fLZQGpb&*ma%B-NZ zeOT%Z!H|LAD66}O5DN9Xj-NJAXjG;~tzK75wL2W#sLr*nS-Jj!e4rFgDdDM?7f>q& z^8iDIvHfo84djD&#&jR*!|y@P^0yYYHeKuCnu?^$Kh|o#M?Xd&Pc&&y$PBM_HG31M zRky1{E-JgdaJfbd80TG1f%vZKp;a#jzuR)fM~hLH;3F?0^k=fRhl#O7jat0lxJ~UJ zntXM}W?qC{ry?io?5!gBQ&%1R{tAROiRHz{nG{&dTI!97SpknTY)3=25G&*imiBwo z+;HRmj6=oBm0|8-ticWb>$&J|e;rv55#sk-g(jT^I8#R>R9OQj7KJ?B=q<$6cd>6h zZXBw=^^$5^cestb+TxGo?=!7QxnysZNTxJji289(|y5(K>LD z&JQ>7sTkOD)rqPlWb4)kEREHbtNAVek;Bs-@-p2;i_(UA4HzmK7GR?k$+0K~`Q-Ld zF-DDID=S{%=K3Ph-H+3pH`>N?rMBzE%(6*(LDgvWbpEMNrUpJl1eK~$xyvqFelldzHm>5{<*XkkT{tZ@2JSzYI literal 0 HcmV?d00001 diff --git a/apps/tempgraph/screenshot_2.png b/apps/tempgraph/screenshot_2.png new file mode 100644 index 0000000000000000000000000000000000000000..68d0ea236c6a513868c69eae8a5e51f995fad9f4 GIT binary patch literal 4186 zcmd6rS5p%Vu!f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gHL%)WiP!{X9izB_e>moe{Rqn}6(cCOIqX_=+ zea8euZgN5{H7D`wa>4TZZfj8i)Tbk`gijiRq-foZ)CxruA9rc1#yPV{fDoL!Ebzzm{w$S zosE2A59t#FLs#qo5A)Jy`@hgEAj)LYus1qw;{fvL_(XJSAl2YcZ=V=$t*#q@Sc*IR z27gB<$S2oSzmeN~mwFswRUzdvq)i?je-`yOiFRtn|r2W9ITbLB0 zJl(StGn1neJ@5~MVGMsH5i$#|;vQ(a7}_h7irKek7*{@`UB8ruHzS@Z+}FY~6)bAx zX=Iz#aSY={_7eW%Xl*--{Tvz8L zUHT}6clZ?X@}eQY^UcFT9;1A_WJ<);p!HYy2#Si-!{J4gL7e%(g?IgIt*abUCS#b_ z5mSPr1NcV8qxXh36%7Z4eSOp4e|k7yaS?U>Y z)xMHw8F3Cj%jNP4H@%x}I~wUr+CiRy>3++vanXZfU@p_n_voXq)-f|93q*+l^1=TB Di-xj= literal 0 HcmV?d00001 From 364c25f26a076c1707e03a7ffe1f07788543c78a Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 11:29:15 +1300 Subject: [PATCH 12/53] Update README.md --- apps/tempgraph/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/tempgraph/README.md b/apps/tempgraph/README.md index de4a0af59..919c20267 100644 --- a/apps/tempgraph/README.md +++ b/apps/tempgraph/README.md @@ -21,14 +21,14 @@ * **Show Temp** Shows the current temperature. +### Note +Using the watch in a normal fashion can raise the temperature it's sensing to quite a few degrees above the surrounding temperature and it may take half an hour or so to drop to close to the surrounding temperature. After that it seems to give quite accurate readings, assuming the thermometer I've been comparing it to is itself reasonably accurate. So best to load the app then not touch the watch for half an hour before starting a recording. This is assuming you're not wearing the app and are just using it to record the temperature where you've put the watch. You could of course wear it and it'll still draw a graph, which might also be useful. + ### Screenshots ![](screenshot_1.png) ![](screenshot_2.png) ![](screenshot_3.png) -### Note -Using the watch in a normal fashion can raise the temperature it's sensing to quite a few degrees above the surrounding temperature and it may take half an hour or so to drop to close to the surrounding temperature. After that it seems to give quite accurate readings, assuming the thermometer I've been comparing it to is itself reasonably accurate. So best to load the app then not touch the watch for half an hour before starting a recording. This is assuming you're not wearing the app and are just using it to record the temperature where you've put the watch. You could of course wear it and it'll still draw a graph, which might also be useful. - ### Creator Carl Read ([mail](mailto:cread98@orcon.net.nz), [github](https://github.com/CarlR9)) From 25cf6125fe2ea13c7ab4e39e9c8e7aec6a89e592 Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 19:10:09 +1300 Subject: [PATCH 14/53] Delete app.png --- apps/tempgraph/app.png | Bin 6941 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 apps/tempgraph/app.png diff --git a/apps/tempgraph/app.png b/apps/tempgraph/app.png deleted file mode 100644 index 1ae347ac837d8366797f532b8d304dc77802fd02..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6941 zcmZ9RRZtvIv#keba0~7X1PksyFv#G+Eod0rC3t|~4ud-h1b26L4-g3M?j8u?x zJT{>|_-nX!K3m*tw5UTwcLV5{EX(@&#mfN`cHS=i>-zX)%??Q z+B6xZCFe5Y)Rx^la^L6LUm8c$woNwumnB2C@<*(j^jbB`-JjkoHG#lh zoNvTUE*$3B_C-!z@QJQPR9^{H11^YjBJHSNi8=cP(qFjWP`IsgZ#kYc7R#=>bS%dc zsd)?whTOt#k{aD$vW6<7Heli)!9rE|Ajz(F5W%cqAW3VqDB0ks;fMR)N{XnhLsRR% zp>=Ihs-aEej>Ou-jD?!`!;h1ie(b)_1Bvq^-(o~22U5Q0nGI#YaxH&`R=;chgTYqS zaLrmSQR!LvRK74FI_~el?^ek~eDmCO3*(niJ(>-{7Xq5|vco!ix1sETGKRGoQ$xON zsf1Za^Z;UZ9bRw@Z;T!m=97)R-o8z{;JCky;F~}3r!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oM%!iC)s7;=h49>W_UOpdPkZ+F)9U86+;uL`5_Nh+N+xqhaMd_cP)mQb=HxEs*r#B=GwKQdCYjthwR2G9@(^Bl6{1% V5(kw?=U-<5P+3(-m9%N_e*t{e8WjKl From 2c479ff715a5fdab7df5cdf2fbbec5c5ac2078ff Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 19:11:26 +1300 Subject: [PATCH 15/53] Add files via upload --- apps/tempgraph/app.png | Bin 0 -> 6941 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 apps/tempgraph/app.png diff --git a/apps/tempgraph/app.png b/apps/tempgraph/app.png new file mode 100644 index 0000000000000000000000000000000000000000..1ae347ac837d8366797f532b8d304dc77802fd02 GIT binary patch literal 6941 zcmZ9RRZtvIv#keba0~7X1PksyFv#G+Eod0rC3t|~4ud-h1b26L4-g3M?j8u?x zJT{>|_-nX!K3m*tw5UTwcLV5{EX(@&#mfN`cHS=i>-zX)%??Q z+B6xZCFe5Y)Rx^la^L6LUm8c$woNwumnB2C@<*(j^jbB`-JjkoHG#lh zoNvTUE*$3B_C-!z@QJQPR9^{H11^YjBJHSNi8=cP(qFjWP`IsgZ#kYc7R#=>bS%dc zsd)?whTOt#k{aD$vW6<7Heli)!9rE|Ajz(F5W%cqAW3VqDB0ks;fMR)N{XnhLsRR% zp>=Ihs-aEej>Ou-jD?!`!;h1ie(b)_1Bvq^-(o~22U5Q0nGI#YaxH&`R=;chgTYqS zaLrmSQR!LvRK74FI_~el?^ek~eDmCO3*(niJ(>-{7Xq5|vco!ix1sETGKRGoQ$xON zsf1Za^Z;UZ9bRw@Z;T!m=97)R-o8z{;JCky;F~}3r!dL-Y=XHLl2lFeHoMl1v-_Y0 zxizvu2P7!bShj65pvlswv30pA$))q;1x@I&UbpD=I{Ne63?-1yu&q5X?WcZr4o`~3 z0Ad}%GOz6$8MeWg8Rv4m=VSio!$%E@=XSpL8MMpSu>-`#A=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209882eed0c65bafb654614bf98a066ca070d5 Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 19:38:06 +1300 Subject: [PATCH 16/53] Delete metadata.json --- apps/tempgraph/metadata.json | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 apps/tempgraph/metadata.json diff --git a/apps/tempgraph/metadata.json b/apps/tempgraph/metadata.json deleted file mode 100644 index f714c1eef..000000000 --- a/apps/tempgraph/metadata.json +++ /dev/null @@ -1,18 +0,0 @@ -{ "id": "tempgraph", - "name": "Temperature Graph", - "shortName":"Temp Graph", - "version":"0.01", - "description": "An app for recording the temperature for time periods ranging from 10 minutes to 7 days.", - "icon": "app.png", - "type": "tool", - "tags": "temperature,tempgraph,graph", - "supports" : ["BANGLEJS2"], - "readme": "README.md", - "storage": [ - {"name":"tempgraph.app.js","url":"app.js"} - ], - "data": [ - {"name":"tempgraph.json"} - ], - "screenshots": [{"url":"screenshot_1.png"},{"url":"screenshot_2.png"},{"url":"screenshot_3.png"}] -} From cfde5ea465080948271b1e0e6d58ca968a164a62 Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 19:39:07 +1300 Subject: [PATCH 17/53] Add files via upload --- apps/tempgraph/app-icon.js | 1 + apps/tempgraph/metadata.json | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 apps/tempgraph/app-icon.js create mode 100644 apps/tempgraph/metadata.json diff --git a/apps/tempgraph/app-icon.js b/apps/tempgraph/app-icon.js new file mode 100644 index 000000000..50aae4c01 --- /dev/null +++ b/apps/tempgraph/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwxH+goA/AH4AgrHXABFYF0XXkYAK64utGENYFxoABSTxeHXYJglF+UAAIQvEBApfhE4UAF4IDBFwZf/X7hfsR4K/tL96/vRwpf/X/5fJGYK/tL9u02i/tF4KOFL/6/XF4ZftR4K/tL96/vRwpf/X/5fJGYK/tL96/vRwpf/X7gADF8ouBGA4v/F/6/urAmGABFYF7pgIL0owPF0KSC64AIRj4A/AH4ACA=")) \ No newline at end of file diff --git a/apps/tempgraph/metadata.json b/apps/tempgraph/metadata.json new file mode 100644 index 000000000..ea41d67ae --- /dev/null +++ b/apps/tempgraph/metadata.json @@ -0,0 +1,19 @@ +{ "id": "tempgraph", + "name": "Temperature Graph", + "shortName":"Temp Graph", + "version":"0.01", + "description": "An app for recording the temperature for time periods ranging from 10 minutes to 7 days.", + "icon": "app.png", + "type": "tool", + "tags": "temperature,tempgraph,graph", + "supports" : ["BANGLEJS2"], + "readme": "README.md", + "storage": [ + {"name":"tempgraph.app.js","url":"app.js"}, + {"name":"tempgraph.img","url":"app-icon.js","evaluate":true} + ], + "data": [ + {"name":"tempgraph.json"} + ], + "screenshots": [{"url":"screenshot_1.png"},{"url":"screenshot_2.png"},{"url":"screenshot_3.png"}] +} From f050b75e5b4892fbbac23cf836a2c04e0ea6c12d Mon Sep 17 00:00:00 2001 From: Erik Andresen Date: Fri, 3 Feb 2023 07:45:22 +0100 Subject: [PATCH 18/53] widalarmeta: fix #2542 Fix check for active alarm, either remove brackets or add return for filter in map --- apps/widalarmeta/ChangeLog | 1 + apps/widalarmeta/metadata.json | 2 +- apps/widalarmeta/widget.js | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/widalarmeta/ChangeLog b/apps/widalarmeta/ChangeLog index 8bdf1156f..1012ee386 100644 --- a/apps/widalarmeta/ChangeLog +++ b/apps/widalarmeta/ChangeLog @@ -4,3 +4,4 @@ Add option to show seconds 0.03: Fix Bell not appearing on alarms > 24h and redrawing interval Update to match the default alarm widget, and not show itself when an alarm is hidden. +0.04: Fix check for active alarm diff --git a/apps/widalarmeta/metadata.json b/apps/widalarmeta/metadata.json index 89e35c090..aad3c4321 100644 --- a/apps/widalarmeta/metadata.json +++ b/apps/widalarmeta/metadata.json @@ -2,7 +2,7 @@ "id": "widalarmeta", "name": "Alarm & Timer ETA", "shortName": "Alarm ETA", - "version": "0.03", + "version": "0.04", "description": "A widget that displays the time to the next Alarm or Timer in hours and minutes, maximum 24h (configurable).", "icon": "widget.png", "type": "widget", diff --git a/apps/widalarmeta/widget.js b/apps/widalarmeta/widget.js index 8615aa1d2..3ad2e6ad2 100644 --- a/apps/widalarmeta/widget.js +++ b/apps/widalarmeta/widget.js @@ -9,10 +9,10 @@ function draw() { const times = alarms - .map(alarm => { + .map(alarm => alarm.hidden !== true && require("sched").getTimeToAlarm(alarm) - }) + ) .filter(a => a !== undefined); const next = times.length > 0 ? Math.min.apply(null, times) : 0; let calcWidth = 0; From 4a3e5bb5a3086a4e315c0654778b2937b2957c8f Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 19:52:25 +1300 Subject: [PATCH 19/53] Delete metadata.json --- apps/tempgraph/metadata.json | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 apps/tempgraph/metadata.json diff --git a/apps/tempgraph/metadata.json b/apps/tempgraph/metadata.json deleted file mode 100644 index ea41d67ae..000000000 --- a/apps/tempgraph/metadata.json +++ /dev/null @@ -1,19 +0,0 @@ -{ "id": "tempgraph", - "name": "Temperature Graph", - "shortName":"Temp Graph", - "version":"0.01", - "description": "An app for recording the temperature for time periods ranging from 10 minutes to 7 days.", - "icon": "app.png", - "type": "tool", - "tags": "temperature,tempgraph,graph", - "supports" : ["BANGLEJS2"], - "readme": "README.md", - "storage": [ - {"name":"tempgraph.app.js","url":"app.js"}, - {"name":"tempgraph.img","url":"app-icon.js","evaluate":true} - ], - "data": [ - {"name":"tempgraph.json"} - ], - "screenshots": [{"url":"screenshot_1.png"},{"url":"screenshot_2.png"},{"url":"screenshot_3.png"}] -} From 230baf7b24fa0be212a32e440471b7c14933b639 Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Fri, 3 Feb 2023 19:54:23 +1300 Subject: [PATCH 20/53] Add files via upload --- apps/tempgraph/metadata.json | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 apps/tempgraph/metadata.json diff --git a/apps/tempgraph/metadata.json b/apps/tempgraph/metadata.json new file mode 100644 index 000000000..6772429a5 --- /dev/null +++ b/apps/tempgraph/metadata.json @@ -0,0 +1,19 @@ +{ "id": "tempgraph", + "name": "Temperature Graph", + "shortName":"Temp Graph", + "version":"0.01", + "description": "An app for recording the temperature for time periods ranging from 10 minutes to 7 days.", + "icon": "app.png", + "type": "app", + "tags": "temperature,tempgraph,graph", + "supports" : ["BANGLEJS2"], + "readme": "README.md", + "storage": [ + {"name":"tempgraph.app.js","url":"app.js"}, + {"name":"tempgraph.img","url":"app-icon.js","evaluate":true} + ], + "data": [ + {"name":"tempgraph.json"} + ], + "screenshots": [{"url":"screenshot_1.png"},{"url":"screenshot_2.png"},{"url":"screenshot_3.png"}] +} From aa91d43fa9a37e97653355c2880b308d93c4fa38 Mon Sep 17 00:00:00 2001 From: Martin Boonk Date: Fri, 3 Feb 2023 12:49:54 +0100 Subject: [PATCH 21/53] qcenter - Cleanup timeout --- apps/qcenter/ChangeLog | 1 + apps/qcenter/app.js | 1 + apps/qcenter/metadata.json | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/qcenter/ChangeLog b/apps/qcenter/ChangeLog index 366b0ff86..436949dc9 100644 --- a/apps/qcenter/ChangeLog +++ b/apps/qcenter/ChangeLog @@ -1,3 +1,4 @@ 0.01: New App! 0.02: Fix fast loading on swipe to clock 0.03: Adds a setting for going back to clock on a timeout +0.04: Fix timeouts closing fast loaded apps \ No newline at end of file diff --git a/apps/qcenter/app.js b/apps/qcenter/app.js index f012fdda8..bd22c87e1 100644 --- a/apps/qcenter/app.js +++ b/apps/qcenter/app.js @@ -111,6 +111,7 @@ let layout = new Layout({ remove: ()=>{ Bangle.removeListener("swipe", onSwipe); Bangle.removeListener("touch", updateTimeout); + if (timeout) clearTimeout(timeout); delete Graphics.prototype.setFont8x12; } }); diff --git a/apps/qcenter/metadata.json b/apps/qcenter/metadata.json index 630fd2bef..cd3e350a4 100644 --- a/apps/qcenter/metadata.json +++ b/apps/qcenter/metadata.json @@ -2,7 +2,7 @@ "id": "qcenter", "name": "Quick Center", "shortName": "QCenter", - "version": "0.03", + "version": "0.04", "description": "An app for quickly launching your favourite apps, inspired by the control centres of other watches.", "icon": "app.png", "tags": "", From 1174faafbf2db3c4397ff4ed3158045109b2f8fe Mon Sep 17 00:00:00 2001 From: Erik Andresen Date: Fri, 3 Feb 2023 18:03:44 +0100 Subject: [PATCH 22/53] sleepphasealarm 0.14 Reduce update interval of current time when seconds are not shown --- apps/sleepphasealarm/ChangeLog | 1 + apps/sleepphasealarm/app.js | 26 ++++++++++++++++++++------ apps/sleepphasealarm/metadata.json | 2 +- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/apps/sleepphasealarm/ChangeLog b/apps/sleepphasealarm/ChangeLog index 4815e5e75..5a7be5b20 100644 --- a/apps/sleepphasealarm/ChangeLog +++ b/apps/sleepphasealarm/ChangeLog @@ -14,3 +14,4 @@ 0.11: Minor tweaks 0.12: Support javascript command to execute as defined in scheduler 'js' configuration 0.13: Fix dated events alarm on wrong date +0.14: Reduce update interval of current time when seconds are not shown diff --git a/apps/sleepphasealarm/app.js b/apps/sleepphasealarm/app.js index 0aef07760..c74303b76 100644 --- a/apps/sleepphasealarm/app.js +++ b/apps/sleepphasealarm/app.js @@ -14,6 +14,7 @@ const active = alarms.filter(alarm => require("sched").getTimeToAlarm(alarm)); const schedSettings = require("sched").getSettings(); let buzzCount = schedSettings.buzzCount; let logs = []; +let drawTimeTimeout; // Sleep/Wake detection with Estimation of Stationary Sleep-segments (ESS): // Marko Borazio, Eugen Berlin, Nagihan Kücükyildiz, Philipp M. Scholl and Kristof Van Laerhoven, "Towards a Benchmark for Wearable Sleep Analysis with Inertial Wrist-worn Sensing Units", ICHI 2014, Verona, Italy, IEEE Press, 2014. @@ -26,7 +27,7 @@ const nomothresh=0.023; // Original implementation: 6, resolution 11 bit, scale const sleepthresh=600; var ess_values = []; var slsnds = 0; -function calc_ess(acc_magn) { +function calc_ess(acc_magn) {"ram" ess_values.push(acc_magn); if (ess_values.length == winwidth) { @@ -90,10 +91,12 @@ function drawApp() { layout.alarm_date.label = `${LABEL_WAKEUP_TIME}: ${alarmHour}:${alarmMinute}`; layout.render(); - function drawTime() { + function drawTime() {"ram" + const drawSeconds = !Bangle.isLocked(); + if (Bangle.isLCDOn()) { const now = new Date(); - layout.date.label = locale.time(now, BANGLEJS2 && Bangle.isLocked() ? 1 : 0); // hide seconds on bangle 2 + layout.date.label = locale.time(now, !drawSeconds); // hide seconds on bangle 2 const diff = nextAlarmDate - now; const diffHour = Math.floor((diff % 86400000) / 3600000).toString(); const diffMinutes = Math.floor(((diff % 86400000) % 3600000) / 60000).toString(); @@ -101,11 +104,22 @@ function drawApp() { layout.render(); } - setTimeout(()=>{ + const period = drawSeconds ? 1000 : 60000; + if (this.drawTimeTimeout !== undefined) { + clearTimeout(this.drawTimeTimeout); + } + drawTimeTimeout = setTimeout(()=>{ + drawTimeTimeout = undefined; drawTime(); - }, 1000 - (Date.now() % 1000)); + }, period - (Date.now() % period)); } + Bangle.on('lock', function(on) { + if (on === false) { + drawTime(); + } + }); + drawTime(); } @@ -146,7 +160,7 @@ if (nextAlarmDate !== undefined) { layout.render(); Bangle.setOptions({powerSave: false}); // do not dynamically change accelerometer poll interval Bangle.setPollInterval(80); // 12.5Hz - Bangle.on('accel', (accelData) => { + Bangle.on('accel', (accelData) => {"ram" const now = new Date(); const acc = accelData.mag; const swest = calc_ess(acc); diff --git a/apps/sleepphasealarm/metadata.json b/apps/sleepphasealarm/metadata.json index 5382160c0..7e8d2b1a0 100644 --- a/apps/sleepphasealarm/metadata.json +++ b/apps/sleepphasealarm/metadata.json @@ -2,7 +2,7 @@ "id": "sleepphasealarm", "name": "SleepPhaseAlarm", "shortName": "SleepPhaseAlarm", - "version": "0.13", + "version": "0.14", "description": "Uses the accelerometer to estimate sleep and wake states with the principle of Estimation of Stationary Sleep-segments (ESS, see https://ubicomp.eti.uni-siegen.de/home/datasets/ichi14/index.html.en). This app will read the next alarm from the alarm application and will wake you up to 30 minutes early at the best guessed time when you are almost already awake.", "icon": "app.png", "tags": "alarm", From aedac6a4293b8a48c5e06dbd108dbab82895a96c Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Sat, 4 Feb 2023 16:05:00 +1300 Subject: [PATCH 23/53] Add files via upload --- apps/tempgraph/ChangeLog | 2 +- apps/tempgraph/app.js | 789 +++++++++++++++++++-------------------- 2 files changed, 395 insertions(+), 396 deletions(-) diff --git a/apps/tempgraph/ChangeLog b/apps/tempgraph/ChangeLog index 58dd75a19..d21f32e9a 100644 --- a/apps/tempgraph/ChangeLog +++ b/apps/tempgraph/ChangeLog @@ -1,2 +1,2 @@ 0.01: 3/Feb/2023 Added 'Temperature Graph' app to depository. - +0.02: 4/Feb/2023 Rewrote the widget handling after discovering there's a 'widget_utils' module to properly hide and show them. diff --git a/apps/tempgraph/app.js b/apps/tempgraph/app.js index a0bb3016b..d88222112 100644 --- a/apps/tempgraph/app.js +++ b/apps/tempgraph/app.js @@ -1,395 +1,394 @@ -// Temperature Graph -// BangleJS Script - -Bangle.setBarometerPower(true,"tempgraph"); -Bangle.loadWidgets(); -var wids=WIDGETS; -var widsOn=true; -var rm=null; -var gt=null; -var dg=null; -var Layout=require("Layout"); -var C=true; -var temp,tempMode,readErrCnt,watchButton2; - -var graph=require("Storage").readJSON("tempgraph.json",true); -if(graph==undefined) { - graph=[]; -} - -var timesData=[ - // dur=duration, u=time units, d=divisions on graph, s=seconds per unit. - {dur:10,u:"Mins",d:5,s:60}, - {dur:20,u:"Mins",d:4,s:60}, - {dur:30,u:"Mins",d:3,s:60}, - {dur:40,u:"Mins",d:4,s:60}, - {dur:1,u:"Hr",d:4,s:3600}, - {dur:2,u:"Hrs",d:4,s:3600}, - {dur:3,u:"Hrs",d:3,s:3600}, - {dur:4,u:"Hrs",d:4,s:3600}, - {dur:6,u:"Hrs",d:6,s:3600}, - {dur:8,u:"Hrs",d:4,s:3600}, - {dur:12,u:"Hrs",d:6,s:3600}, - {dur:16,u:"Hrs",d:4,s:3600}, - {dur:20,u:"Hrs",d:5,s:3600}, - {dur:1,u:"Day",d:4,s:3600}, - {dur:2,u:"Days",d:4,s:86400}, - {dur:3,u:"Days",d:3,s:86400}, - {dur:4,u:"Days",d:4,s:86400}, - {dur:5,u:"Days",d:5,s:86400}, - {dur:6,u:"Days",d:6,s:86400}, - {dur:7,u:"Days",d:7,s:86400} -]; -var times=[]; -for(n=0;n{ - temp=p.temperature; - if(tempMode=="drawGraph"&&graph.length>0&&Math.abs(graph[graph.length-1].temp-temp)>10&&readErrCnt<2){ - // A large change in temperature may be a reading error. ie. A 0C or less reading after - // a 20C reading. So if this happens, the reading is repeated up to 2 times to hopefully - // skip such errors. - readErrCnt++; - print("readErrCnt "+readErrCnt); - return; - } - clearInterval(gt); - readErrCnt=0; - switch (tempMode){ - case "showTemp": - showT(); - break; - case "drawGraph": - var date=new Date(); - var dateStr=require("locale").date(date).trim(); - var hrs=date.getHours(); - var mins=date.getMinutes(); - var secs=date.getSeconds(); - graph.push({ - temp:temp, - date:dateStr, - hrs:hrs, - mins:mins, - secs:secs - }); - if(graph.length==1){ - graph[0].dur=durInd; - } - require("Storage").writeJSON("tempgraph.json", graph); - if(graph.length==150){ - clearInterval(dg); - } - drawG(); - } - }); -} - -function getTemp(){ - readErrCnt=0; - gt = setInterval(getT,800); -} - -function setButton(){ - var watchButton=setWatch(function(){ - clearInterval(gt); - clearInterval(dg); - clearWatch(watchButton); - Bangle.removeListener("touch",screenTouch); - openMenu(); - },BTN); - Bangle.on('touch',screenTouch); -} - -function setButton2(){ - watchButton2=setWatch(function(){ - clearWatch(watchButton2); - openMenu(); - },BTN); -} - -function zPad(n){ - return n.toString().padStart(2,0); -} - -function screenTouch(n,ev){ - if(ev.y>23&&ev.y<152){ - C=C==false; - drawG(false); - } -} - -function drawG(){ - function cf(t){ - if(C){ - return t; - } - return getF(t); - } - drawWids(); - var top=1; - var bar=21; - var barBot=175-22; - if(widsOn){ - top=25; - bar=bar+24; - barBot=barBot-24; - } - var low=graph[0].temp; - var hi=low; - for(n=0;nt){ - low=t; - } - if(hi10){ - div=5; - } - if(C){ - g.setColor(1,0,0); - }else{ - g.setColor(0,0,1); - } - var step=(barBot-bar)/((tempHi-tempLow)/div); - for(n=0;nexit()}, - ],lazy:true - }); - drawWids(); - messageLO.render(); -} - -function showT(){ - tempLO.lab1.label=tempLO.lab3.label; - tempLO.lab2.label=tempLO.lab4.label; - tempLO.lab3.label=tempLO.lab5.label; - tempLO.lab4.label=tempLO.lab6.label; - tempLO.lab5.label=temp.toFixed(2)+"C"; - tempLO.lab6.label=getF(temp).toFixed(2)+"F"; - tempLO.render(); -} - -function exit(){ - clearWatch(watchButton2); - openMenu(); -} - -function showTemp(){ - tempMode="showTemp"; - setButton2(); - tempLO=new Layout({ - type:"v",c:[ - {type:"h",c:[ - {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab1"}, - {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab2"} - ]}, - {type:"h",c:[ - {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab3"}, - {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab4"} - ]}, - {type:"h",c:[ - {type:"txt",pad:5,col:"#f00",font:"6x8:2",label:" ",id:"lab5"}, - {type:"txt",pad:5,col:"#00f",font:"6x8:2",label:" ",id:"lab6"} - ]}, - {type:"h",c:[ - {type:"btn",pad:2,font:"6x8:2",label:"Temp",cb:l=>getTemp()}, - {type:"btn",pad:2,font:"6x8:2",label:"Exit",cb:l=>exit()} - ]} - ] - },{lazy:true}); - tempLO.render(); - getTemp(); -} - -var menu={ - "":{ - "title":" Temp. Graph" - }, - - "Widgets":{ - value:widsOn, - format:vis=>vis?"Hide":"Show", - onchange:vis=>{ - widsOn=vis; - refreshMenu(); - } - }, - - "Duration":{ - value:times.indexOf(duration), - min:0,max:times.length-1,step:1,wrap:true, - format:tim=>times[tim], - onchange:(dur)=>{ - duration=times[dur]; - } - }, - - "Draw Graph":function(){ - E.showMenu(); - drawGraph(); - }, - - "Show Graph" : function(){ - E.showMenu(); - if(graph.length>0){ - showGraph(); - }else{ - message("No graph to\nshow as no\ngraph has been\ndrawn yet."); - } - }, - - "Save Graph" : function(){ - E.showMenu(); - if(graph.length>0){ - saveGraph(); - }else{ - message("No graph to\nsave as no\ngraph has been\ndrawn yet."); - } - }, - - "Save Data" : function(){ - E.showMenu(); - if(graph.length>0){ - saveData(); - }else{ - message("No data to\nsave as no\ngraph has been\ndrawn yet."); - } - }, - - "Show Temp":function(){ - E.showMenu(); - showTemp(); - } -}; - -openMenu(); +// Temperature Graph +// BangleJS Script + +Bangle.setBarometerPower(true,"tempgraph"); +Bangle.loadWidgets(); +var widsOn=true; +var rm=null; +var gt=null; +var dg=null; +var Layout=require("Layout"); +var C=true; +var temp,tempMode,readErrCnt,watchButton2; + +var graph=require("Storage").readJSON("tempgraph.json",true); +if(graph==undefined) { + graph=[]; +} + +var timesData=[ + // dur=duration, u=time units, d=divisions on graph, s=seconds per unit. + {dur:10,u:"Mins",d:5,s:60}, + {dur:20,u:"Mins",d:4,s:60}, + {dur:30,u:"Mins",d:3,s:60}, + {dur:40,u:"Mins",d:4,s:60}, + {dur:1,u:"Hr",d:4,s:3600}, + {dur:2,u:"Hrs",d:4,s:3600}, + {dur:3,u:"Hrs",d:3,s:3600}, + {dur:4,u:"Hrs",d:4,s:3600}, + {dur:6,u:"Hrs",d:6,s:3600}, + {dur:8,u:"Hrs",d:4,s:3600}, + {dur:12,u:"Hrs",d:6,s:3600}, + {dur:16,u:"Hrs",d:4,s:3600}, + {dur:20,u:"Hrs",d:5,s:3600}, + {dur:1,u:"Day",d:4,s:3600}, + {dur:2,u:"Days",d:4,s:86400}, + {dur:3,u:"Days",d:3,s:86400}, + {dur:4,u:"Days",d:4,s:86400}, + {dur:5,u:"Days",d:5,s:86400}, + {dur:6,u:"Days",d:6,s:86400}, + {dur:7,u:"Days",d:7,s:86400} +]; +var times=[]; +for(n=0;n{ + temp=p.temperature; + if(tempMode=="drawGraph"&&graph.length>0&&Math.abs(graph[graph.length-1].temp-temp)>10&&readErrCnt<2){ + // A large change in temperature may be a reading error. ie. A 0C or less reading after + // a 20C reading. So if this happens, the reading is repeated up to 2 times to hopefully + // skip such errors. + readErrCnt++; + print("readErrCnt "+readErrCnt); + return; + } + clearInterval(gt); + readErrCnt=0; + switch (tempMode){ + case "showTemp": + showT(); + break; + case "drawGraph": + var date=new Date(); + var dateStr=require("locale").date(date).trim(); + var hrs=date.getHours(); + var mins=date.getMinutes(); + var secs=date.getSeconds(); + graph.push({ + temp:temp, + date:dateStr, + hrs:hrs, + mins:mins, + secs:secs + }); + if(graph.length==1){ + graph[0].dur=durInd; + } + require("Storage").writeJSON("tempgraph.json", graph); + if(graph.length==150){ + clearInterval(dg); + } + drawG(); + } + }); +} + +function getTemp(){ + readErrCnt=0; + gt = setInterval(getT,800); +} + +function setButton(){ + var watchButton=setWatch(function(){ + clearInterval(gt); + clearInterval(dg); + clearWatch(watchButton); + Bangle.removeListener("touch",screenTouch); + openMenu(); + },BTN); + Bangle.on('touch',screenTouch); +} + +function setButton2(){ + watchButton2=setWatch(function(){ + clearWatch(watchButton2); + openMenu(); + },BTN); +} + +function zPad(n){ + return n.toString().padStart(2,0); +} + +function screenTouch(n,ev){ + if(ev.y>23&&ev.y<152){ + C=C==false; + drawG(false); + } +} + +function drawG(){ + function cf(t){ + if(C){ + return t; + } + return getF(t); + } + drawWids(); + var top=1; + var bar=21; + var barBot=175-22; + if(widsOn){ + top=25; + bar=bar+24; + barBot=barBot-24; + } + var low=graph[0].temp; + var hi=low; + for(n=0;nt){ + low=t; + } + if(hi10){ + div=5; + } + if(C){ + g.setColor(1,0,0); + }else{ + g.setColor(0,0,1); + } + var step=(barBot-bar)/((tempHi-tempLow)/div); + for(n=0;nexit()}, + ],lazy:true + }); + drawWids(); + messageLO.render(); +} + +function showT(){ + tempLO.lab1.label=tempLO.lab3.label; + tempLO.lab2.label=tempLO.lab4.label; + tempLO.lab3.label=tempLO.lab5.label; + tempLO.lab4.label=tempLO.lab6.label; + tempLO.lab5.label=temp.toFixed(2)+"C"; + tempLO.lab6.label=getF(temp).toFixed(2)+"F"; + tempLO.render(); +} + +function exit(){ + clearWatch(watchButton2); + openMenu(); +} + +function showTemp(){ + tempMode="showTemp"; + setButton2(); + tempLO=new Layout({ + type:"v",c:[ + {type:"h",c:[ + {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab1"}, + {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab2"} + ]}, + {type:"h",c:[ + {type:"txt",pad:5,col:"#f77",font:"6x8:2",label:" ",id:"lab3"}, + {type:"txt",pad:5,col:"#77f",font:"6x8:2",label:" ",id:"lab4"} + ]}, + {type:"h",c:[ + {type:"txt",pad:5,col:"#f00",font:"6x8:2",label:" ",id:"lab5"}, + {type:"txt",pad:5,col:"#00f",font:"6x8:2",label:" ",id:"lab6"} + ]}, + {type:"h",c:[ + {type:"btn",pad:2,font:"6x8:2",label:"Temp",cb:l=>getTemp()}, + {type:"btn",pad:2,font:"6x8:2",label:"Exit",cb:l=>exit()} + ]} + ] + },{lazy:true}); + tempLO.render(); + getTemp(); +} + +var menu={ + "":{ + "title":" Temp. Graph" + }, + + "Widgets":{ + value:widsOn, + format:vis=>vis?"Hide":"Show", + onchange:vis=>{ + widsOn=vis; + refreshMenu(); + } + }, + + "Duration":{ + value:times.indexOf(duration), + min:0,max:times.length-1,step:1,wrap:true, + format:tim=>times[tim], + onchange:(dur)=>{ + duration=times[dur]; + } + }, + + "Draw Graph":function(){ + E.showMenu(); + drawGraph(); + }, + + "Show Graph" : function(){ + E.showMenu(); + if(graph.length>0){ + showGraph(); + }else{ + message("No graph to\nshow as no\ngraph has been\ndrawn yet."); + } + }, + + "Save Graph" : function(){ + E.showMenu(); + if(graph.length>0){ + saveGraph(); + }else{ + message("No graph to\nsave as no\ngraph has been\ndrawn yet."); + } + }, + + "Save Data" : function(){ + E.showMenu(); + if(graph.length>0){ + saveData(); + }else{ + message("No data to\nsave as no\ngraph has been\ndrawn yet."); + } + }, + + "Show Temp":function(){ + E.showMenu(); + showTemp(); + } +}; + +openMenu(); From 46c1ffa89311bbbb1aab22c85eec30d0b6be3cd9 Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Sat, 4 Feb 2023 19:05:16 +1300 Subject: [PATCH 24/53] Add files via upload --- apps/tempgraph/metadata.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/tempgraph/metadata.json b/apps/tempgraph/metadata.json index 6772429a5..ceb6e565f 100644 --- a/apps/tempgraph/metadata.json +++ b/apps/tempgraph/metadata.json @@ -1,7 +1,7 @@ { "id": "tempgraph", "name": "Temperature Graph", "shortName":"Temp Graph", - "version":"0.01", + "version":"0.02", "description": "An app for recording the temperature for time periods ranging from 10 minutes to 7 days.", "icon": "app.png", "type": "app", From 3ada5934776d2058926b62f5c87e836f4c428e6f Mon Sep 17 00:00:00 2001 From: Erik Andresen Date: Sat, 4 Feb 2023 09:53:05 +0100 Subject: [PATCH 25/53] sleepphasealarm: loggin on Bangle 1 Limit logging on Bangle.js 1 to one day due to low memory --- apps/sleepphasealarm/ChangeLog | 1 + apps/sleepphasealarm/README.md | 1 + apps/sleepphasealarm/app.js | 5 +++-- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/sleepphasealarm/ChangeLog b/apps/sleepphasealarm/ChangeLog index 5a7be5b20..1d4331042 100644 --- a/apps/sleepphasealarm/ChangeLog +++ b/apps/sleepphasealarm/ChangeLog @@ -15,3 +15,4 @@ 0.12: Support javascript command to execute as defined in scheduler 'js' configuration 0.13: Fix dated events alarm on wrong date 0.14: Reduce update interval of current time when seconds are not shown + Limit logging on Bangle.js 1 to one day due to low memory diff --git a/apps/sleepphasealarm/README.md b/apps/sleepphasealarm/README.md index 574e84e1e..bbf1d84ab 100644 --- a/apps/sleepphasealarm/README.md +++ b/apps/sleepphasealarm/README.md @@ -23,6 +23,7 @@ Replacing the watch strap with a more comfortable one (e.g. made of nylon) is re ## Logging For each day of month (1..31) the ESS states are logged. An entry will be overwritten in the next month, e.g. an entry on the 4th May will overwrite an entry on the 4th April. +On Bangle.js 1 only one day is logged due to low memory. The logs can be viewed with the download button: ![](screenshot.jpg) diff --git a/apps/sleepphasealarm/app.js b/apps/sleepphasealarm/app.js index c74303b76..25ca7e781 100644 --- a/apps/sleepphasealarm/app.js +++ b/apps/sleepphasealarm/app.js @@ -146,8 +146,9 @@ function addLog(time, type) { var minAlarm = new Date(); var measure = true; if (nextAlarmDate !== undefined) { - config.logs[nextAlarmDate.getDate()] = []; // overwrite log on each day of month - logs = config.logs[nextAlarmDate.getDate()]; + const logday = BANGLEJS2 ? nextAlarmDate.getDate() : 0; + config.logs[logday] = []; // overwrite log on each day of month + logs = config.logs[logday]; g.clear(); Bangle.loadWidgets(); Bangle.drawWidgets(); From de20a40100ecd75c94f557b7df91cc6fc0007a17 Mon Sep 17 00:00:00 2001 From: thyttan <6uuxstm66@mozmail.com⁩> Date: Sat, 4 Feb 2023 22:36:16 +0100 Subject: [PATCH 26/53] check for existing swipe handlers --- apps/backswipe/ChangeLog | 1 + apps/backswipe/boot.js | 4 ++-- apps/backswipe/metadata.json | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/backswipe/ChangeLog b/apps/backswipe/ChangeLog index 5560f00bc..1e5479d6e 100644 --- a/apps/backswipe/ChangeLog +++ b/apps/backswipe/ChangeLog @@ -1 +1,2 @@ 0.01: New App! +0.02: Don't fire if the app uses swipes already. diff --git a/apps/backswipe/boot.js b/apps/backswipe/boot.js index 523149e8c..31b277620 100644 --- a/apps/backswipe/boot.js +++ b/apps/backswipe/boot.js @@ -15,8 +15,8 @@ var currentFile = global.__FILE__ || ""; - if(global.BACK) delete global.BACK; - if (options && options.back && enabledForApp(currentFile)) { + if (global.BACK) delete global.BACK; + if (options && options.back && enabledForApp(currentFile) && (Bangle["#onswipe"] instanceof Array)&&Bangle["#onswipe"].length>1 ) { global.BACK = options.back; } setUI(mode, cb); diff --git a/apps/backswipe/metadata.json b/apps/backswipe/metadata.json index 7aa9f6247..0274ec8d7 100644 --- a/apps/backswipe/metadata.json +++ b/apps/backswipe/metadata.json @@ -1,7 +1,7 @@ { "id": "backswipe", "name": "Back Swipe", "shortName":"BackSwipe", - "version":"0.01", + "version":"0.02", "description": "Service that allows you to use an app's back button using left to right swipe gesture", "icon": "app.png", "tags": "back,gesture,swipe", From 12c75117820f164d9670e1afff3b162ce1e50e02 Mon Sep 17 00:00:00 2001 From: CarlR9 <108166078+CarlR9@users.noreply.github.com> Date: Sun, 5 Feb 2023 16:07:35 +1300 Subject: [PATCH 27/53] Add files via upload --- apps/tempgraph/ChangeLog | 1 + apps/tempgraph/app.js | 2 +- apps/tempgraph/metadata.json | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/tempgraph/ChangeLog b/apps/tempgraph/ChangeLog index d21f32e9a..74f2d7255 100644 --- a/apps/tempgraph/ChangeLog +++ b/apps/tempgraph/ChangeLog @@ -1,2 +1,3 @@ 0.01: 3/Feb/2023 Added 'Temperature Graph' app to depository. 0.02: 4/Feb/2023 Rewrote the widget handling after discovering there's a 'widget_utils' module to properly hide and show them. +0.03: 4/Feb/2023 Fixed number error in timesData array. diff --git a/apps/tempgraph/app.js b/apps/tempgraph/app.js index d88222112..b8dd231ae 100644 --- a/apps/tempgraph/app.js +++ b/apps/tempgraph/app.js @@ -31,7 +31,7 @@ var timesData=[ {dur:12,u:"Hrs",d:6,s:3600}, {dur:16,u:"Hrs",d:4,s:3600}, {dur:20,u:"Hrs",d:5,s:3600}, - {dur:1,u:"Day",d:4,s:3600}, + {dur:1,u:"Day",d:4,s:86400}, {dur:2,u:"Days",d:4,s:86400}, {dur:3,u:"Days",d:3,s:86400}, {dur:4,u:"Days",d:4,s:86400}, diff --git a/apps/tempgraph/metadata.json b/apps/tempgraph/metadata.json index ceb6e565f..63d4feddd 100644 --- a/apps/tempgraph/metadata.json +++ b/apps/tempgraph/metadata.json @@ -1,7 +1,7 @@ { "id": "tempgraph", "name": "Temperature Graph", "shortName":"Temp Graph", - "version":"0.02", + "version":"0.03", "description": "An app for recording the temperature for time periods ranging from 10 minutes to 7 days.", "icon": "app.png", "type": "app", From b0b1eefb01ba600e8bda0e3848498e7dd932bfcf Mon Sep 17 00:00:00 2001 From: Erik Andresen Date: Sun, 5 Feb 2023 11:38:22 +0100 Subject: [PATCH 28/53] sleepphasealarm Add plot logged data to settings --- apps/sleepphasealarm/ChangeLog | 1 + apps/sleepphasealarm/settings.js | 117 +++++++++++++++++++++++++------ 2 files changed, 98 insertions(+), 20 deletions(-) diff --git a/apps/sleepphasealarm/ChangeLog b/apps/sleepphasealarm/ChangeLog index 1d4331042..4b119b571 100644 --- a/apps/sleepphasealarm/ChangeLog +++ b/apps/sleepphasealarm/ChangeLog @@ -16,3 +16,4 @@ 0.13: Fix dated events alarm on wrong date 0.14: Reduce update interval of current time when seconds are not shown Limit logging on Bangle.js 1 to one day due to low memory + Add plot logged data to settings diff --git a/apps/sleepphasealarm/settings.js b/apps/sleepphasealarm/settings.js index a79abb598..b6fbdf60b 100644 --- a/apps/sleepphasealarm/settings.js +++ b/apps/sleepphasealarm/settings.js @@ -13,25 +13,102 @@ require('Storage').writeJSON(CONFIGFILE, config); } - // Show the menu - E.showMenu({ - "" : { "title" : "SleepPhaseAlarm" }, - 'Keep alarm enabled': { - value: !!config.settings.disableAlarm, - format: v => v?"No":"Yes", - onchange: v => { - config.settings.disableAlarm = v; - writeSettings(); + function draw(log) { + const step = 10*60*1000; // resolution 10min + const yTicks = ["sleep", "awake", "alarm"]; + const starttime = new Date(log[0].time); + const endtime = new Date(log[log.length-1].time); + + let logidx = 0; + let curtime = starttime; + const data = new Uint8Array(Math.ceil((endtime-curtime)/step) + 1); + let curval; + let logtime; + let i=0; + while(curtime < endtime) { + if (logtime === undefined || curtime > logtime) { + curval = yTicks.indexOf(log[logidx].type); + logidx++; + logtime = new Date(log[logidx].time); } - }, "< Back" : () => back(), - 'Run before alarm': { - format: v => v === 0 ? 'disabled' : v+'h', - value: config.settings.startBeforeAlarm, - min: 0, max: 23, - onchange: v => { - config.settings.startBeforeAlarm = v; - writeSettings(); - } - }, - }); + + data[i++] = curval; + curtime = new Date(curtime + step); + } + data[i] = 1; // always end with awake + + Bangle.setUI({ + mode: "custom", + back: () => selectday(), + }); + g.reset().setFont("6x8",1); + + require("graph").drawLine(g, data, { + axes: true, + x: 4, + y: Bangle.appRect.y+8, + height: Bangle.appRect.h-20, + gridx: 1, + gridy: 1, + miny: -1, + maxy: 2, + title: /*LANG*/"Wakeup " + require("locale").date(endtime, 1), + ylabel: y => y >= 0 && y <= 1 ? yTicks[y] : "", + xlabel: x => { + if (x === Math.round(data.length/10)) { + return require("locale").time(starttime, 1); + } else if (x === (data.length-2)-Math.round(data.length/10)) { + return require("locale").time(endtime, 1); + } + return ""; + }, + }); + } + + function selectday() { + E.showMessage(/*LANG*/"Loading..."); + + const logs = config.logs.filter(log => log != null && log.filter(entry => entry.type === "alarm").length > 0); + logs.sort(function(a, b) { // sort by alarm date desc + const adate = new Date(a.filter(entry => entry.type === "alarm")[0].time); + const bdate = new Date(b.filter(entry => entry.type === "alarm")[0].time); + return bdate - adate; + }); + + const menu = {}; + menu[""] = { title: /*LANG*/"Select day" }; + menu["< Back"] = () => settingsmenu(); + logs.forEach((log, i) => { + const date = new Date(log.filter(entry => entry.type === "alarm")[0].time); + menu[require("locale").date(date, 1)] = () => { E.showMenu(); draw(log); }; + }); + E.showMenu(menu); + } + + function settingsmenu() { + // Show the menu + E.showMenu({ + "" : { "title" : "SleepPhaseAlarm" }, + 'Keep alarm enabled': { + value: !!config.settings.disableAlarm, + format: v => v?"No":"Yes", + onchange: v => { + config.settings.disableAlarm = v; + writeSettings(); + } + }, "< Back" : () => back(), + 'Run before alarm': { + format: v => v === 0 ? 'disabled' : v+'h', + value: config.settings.startBeforeAlarm, + min: 0, max: 23, + onchange: v => { + config.settings.startBeforeAlarm = v; + writeSettings(); + } + }, + /*LANG*/'Select day': () => selectday(), + }); + } + + settingsmenu(); }) From 853c99e8891c0ad1ca93f4d963ecf04dbc246489 Mon Sep 17 00:00:00 2001 From: thyttan <6uuxstm66@mozmail.com⁩> Date: Sun, 5 Feb 2023 14:25:37 +0100 Subject: [PATCH 29/53] check for NOT more than one swipe handler --- apps/backswipe/boot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/backswipe/boot.js b/apps/backswipe/boot.js index 31b277620..12910fbb5 100644 --- a/apps/backswipe/boot.js +++ b/apps/backswipe/boot.js @@ -16,7 +16,7 @@ var currentFile = global.__FILE__ || ""; if (global.BACK) delete global.BACK; - if (options && options.back && enabledForApp(currentFile) && (Bangle["#onswipe"] instanceof Array)&&Bangle["#onswipe"].length>1 ) { + if (options && options.back && enabledForApp(currentFile) && !((Bangle["#onswipe"] instanceof Array)&&Bangle["#onswipe"].length>1 )) { global.BACK = options.back; } setUI(mode, cb); From 0c29640dfdc96e1e2fd3c20e8a0c3399825c1621 Mon Sep 17 00:00:00 2001 From: thyttan <6uuxstm66@mozmail.com⁩> Date: Sun, 5 Feb 2023 14:43:43 +0100 Subject: [PATCH 30/53] ud is not used --- apps/backswipe/boot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/backswipe/boot.js b/apps/backswipe/boot.js index 12910fbb5..1369c1949 100644 --- a/apps/backswipe/boot.js +++ b/apps/backswipe/boot.js @@ -22,7 +22,7 @@ setUI(mode, cb); }; - function goBack(lr, ud) { + function goBack(lr, _) { // if it is a left to right swipe if (lr === 1) { // if we're in an app that has a back button, run the callback for it From f4f07806a66cbd48d65857786de9944967f18161 Mon Sep 17 00:00:00 2001 From: Sam Sorensen <825813+sabrsorensen@users.noreply.github.com> Date: Sun, 5 Feb 2023 19:14:35 -0700 Subject: [PATCH 31/53] Added mtnclock support for reading weather.json This allows the use of owmweather or weather to provide weather updates to mtnclock. --- apps/mtnclock/app.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/apps/mtnclock/app.js b/apps/mtnclock/app.js index 28ba25882..dedf60cfd 100644 --- a/apps/mtnclock/app.js +++ b/apps/mtnclock/app.js @@ -323,6 +323,11 @@ function setWeather() { draw(a); } +function readWeather() { + data = require("Storage").readJSON('weather.json').weather; + require("Storage").write('mtnclock.json', data); +} + const _GB = global.GB; global.GB = (event) => { if (event.t==="weather") { @@ -340,6 +345,7 @@ function queueDraw() { if (drawTimeout) clearTimeout(drawTimeout); drawTimeout = setTimeout(function() { drawTimeout = undefined; + readWeather(); setWeather(); queueDraw(); }, 60000 - (Date.now() % 60000)); From 5c3b742a4275361656b734cda6037e2d68a4be25 Mon Sep 17 00:00:00 2001 From: Sam Sorensen <825813+sabrsorensen@users.noreply.github.com> Date: Sun, 5 Feb 2023 20:18:37 -0700 Subject: [PATCH 32/53] Prevent exceptions if weather.json doesn't exist. --- apps/mtnclock/app.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/apps/mtnclock/app.js b/apps/mtnclock/app.js index dedf60cfd..82d06e03b 100644 --- a/apps/mtnclock/app.js +++ b/apps/mtnclock/app.js @@ -324,8 +324,13 @@ function setWeather() { } function readWeather() { - data = require("Storage").readJSON('weather.json').weather; - require("Storage").write('mtnclock.json', data); + var weatherData = require("Storage").readJSON('weather.json', true); + if (weatherData !== undefined) { + if (weatherData.weather.time > data.time) { + data = weatherData.weather; + require("Storage").write('mtnclock.json', data); + } + } } const _GB = global.GB; From 3371f86bb5b8335d4d312ce7ca1d8ce967fc818b Mon Sep 17 00:00:00 2001 From: Sam Sorensen <825813+sabrsorensen@users.noreply.github.com> Date: Sun, 5 Feb 2023 21:39:43 -0700 Subject: [PATCH 33/53] Save minimal weather data and limit weather update frequency --- apps/mtnclock/app.js | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/apps/mtnclock/app.js b/apps/mtnclock/app.js index 82d06e03b..996fe2cee 100644 --- a/apps/mtnclock/app.js +++ b/apps/mtnclock/app.js @@ -324,19 +324,26 @@ function setWeather() { } function readWeather() { - var weatherData = require("Storage").readJSON('weather.json', true); - if (weatherData !== undefined) { - if (weatherData.weather.time > data.time) { - data = weatherData.weather; - require("Storage").write('mtnclock.json', data); - } + var weatherJson = require("Storage").readJSON('weather.json', 1); + // save updated weather data if available and it has been an hour since last updated + if (weatherJson !== undefined && (data.time === undefined || (data.time + 3600000) < weatherJson.weather.time)) { + data = { + time: weatherJson.weather.time, + temp: weatherJson.weather.temp, + code: weatherJson.weather.code + }; + require("Storage").writeJSON('mtnclock.json', data); } } const _GB = global.GB; global.GB = (event) => { if (event.t==="weather") { - data = event; + data = { + temp: event.temp, + code: event.code, + time: Date.now() + }; require("Storage").write('mtnclock.json', event); setWeather(); } @@ -357,5 +364,6 @@ function queueDraw() { } queueDraw(); +readWeather(); setWeather(); Bangle.setUI("clock"); From 653756c9172976d10a8098e780db694c1a231f49 Mon Sep 17 00:00:00 2001 From: Sam Sorensen <825813+sabrsorensen@users.noreply.github.com> Date: Sun, 5 Feb 2023 21:48:53 -0700 Subject: [PATCH 34/53] Updated version and README --- apps/mtnclock/README.md | 2 +- apps/mtnclock/metadata.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/mtnclock/README.md b/apps/mtnclock/README.md index 58538509d..066230d4e 100644 --- a/apps/mtnclock/README.md +++ b/apps/mtnclock/README.md @@ -4,7 +4,7 @@ Based on the Pebble watchface Weather Land. Mountain Pass Clock changes depending on time (day/night) and weather conditions. -This clock requires Gadgetbridge and an app that Gadgetbridge can use to get the current weather from OpenWeatherMap (e.g. Weather Notification). To set up Gadgetbridge and weather, see https://codeberg.org/Freeyourgadget/Gadgetbridge/wiki/Weather. +This clock requires Gadgetbridge and an app that Gadgetbridge can use to get the current weather from OpenWeatherMap (e.g. Weather Notification), or a Bangle app that will update weather.kson such as OWM Weather. To set up Gadgetbridge and weather, see https://codeberg.org/Freeyourgadget/Gadgetbridge/wiki/Weather. The scene will change according to the following OpenWeatherMap conditions: clear, cloudy, overcast, lightning, drizzle, rain, fog and snow. Each weather condition has night/day scenes. diff --git a/apps/mtnclock/metadata.json b/apps/mtnclock/metadata.json index a3a173069..82a0cccab 100644 --- a/apps/mtnclock/metadata.json +++ b/apps/mtnclock/metadata.json @@ -2,7 +2,7 @@ "id": "mtnclock", "name": "Mountain Pass Clock", "shortName": "Mtn Clock", - "version": "0.01", + "version": "0.02", "description": "A clock that changes scenery based on time and weather.", "readme":"README.md", "icon": "app.png", From 959e376f099fce0dedca47b43ff97c970c2f5637 Mon Sep 17 00:00:00 2001 From: Sam Sorensen <825813+sabrsorensen@users.noreply.github.com> Date: Sun, 5 Feb 2023 21:57:52 -0700 Subject: [PATCH 35/53] Fixed typo --- apps/mtnclock/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/mtnclock/README.md b/apps/mtnclock/README.md index 066230d4e..441754b83 100644 --- a/apps/mtnclock/README.md +++ b/apps/mtnclock/README.md @@ -4,7 +4,7 @@ Based on the Pebble watchface Weather Land. Mountain Pass Clock changes depending on time (day/night) and weather conditions. -This clock requires Gadgetbridge and an app that Gadgetbridge can use to get the current weather from OpenWeatherMap (e.g. Weather Notification), or a Bangle app that will update weather.kson such as OWM Weather. To set up Gadgetbridge and weather, see https://codeberg.org/Freeyourgadget/Gadgetbridge/wiki/Weather. +This clock requires Gadgetbridge and an app that Gadgetbridge can use to get the current weather from OpenWeatherMap (e.g. Weather Notification), or a Bangle app that will update weather.json such as OWM Weather. To set up Gadgetbridge and weather, see https://codeberg.org/Freeyourgadget/Gadgetbridge/wiki/Weather. The scene will change according to the following OpenWeatherMap conditions: clear, cloudy, overcast, lightning, drizzle, rain, fog and snow. Each weather condition has night/day scenes. From b2b299efc35e80ef23e07e22df62ed3e6abc38ee Mon Sep 17 00:00:00 2001 From: Sam Sorensen <825813+sabrsorensen@users.noreply.github.com> Date: Sun, 5 Feb 2023 21:59:29 -0700 Subject: [PATCH 36/53] Updated minimal weather data save from GB --- apps/mtnclock/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/mtnclock/app.js b/apps/mtnclock/app.js index 996fe2cee..c6adc7706 100644 --- a/apps/mtnclock/app.js +++ b/apps/mtnclock/app.js @@ -344,7 +344,7 @@ global.GB = (event) => { code: event.code, time: Date.now() }; - require("Storage").write('mtnclock.json', event); + require("Storage").writeJSON('mtnclock.json', data); setWeather(); } if (_GB) setTimeout(_GB, 0, event); From d426ca3656591417fa82b07c6229d53c9770d843 Mon Sep 17 00:00:00 2001 From: Gordon Williams Date: Mon, 6 Feb 2023 11:20:36 +0000 Subject: [PATCH 37/53] assistedgps 0.05: Fix regression in 0.04 that caused AGPS data not to get loaded --- apps/assistedgps/ChangeLog | 1 + apps/assistedgps/custom.html | 2 +- apps/assistedgps/metadata.json | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/assistedgps/ChangeLog b/apps/assistedgps/ChangeLog index ff2de6f67..92f04dc6d 100644 --- a/apps/assistedgps/ChangeLog +++ b/apps/assistedgps/ChangeLog @@ -2,3 +2,4 @@ 0.02: Update to work with Bangle.js 2 0.03: Select GNSS systems to use for Bangle.js 2 0.04: Now turns GPS off after upload +0.05: Fix regression in 0.04 that caused AGPS data not to get loaded diff --git a/apps/assistedgps/custom.html b/apps/assistedgps/custom.html index 75a4ecf32..716865983 100644 --- a/apps/assistedgps/custom.html +++ b/apps/assistedgps/custom.html @@ -158,7 +158,7 @@ var chunk = bin.substr(i,chunkSize); js += `\x10Serial1.write(atob("${btoa(chunk)}"))\n`; } - js = "\x10setTimeout(() => Bangle.setGPSPower(0,'agps'), 1000);\n"; // turn GPS off after a delay + js += "\x10setTimeout(() => Bangle.setGPSPower(0,'agps'), 1000);\n"; // turn GPS off after a delay return js; } diff --git a/apps/assistedgps/metadata.json b/apps/assistedgps/metadata.json index ac9fe5725..d2e7334c4 100644 --- a/apps/assistedgps/metadata.json +++ b/apps/assistedgps/metadata.json @@ -1,7 +1,7 @@ { "id": "assistedgps", "name": "Assisted GPS Updater (AGPS)", - "version": "0.04", + "version": "0.05", "description": "Downloads assisted GPS (AGPS) data to Bangle.js for faster GPS startup and more accurate fixes. **No app will be installed**, this just uploads new data to the GPS chip.", "sortorder": -1, "icon": "app.png", From aa7fdc3966c5ead721f0002746215cf6806524ae Mon Sep 17 00:00:00 2001 From: Erik Andresen Date: Mon, 6 Feb 2023 19:19:38 +0100 Subject: [PATCH 38/53] sleepphasealarm Added screenshot_log.png --- apps/sleepphasealarm/README.md | 8 ++++++-- .../{screenshot.jpg => interface.jpg} | Bin apps/sleepphasealarm/metadata.json | 3 ++- apps/sleepphasealarm/screenshot.png | Bin 0 -> 3404 bytes apps/sleepphasealarm/screenshot_log.png | Bin 0 -> 3179 bytes 5 files changed, 8 insertions(+), 3 deletions(-) rename apps/sleepphasealarm/{screenshot.jpg => interface.jpg} (100%) create mode 100644 apps/sleepphasealarm/screenshot.png create mode 100644 apps/sleepphasealarm/screenshot_log.png diff --git a/apps/sleepphasealarm/README.md b/apps/sleepphasealarm/README.md index bbf1d84ab..5aded316e 100644 --- a/apps/sleepphasealarm/README.md +++ b/apps/sleepphasealarm/README.md @@ -24,6 +24,10 @@ Replacing the watch strap with a more comfortable one (e.g. made of nylon) is re For each day of month (1..31) the ESS states are logged. An entry will be overwritten in the next month, e.g. an entry on the 4th May will overwrite an entry on the 4th April. On Bangle.js 1 only one day is logged due to low memory. -The logs can be viewed with the download button: +The logs can be plotted from the settings menu: -![](screenshot.jpg) +![](screenshot_log.png) + +The logs can also be viewed with the download button in the App Loader: + +![](interface.jpg) diff --git a/apps/sleepphasealarm/screenshot.jpg b/apps/sleepphasealarm/interface.jpg similarity index 100% rename from apps/sleepphasealarm/screenshot.jpg rename to apps/sleepphasealarm/interface.jpg diff --git a/apps/sleepphasealarm/metadata.json b/apps/sleepphasealarm/metadata.json index 7e8d2b1a0..fabd9f135 100644 --- a/apps/sleepphasealarm/metadata.json +++ b/apps/sleepphasealarm/metadata.json @@ -15,5 +15,6 @@ {"name":"sleepphasealarm.img","url":"app-icon.js","evaluate":true} ], "data": [{"name":"sleepphasealarm.json"}], - "interface": "interface.html" + "interface": "interface.html", + "screenshots": [ {"url":"screenshot.png"}, {"url":"screenshot_log.png"} ] } diff --git a/apps/sleepphasealarm/screenshot.png b/apps/sleepphasealarm/screenshot.png new file mode 100644 index 0000000000000000000000000000000000000000..769ebbbbc85b4147cced277ba7bc4afdc49f3db2 GIT binary patch literal 3404 zcmbVPX*kqf-2Ts)8Do1I+b|wmCbH9rN=&kADoZjVndGr1vhOqFX|pBSmE|#!Z5X>k z{zcYmkS4~HCKO>XNTTx2^X2{eUe|lB>zw;K*YDh4&hNhO>zrhVvo>PFa>4)rh}qd% zI`NV5-$Ww#Ykk|?B|bpHoNUa2x;OG)`5Rc6xt%kTKjM+zcK|?i%g*wobMz%{(I>B2 zbCC#ycA*SM8x!CGV5K7X2_VByyN9qdEw0!)u#ND1}kUK=jtL>|qQN&T38 zeMxkCsca?nF!a@w&X7))2E{j!^A0oNKD#d8E?-h@@m3WEnbzXiuWzwZ+gJbocy@Gk zW1iP=Ycr?SRlptNDy-g}T$8@T?f1(9dX8+MIBaF>&RH2ueT@@0@PrQs>Gu8GC*oj& zMo;j}3hj{o`jy}>LVmm&kyXJr4%g{ot4FQ}c4g8#x=+0c$p(BY+gZ0F&_7v6n(K3l zSq4%ZtQAIc3?ZHGK$`4AN#Yx{q$$$MAjA2pt0M$@@sQ@GkP8Lqaca111@FsHB5r2m z9jR0(EZ_Ai9e_+5$A=dKSyVco;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-ygIw5U1VS_b$xOP`FX(ma7?3W|> z+>A;EyY56HZhq%jgL|UZWN2E+Ifx}>8 zU4xHO82>q4IC9NnDC}P;I5H$9?Qm!w6t=DV`Pj7-DD0?}wcHZ|1R9^WE`P)d0)420 zP5-wXfIK6_+Z%uDEXUy6uGw4-ieYczqjzH2 zv0q}X+@b$gcH-_8?|PdC8HO;K_ux}glb>~`bbz~eFw_RYgSZv-CEMf45l!Sk5uU2? zn}y8%-kn;wT0;aRQR8sdx6_%P_3VHWy#H{C<0Pdyr%`W=7#9GGDeEoVIA0>k`GfRT z{BbQMIuc>;9xQg6(xg&7Q7{Ob=Cob$PwjoM%a~`P8)OAr;y-sdMVi9Z;N7KVT`|-K?!?C6Dn{JK1jMK7Lt*f}I3}I8{~X z0i=mrZCPTBA)_x7-?pPOqknaa3u)yf7=vub;;7LZ8V?t2DG#u^T-N~eStSos%$v7H zOHy7wue8%mB3l912dH(OtX#WJ;(BK4QTyDC=5O&u`05Spds)Q+m)3+pO6JwK0t5%_L$1#de|-S4%hZJLV0E9oe>tCS1h~CWvL+!TEy5|-D$a9`Luc>H*r6+lF>-!2LRgLU zn+3U4dXbk;;6CCBV+=tYw`!Dd~RzI=DcH literal 0 HcmV?d00001 diff --git a/apps/sleepphasealarm/screenshot_log.png b/apps/sleepphasealarm/screenshot_log.png new file mode 100644 index 0000000000000000000000000000000000000000..3442e36ca1a2c33e0e7d21f91d638893aa012386 GIT binary patch literal 3179 zcmd56EqzFp8QZ)on5v8iM0P=9=eY(~5nbd5SmBwBlQc6qc=?@M9V>^PRltE0Yc9hC?c zg0Z=2T9~MHxbwC#UpGKyC!ZDh_~1p*n`%}xr#q0C)a-b0&!c9Acg2qC4+)SWo0bMq zel;Fx5Te5yNI>De#(Ul5F_@dYCuFPuYtocr<(1tuuZ5M*w(}WZea)z2Ye=uN!yTS2 zqf^wFrLLQi6;sEhCsa^7AF8|nsXOO{VQiV`0%^kbMNcr!+xaJOUN~hncxUS_-`cXu zXtJ7+;%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Y=l3UqOu=Q&+ftx`z{5Ir#xV{V z68W7o-P9Oo|NfdTX(x#puB7Lv^=L||!t?2&53I@0a#oZLl>={{Yk}@n9MQ_xrBRNR zB+af;%`#szcAauo3k)h8xVC{zy?K(}b;WjKV3QS(ccqrsD|9<27G_qRhG=s;xZ@JS{q7 m(K#%(59R+l3H<|acMdS1z8d8 Date: Mon, 6 Feb 2023 18:01:04 +0100 Subject: [PATCH 39/53] agenda: show day of the week in date --- apps/agenda/ChangeLog | 1 + apps/agenda/agenda.js | 29 +++++++++++++++++------------ apps/agenda/metadata.json | 2 +- lang/it_IT.json | 10 +++++++++- 4 files changed, 28 insertions(+), 14 deletions(-) diff --git a/apps/agenda/ChangeLog b/apps/agenda/ChangeLog index 99c44a2b1..9e7151e1e 100644 --- a/apps/agenda/ChangeLog +++ b/apps/agenda/ChangeLog @@ -12,3 +12,4 @@ 0.11: Setting to use "Today" and "Yesterday" instead of dates Added dynamic, short and range fields to clkinfo 0.12: Added color field and updating clkinfo periodically (running events) +0.13: Show day of the week in date diff --git a/apps/agenda/agenda.js b/apps/agenda/agenda.js index 8afca95a9..6d2b783fd 100644 --- a/apps/agenda/agenda.js +++ b/apps/agenda/agenda.js @@ -34,8 +34,9 @@ function getDate(timestamp) { return new Date(timestamp*1000); } function formatDay(date) { + let formattedDate = Locale.dow(date,1) + " " + Locale.date(date).replace(/\d\d\d\d/,""); if (!settings.useToday) { - return Locale.date(date); + return formattedDate; } const dateformatted = date.toISOString().split('T')[0]; // yyyy-mm-dd const today = new Date(Date.now()).toISOString().split('T')[0]; // yyyy-mm-dd @@ -46,7 +47,7 @@ function formatDay(date) { if (dateformatted == tomorrow) { return /*LANG*/"Tomorrow "; } - return Locale.date(date); + return formattedDate; } } function formatDateLong(date, includeDay, allDay) { @@ -58,7 +59,7 @@ function formatDateLong(date, includeDay, allDay) { return shortTime; } function formatDateShort(date, allDay) { - return formatDay(date).replace(/\d\d\d\d/,"")+(allDay?"":Locale.time(date,1)+Locale.meridian(date)); + return formatDay(date)+(allDay?"":Locale.time(date,1)+Locale.meridian(date)); } var lines = []; @@ -75,25 +76,29 @@ function showEvent(ev) { if (titleCnt) lines.push(""); // add blank line after title if(start.getDay() == end.getDay() && start.getMonth() == end.getMonth()) includeDay = false; - if(includeDay || ev.allDay) { + if(includeDay && ev.allDay) { + //single day all day (average to avoid getting previous day) lines = lines.concat( - /*LANG*/"Start:", + g.wrapString(formatDateLong(new Date((start+end)/2), includeDay, ev.allDay), g.getWidth()-10)); + } else if(includeDay || ev.allDay) { + lines = lines.concat( + /*LANG*/"Start"+":", g.wrapString(formatDateLong(start, includeDay, ev.allDay), g.getWidth()-10), - /*LANG*/"End:", + /*LANG*/"End"+":", g.wrapString(formatDateLong(end, includeDay, ev.allDay), g.getWidth()-10)); } else { lines = lines.concat( - g.wrapString(Locale.date(start), g.getWidth()-10), + g.wrapString(formatDateShort(start,true), g.getWidth()-10), g.wrapString(/*LANG*/"Start"+": "+formatDateLong(start, includeDay, ev.allDay), g.getWidth()-10), g.wrapString(/*LANG*/"End"+": "+formatDateLong(end, includeDay, ev.allDay), g.getWidth()-10)); } if(ev.location) - lines = lines.concat(/*LANG*/"Location"+": ", g.wrapString(ev.location, g.getWidth()-10)); - if(ev.description) + lines = lines.concat("",/*LANG*/"Location"+": ", g.wrapString(ev.location, g.getWidth()-10)); + if(ev.description && ev.description.trim()) lines = lines.concat("",g.wrapString(ev.description, g.getWidth()-10)); if(ev.calName) - lines = lines.concat(/*LANG*/"Calendar"+": ", g.wrapString(ev.calName, g.getWidth()-10)); - lines = lines.concat(["",/*LANG*/"< Back"]); + lines = lines.concat("",/*LANG*/"Calendar"+": ", g.wrapString(ev.calName, g.getWidth()-10)); + lines = lines.concat("",/*LANG*/"< Back"); E.showScroller({ h : g.getFontHeight(), // height of each menu item in pixels c : lines.length, // number of menu items @@ -120,7 +125,7 @@ function showList() { CALENDAR = CALENDAR.filter(ev=>ev.timestamp + ev.durationInSeconds > now/1000); } if(CALENDAR.length == 0) { - E.showMessage("No events"); + E.showMessage(/*LANG*/"No events"); return; } E.showScroller({ diff --git a/apps/agenda/metadata.json b/apps/agenda/metadata.json index 88dd2c1bc..737568cb5 100644 --- a/apps/agenda/metadata.json +++ b/apps/agenda/metadata.json @@ -1,7 +1,7 @@ { "id": "agenda", "name": "Agenda", - "version": "0.12", + "version": "0.13", "description": "Simple agenda", "icon": "agenda.png", "screenshots": [{"url":"screenshot_agenda_overview.png"}, {"url":"screenshot_agenda_event1.png"}, {"url":"screenshot_agenda_event2.png"}], diff --git a/lang/it_IT.json b/lang/it_IT.json index 310af8580..72d7dbb51 100644 --- a/lang/it_IT.json +++ b/lang/it_IT.json @@ -200,7 +200,15 @@ "Green": "Verde", "Blue": "Blu", "Black": "Nero", - "Show Week Number": "Mostra numero settimana" + "Show Week Number": "Mostra numero settimana", + "Calendar": "Calendario", + "Start": "Inizio", + "End": "Fine", + "Location": "Posizione", + "No location": "Nessuna posizione", + "No events": "Nessun evento", + "Today": "Oggi", + "Tomorrow": "Domani" }, "//2": "App-specific overrides", "alarm": { From 61b71360c2b8960feb0be0a2f2432173b1469ab2 Mon Sep 17 00:00:00 2001 From: thyttan <6uuxstm66@mozmail.com⁩> Date: Tue, 7 Feb 2023 19:33:57 +0100 Subject: [PATCH 40/53] count # of handlers when deciding whether to go back --- apps/backswipe/boot.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/apps/backswipe/boot.js b/apps/backswipe/boot.js index 1369c1949..8acd5244c 100644 --- a/apps/backswipe/boot.js +++ b/apps/backswipe/boot.js @@ -22,11 +22,21 @@ setUI(mode, cb); }; + function countHandlers(eventType) { + if (Bangle["#on"+eventType] === undefined) { + return 0; + } else if (Bangle["#on"+eventType] instanceof Array) { + return Bangle["#on"+eventType].length; + } else if (Bangle["#on"+eventType] !== undefiened) { + return 1; + } + } + function goBack(lr, _) { // if it is a left to right swipe if (lr === 1) { // if we're in an app that has a back button, run the callback for it - if (global.BACK) { + if (global.BACK && countHandlers("swipe")<4 && countHandlers("drag")<1) { // # of allowed handlers should be user configurable in settings global.BACK(); } } From 23e345202aedf2e85556efd2e98ff54c22aadc74 Mon Sep 17 00:00:00 2001 From: thyttan <6uuxstm66@mozmail.com⁩> Date: Tue, 7 Feb 2023 19:40:07 +0100 Subject: [PATCH 41/53] remove some bool --- apps/backswipe/boot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/backswipe/boot.js b/apps/backswipe/boot.js index 8acd5244c..337718dec 100644 --- a/apps/backswipe/boot.js +++ b/apps/backswipe/boot.js @@ -16,7 +16,7 @@ var currentFile = global.__FILE__ || ""; if (global.BACK) delete global.BACK; - if (options && options.back && enabledForApp(currentFile) && !((Bangle["#onswipe"] instanceof Array)&&Bangle["#onswipe"].length>1 )) { + if (options && options.back && enabledForApp(currentFile)) { global.BACK = options.back; } setUI(mode, cb); From 4649f908d075f9a5ac09311d49d2b2560a5f07d4 Mon Sep 17 00:00:00 2001 From: thyttan <6uuxstm66@mozmail.com⁩> Date: Tue, 7 Feb 2023 20:28:22 +0100 Subject: [PATCH 42/53] add settings for standard # of swipe and drag handlers --- apps/backswipe/boot.js | 4 ++-- apps/backswipe/settings.js | 46 ++++++++++++++++++++++++++++---------- 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/apps/backswipe/boot.js b/apps/backswipe/boot.js index 337718dec..e46f902eb 100644 --- a/apps/backswipe/boot.js +++ b/apps/backswipe/boot.js @@ -27,7 +27,7 @@ return 0; } else if (Bangle["#on"+eventType] instanceof Array) { return Bangle["#on"+eventType].length; - } else if (Bangle["#on"+eventType] !== undefiened) { + } else if (Bangle["#on"+eventType] !== undefined) { return 1; } } @@ -36,7 +36,7 @@ // if it is a left to right swipe if (lr === 1) { // if we're in an app that has a back button, run the callback for it - if (global.BACK && countHandlers("swipe")<4 && countHandlers("drag")<1) { // # of allowed handlers should be user configurable in settings + if (global.BACK && countHandlers("swipe")<=settings.standardNumSwipeHandlers && countHandlers("drag")<=settings.standardNumDragHandlers) { global.BACK(); } } diff --git a/apps/backswipe/settings.js b/apps/backswipe/settings.js index 2c29e86f8..3eb1fb377 100644 --- a/apps/backswipe/settings.js +++ b/apps/backswipe/settings.js @@ -4,19 +4,21 @@ // Apps is an array of app info objects, where all the apps that are there are either blocked or allowed, depending on the mode var DEFAULTS = { 'mode': 0, - 'apps': [] + 'apps': [], + 'standardNumSwipeHandlers': 0, + 'standardNumDragHandlers': 0 }; - + var settings = {}; - + var loadSettings = function() { settings = require('Storage').readJSON(FILE, 1) || DEFAULTS; - } - + }; + var saveSettings = function(settings) { require('Storage').write(FILE, settings); - } - + }; + // Get all app info files var getApps = function() { var apps = require('Storage').list(/\.info$/).map(appInfoFileName => { @@ -35,8 +37,8 @@ return 0; }); return apps; - } - + }; + var showMenu = function() { var menu = { '': { 'title': 'Backswipe' }, @@ -55,11 +57,31 @@ }, 'App List': () => { showAppSubMenu(); + }, + 'standard # of swipe handlers' : { // If more than this many handlers are present backswipe will not go back + value: 0|settings.standardNumSwipeHandlers, + min: 0, + max: 10, + format: v=>v, + onchange: v => { + settings.standardNumSwipeHandlers = v; + saveSettings(settings); + }, + }, + 'standard # of drag handlers' : { // If more than this many handlers are present backswipe will not go back + value: 0|settings.standardNumDragHandlers, + min: 0, + max: 10, + format: v=>v, + onchange: v => { + settings.standardNumDragHandlers = v; + saveSettings(settings); + }, } }; - + E.showMenu(menu); - } + }; var showAppSubMenu = function() { var menu = { @@ -101,4 +123,4 @@ loadSettings(); showMenu(); -}) \ No newline at end of file +}) From db9bc005104523e8acfc8dbc7b168fce218094e5 Mon Sep 17 00:00:00 2001 From: Gordon Williams Date: Wed, 8 Feb 2023 09:29:40 +0000 Subject: [PATCH 43/53] fix sanity check warning --- apps/mtnclock/ChangeLog | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 apps/mtnclock/ChangeLog diff --git a/apps/mtnclock/ChangeLog b/apps/mtnclock/ChangeLog new file mode 100644 index 000000000..cbf5c7f40 --- /dev/null +++ b/apps/mtnclock/ChangeLog @@ -0,0 +1,2 @@ +0.01: New App! +0.02: Get weather from weather.json From 489c96d9baaf2a85dd7f2185f9e6bf1a6aebb85a Mon Sep 17 00:00:00 2001 From: Gordon Williams Date: Wed, 8 Feb 2023 09:30:07 +0000 Subject: [PATCH 44/53] Add LEGO remote control --- apps/legoremote/ChangeLog | 1 + apps/legoremote/README.md | 28 ++++++++++++++ apps/legoremote/app-icon.js | 1 + apps/legoremote/app.js | 70 ++++++++++++++++++++++++++++++++++ apps/legoremote/app.png | Bin 0 -> 14820 bytes apps/legoremote/metadata.json | 14 +++++++ 6 files changed, 114 insertions(+) create mode 100644 apps/legoremote/ChangeLog create mode 100644 apps/legoremote/README.md create mode 100644 apps/legoremote/app-icon.js create mode 100644 apps/legoremote/app.js create mode 100644 apps/legoremote/app.png create mode 100644 apps/legoremote/metadata.json diff --git a/apps/legoremote/ChangeLog b/apps/legoremote/ChangeLog new file mode 100644 index 000000000..5560f00bc --- /dev/null +++ b/apps/legoremote/ChangeLog @@ -0,0 +1 @@ +0.01: New App! diff --git a/apps/legoremote/README.md b/apps/legoremote/README.md new file mode 100644 index 000000000..a95b7b154 --- /dev/null +++ b/apps/legoremote/README.md @@ -0,0 +1,28 @@ +# LEGO Remote control + +This app allows you to control LEGO models from Bangle.js + +Right now the only supported control device is the Mould King M-0006 +Bluetooth remote for LEGO Power Functions: http://www.espruino.com/LEGO+Power+Functions+Clone + +LEGO Power Functions does not have an official Bluetooth remote controller. Hopefully +in the future this app will be able to support other types of remote (see below). + +## Usage + +Run the app, and ensure you're not connected to your watch via Bluetooth +(a warning will pop up if so). + +Now press the arrow keys on the screen to control the robot. + +It is expected that the robot is controlled by two motors, one on the left +side (connected to the `A` output) and one on the right (connected to the `B` output). + +## Future additions + +In the future it would be great to add: + +* Recording a series of movements and playing them back +* Support for official LEGO bluetooth remotes (via [Pybricks](https://pybricks.com/)) +* Support for different robot styles and configurations +* Using the Bangle's compass (or even GPS) to allow better robot control. diff --git a/apps/legoremote/app-icon.js b/apps/legoremote/app-icon.js new file mode 100644 index 000000000..850e0eda6 --- /dev/null +++ b/apps/legoremote/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEw4X/8H5A4NH/4ABJf4A/AFMC1Uq1QABhWqBYYJDAAegBYWqxWogWohQBCBYWpqsVqoABytVBYUC0u5rf5rf1q/xtQLBhWW/t//2/AYVKBYWX/u//z3B3//rRGCr/1/+H/v9/1/BYn2/lT+v6/oXDlF/4//9/78/5F4epv/X//f7/3+v9I4Wp38b/9v7//+4LD0P/HgN/7f/EgMoBYOlJ4IACDAP1O4QLH6ibCBYI7Br/+qf/iwLC1NIquhq2lquprWAWQVVoNVgtU0NVlQLCZQ7XDbgLWJEgOCdgLZBdwgA/AH4AaA")) diff --git a/apps/legoremote/app.js b/apps/legoremote/app.js new file mode 100644 index 000000000..1c76a54a8 --- /dev/null +++ b/apps/legoremote/app.js @@ -0,0 +1,70 @@ +var lego = require("mouldking"); +lego.start(); +E.on('kill', () => { + // return to normal Bluetooth advertising + NRF.setAdvertising({},{showName:true}); +}); +// You must leave one second after 'start' to allow the remote to be paired + +var arrowIcon = atob("IiiBAAAAwAAAAPwAAAB/gAAAP/AAAB/+AAAP/8AAB//4AAP//wAA///gAH///AA///8AH///4A////wH////gf////D////8f////5/////n////+f////4AP/8AAA//wAAD//AAAP/8AAA//wAAD//AAAH/8AAAf/wAAB//AAAH/8AAAf/gAAB/+AAAH/4AAAf/gAAB/+AAAH/4AAAP/gAAA/+AAAD/wAAAD8AA"); +var controlState = ""; + +Bangle.loadWidgets(); +Bangle.drawWidgets(); +var R = Bangle.appRect; +// we'll divide up into 3x3 +function getBoxCoords(x,y) { + return { + x : R.x + R.w*x/3, + y : R.y + R.h*y/3 + }; +} + +function draw() { + g.reset().clearRect(R); + var c, ninety = Math.PI/2; + var colOn = "#f00", colOff = g.theme.fg; + c = getBoxCoords(1.5, 0.5); + g.setColor(controlState=="up"?colOn:colOff).drawImage(arrowIcon,c.x,c.y,{rotate:0}); + c = getBoxCoords(2.5, 1.5); + g.setColor(controlState=="right"?colOn:colOff).drawImage(arrowIcon,c.x,c.y,{rotate:ninety}); + c = getBoxCoords(0.5, 1.5); + g.setColor(controlState=="left"?colOn:colOff).drawImage(arrowIcon,c.x,c.y,{rotate:-ninety}); + c = getBoxCoords(1.5, 1.5); + g.setColor(controlState=="down"?colOn:colOff).drawImage(arrowIcon,c.x,c.y,{rotate:ninety*2}); + if (NRF.getSecurityStatus().connected) { + c = getBoxCoords(1.5, 2.5); + g.setFontAlign(0,0).setFont("6x8").drawString("WARNING:\nBluetooth Connected\nYou must disconnect\nbefore LEGO will work",c.x,c.y); + } +} +draw(); +NRF.on('connect', draw); +NRF.on('disconnect', draw); + +function setControlState(s) { + controlState = s; + var c = {}; + var speed = 3; + if (s=="up") c={a:-speed,b:-speed}; + if (s=="down") c={a:speed,b:speed}; + if (s=="left") c={a:speed,b:-speed}; + if (s=="right") c={a:-speed,b:speed}; + draw(); + lego.set(c); +} + +Bangle.on('drag',e => { + var x = Math.floor(E.clip((e.x - R.x) * 3 / R.w,0,2.99)); + var y = Math.floor(E.clip((e.y - R.y) * 3 / R.h,0,2.99)); + if (!e.b) { + setControlState(""); + return; + } + if (y==0) { // top row + if (x==1) setControlState("up"); + } else if (y==1) { + if (x==0) setControlState("left"); + if (x==1) setControlState("down"); + if (x==2) setControlState("right"); + } +}); diff --git a/apps/legoremote/app.png b/apps/legoremote/app.png new file mode 100644 index 0000000000000000000000000000000000000000..727049e2ba713fe02ab9bcf97e8a9c52e0168b96 GIT binary patch literal 14820 zcmeHtWmFu^*6!eLL4q?35}W}BcZZ8{%Q*?T{=t5(-^MJOvuW1teF0ssIESs4kH=U?#e6B+UOstNle z3;+O;d#h==su+6!9i1J_t!$w{S1(5>5b9}V4gh$ro@K~7Q}ZTB-tkCMz+5|$MuB{T zg#3E2c!UGXamD`hxv>W;T;wu15vw4^mNqq0k3_)Si& zyT|3-ueKk8Iy3JKUih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2F)6S{X``pp_)2APW<+^v8=3Y{KLcBuijlh`C^5C zwE~=f1s^0nm=+DMM*LC~fWfa~26TV#j~=5ENY0RZ`?k}a9ucAqn`?f4KH%u&Wanys48qA7pPXD&lbDiHa;Ru(O4VY&zSA23r^Q47 z(9zN1@%;&js6!q5U?uc*;j)m#kKLb#BOf(~yB%h^)v17`+wYODL@}%1r0(b|hU3>A zNrQKfZh-WR40<}cY3Rhn#54XIL&F-l+O@Os9AU$yHrL}9R#sM(hCK#{>gwt+wO`73 z2Pd2T4MTcve3g)^LodP((VK=EzI$xSeK+guI{^YTRBwXB_)H0jV#>cx}1 z)2|MhD#B0fw^;QNfuGz&2Y^jKqGwSM5y{%xGPxX14()z@__CVHiyPGEKVwPF%bV8R z%%$IKIRk38T@iD2g_M_HZHG}@E$TXKyLY%{ou1liROu9HHaw^Evj<+y;Ovn11&tqf zcKKDg!c}3x#CXkS*6JnQ-PuOqQqA0r4TBg`UNK2Y1eO#uoEhl)`g&4I%JoMQ2gluy z7;5TY$ko-Mj*f9u(lNDeUo-$4UWa6eNJwrz>grBBq@CY)-m9sp)!u%h&Gw~5Ku2x# z+0vU5Y@8F#Juwbv|C*A{zxS&iVaTYkv@|>f?d9ysiYydLE-Xmqs~fKf;8LtTR%+D+K9BC_f$?mZRKOEE z_S3-ZJ$mQUz3T@dqXm<9?>Oe~Hg^S-lTdjZ;{28MeZ!Xg))d91m0wPA(VhOfAr&wc zy-m7P1nYB+_10v|_1kjQdc1q3(1m+{w<(a=JB9WlLaz3*BT~`*0}riwQc6z71Zy*m zli_RlQdkO}Ezh;a^R)7@C$=K)@ch*n8? Date: Wed, 8 Feb 2023 12:29:49 +0100 Subject: [PATCH 45/53] add readme --- apps/backswipe/README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 apps/backswipe/README.md diff --git a/apps/backswipe/README.md b/apps/backswipe/README.md new file mode 100644 index 000000000..7f0e2f6be --- /dev/null +++ b/apps/backswipe/README.md @@ -0,0 +1,16 @@ +Service that allows you to use an app's back button using left to right swipe gesture. + +## Settings + +Mode: Blacklist/Whitelist/Always On/Disabled +App List: Black-/whitelisted apps +standard # of swipe handlers: 0-10 +standard # of drag handlers: 0-10 + +Standard # of handlers settings are used to fine tune when backswipe should trigger the back function. E.g. when using a keyboard that works on drags, we don't want the backswipe to trigger when we just wanted to select a letter. This might not be able to cover all cases however. + +## Creator +Kedlub + +## Contributors +thyttan From c9dabdf680b8da0f5da3b93899db84337aabd9ff Mon Sep 17 00:00:00 2001 From: thyttan <6uuxstm66@mozmail.com⁩> Date: Wed, 8 Feb 2023 12:39:27 +0100 Subject: [PATCH 46/53] Capitalization --- apps/backswipe/README.md | 4 ++-- apps/backswipe/settings.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/backswipe/README.md b/apps/backswipe/README.md index 7f0e2f6be..fd6dd29b6 100644 --- a/apps/backswipe/README.md +++ b/apps/backswipe/README.md @@ -4,8 +4,8 @@ Service that allows you to use an app's back button using left to right swipe ge Mode: Blacklist/Whitelist/Always On/Disabled App List: Black-/whitelisted apps -standard # of swipe handlers: 0-10 -standard # of drag handlers: 0-10 +Standard # of swipe handlers: 0-10 +Standard # of drag handlers: 0-10 Standard # of handlers settings are used to fine tune when backswipe should trigger the back function. E.g. when using a keyboard that works on drags, we don't want the backswipe to trigger when we just wanted to select a letter. This might not be able to cover all cases however. diff --git a/apps/backswipe/settings.js b/apps/backswipe/settings.js index 3eb1fb377..42ca7ae7d 100644 --- a/apps/backswipe/settings.js +++ b/apps/backswipe/settings.js @@ -58,7 +58,7 @@ 'App List': () => { showAppSubMenu(); }, - 'standard # of swipe handlers' : { // If more than this many handlers are present backswipe will not go back + 'Standard # of swipe handlers' : { // If more than this many handlers are present backswipe will not go back value: 0|settings.standardNumSwipeHandlers, min: 0, max: 10, @@ -68,7 +68,7 @@ saveSettings(settings); }, }, - 'standard # of drag handlers' : { // If more than this many handlers are present backswipe will not go back + 'Standard # of drag handlers' : { // If more than this many handlers are present backswipe will not go back value: 0|settings.standardNumDragHandlers, min: 0, max: 10, From 8b7e152c83933b56c626d271439354478071fea5 Mon Sep 17 00:00:00 2001 From: thyttan <6uuxstm66@mozmail.com⁩> Date: Wed, 8 Feb 2023 12:42:02 +0100 Subject: [PATCH 47/53] add to readme --- apps/backswipe/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/backswipe/README.md b/apps/backswipe/README.md index fd6dd29b6..1611263bb 100644 --- a/apps/backswipe/README.md +++ b/apps/backswipe/README.md @@ -4,8 +4,9 @@ Service that allows you to use an app's back button using left to right swipe ge Mode: Blacklist/Whitelist/Always On/Disabled App List: Black-/whitelisted apps -Standard # of swipe handlers: 0-10 -Standard # of drag handlers: 0-10 +Standard # of swipe handlers: 0-10 (Default: 0, must be changed for backswipe to work at all) +Standard # of drag handlers: 0-10 (Default: 0, must be changed for backswipe to work at all) + Standard # of handlers settings are used to fine tune when backswipe should trigger the back function. E.g. when using a keyboard that works on drags, we don't want the backswipe to trigger when we just wanted to select a letter. This might not be able to cover all cases however. From 2538d417ad9336f22410628e2c4e0dd1f3545036 Mon Sep 17 00:00:00 2001 From: KungPhoo Date: Wed, 8 Feb 2023 13:59:38 +0100 Subject: [PATCH 48/53] Change colour Changes the to yellow on < 50% and red on < 20% battery percentage. --- apps/widbat/widget.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/widbat/widget.js b/apps/widbat/widget.js index a8a0c5382..7fce16335 100644 --- a/apps/widbat/widget.js +++ b/apps/widbat/widget.js @@ -31,7 +31,11 @@ x+=16; } g.setColor(g.theme.fg).fillRect(x,y+2,x+s-4,y+21).clearRect(x+2,y+4,x+s-6,y+19).fillRect(x+s-3,y+10,x+s,y+14); - g.setColor("#0f0").fillRect(x+4,y+6,x+4+E.getBattery()*(s-12)/100,y+17); + var battery = E.getBattery(); + if(battery < 20) {g.setColor("#f00");} + else if (battery < 50) {g.setColor("#ff0");} + else {g.setColor("#0f0");} + g.fillRect(x+4,y+6,x+4+battery*(s-12)/100,y+17); }}; setWidth(); })() From 26589fa779c0a3a34679c36a214dbb4c14ffa1cb Mon Sep 17 00:00:00 2001 From: KungPhoo Date: Wed, 8 Feb 2023 14:06:46 +0100 Subject: [PATCH 49/53] Update ChangeLog --- apps/widbat/ChangeLog | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/widbat/ChangeLog b/apps/widbat/ChangeLog index 5986ecf3f..59c58af32 100644 --- a/apps/widbat/ChangeLog +++ b/apps/widbat/ChangeLog @@ -6,3 +6,4 @@ 0.07: Move CHARGING variable to more readable string 0.08: Ensure battery updates every 60s even if LCD was on at boot and stays on 0.09: Misc speed/memory tweaks +0.10: Color changes due to the battery level From 50a66490909fd7bbc2cb20c57e2e7a5196f81dd3 Mon Sep 17 00:00:00 2001 From: KungPhoo Date: Wed, 8 Feb 2023 14:10:10 +0100 Subject: [PATCH 50/53] Update version --- apps/widbat/metadata.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/widbat/metadata.json b/apps/widbat/metadata.json index 993310eb2..5f0d1b7d1 100644 --- a/apps/widbat/metadata.json +++ b/apps/widbat/metadata.json @@ -1,7 +1,7 @@ { "id": "widbat", "name": "Battery Level Widget", - "version": "0.09", + "version": "0.10", "description": "Show the current battery level and charging status in the top right of the clock", "icon": "widget.png", "type": "widget", From 6439062d922cea0fdedcecef3a6480c4ea3ff652 Mon Sep 17 00:00:00 2001 From: Sam Sorensen <825813+sabrsorensen@users.noreply.github.com> Date: Wed, 8 Feb 2023 22:37:39 -0700 Subject: [PATCH 51/53] Addressed undefined weather timestamp --- apps/mtnclock/ChangeLog | 1 + apps/mtnclock/app.js | 2 +- apps/mtnclock/metadata.json | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/mtnclock/ChangeLog b/apps/mtnclock/ChangeLog index cbf5c7f40..98cd0cc94 100644 --- a/apps/mtnclock/ChangeLog +++ b/apps/mtnclock/ChangeLog @@ -1,2 +1,3 @@ 0.01: New App! 0.02: Get weather from weather.json +0.03: Address unexpected undefined when reading weather.json \ No newline at end of file diff --git a/apps/mtnclock/app.js b/apps/mtnclock/app.js index c6adc7706..a65382dec 100644 --- a/apps/mtnclock/app.js +++ b/apps/mtnclock/app.js @@ -326,7 +326,7 @@ function setWeather() { function readWeather() { var weatherJson = require("Storage").readJSON('weather.json', 1); // save updated weather data if available and it has been an hour since last updated - if (weatherJson !== undefined && (data.time === undefined || (data.time + 3600000) < weatherJson.weather.time)) { + if (weatherJson && weatherJson.weather && weatherJson.weather.time && (data.time === undefined || (data.time + 3600000) < weatherJson.weather.time)) { data = { time: weatherJson.weather.time, temp: weatherJson.weather.temp, diff --git a/apps/mtnclock/metadata.json b/apps/mtnclock/metadata.json index 82a0cccab..2d3d0a02f 100644 --- a/apps/mtnclock/metadata.json +++ b/apps/mtnclock/metadata.json @@ -2,7 +2,7 @@ "id": "mtnclock", "name": "Mountain Pass Clock", "shortName": "Mtn Clock", - "version": "0.02", + "version": "0.03", "description": "A clock that changes scenery based on time and weather.", "readme":"README.md", "icon": "app.png", From 65d369f049668c618379da550f416b08e188e6e1 Mon Sep 17 00:00:00 2001 From: Gordon Williams Date: Thu, 9 Feb 2023 10:43:47 +0000 Subject: [PATCH 52/53] added textinput dependency --- apps/mitherm/metadata.json | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/mitherm/metadata.json b/apps/mitherm/metadata.json index a8da6fd26..e44d4ff52 100644 --- a/apps/mitherm/metadata.json +++ b/apps/mitherm/metadata.json @@ -8,6 +8,7 @@ "tags": "xiaomi,mi,ble,bluetooth,thermometer,humidity", "readme": "README.md", "supports": ["BANGLEJS", "BANGLEJS2"], + "dependencies": {"textinput":"type"}, "storage": [ {"name":"mitherm.app.js","url":"app.js"}, {"name":"mitherm.img","url":"app-icon.js","evaluate":true} From 486ca23c4c2cc2e7881b1a2658290647c4564730 Mon Sep 17 00:00:00 2001 From: Rob Pilling Date: Thu, 9 Feb 2023 18:10:56 +0000 Subject: [PATCH 53/53] Regenerate typescript / main.d.ts This regenerates `main.d.ts` from [`build_types.js`] in the espruino repo, after [updates to optionals and other changes]. The main changes are new modules, and some older typings that might have not been regenerated since their jsdoc/comments changed. New module typings: - CC3000 - ESP8266 - Flash - NetworkJS - Storage - TelnetServer - WIZnet - Wifi - crypto - dgram - fs - heatshrink - http - neopixel - net - tensorflow - tls - tv [`build_types.js`]: https://github.com/espruino/Espruino/blob/149a7f6bace3a56c1892de47bd8baacfb3f496a5/scripts/build_types.js [updates to optionals and other changes]: https://github.com/espruino/Espruino/pull/2322 --- typescript/types/main.d.ts | 17882 ++++++++++++++++++----------------- 1 file changed, 9086 insertions(+), 8796 deletions(-) diff --git a/typescript/types/main.d.ts b/typescript/types/main.d.ts index 89921972c..cd7b364a6 100644 --- a/typescript/types/main.d.ts +++ b/typescript/types/main.d.ts @@ -1,4 +1,5 @@ -// NOTE: This file has been automatically generated. +// Type definitions for Espruino latest +// Project: http://www.espruino.com/, https://github.com/espruino/espruinotools// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -34,6 +35,7 @@ type MenuOptions = { back?: () => void; selected?: number; fontHeight?: number; + scroll?: number; x?: number; y?: number; x2?: number; @@ -69,67 +71,6 @@ type MenuInstance = { select: () => void; }; -type ImageObject = { - width: number; - height: number; - bpp?: number; - buffer: ArrayBuffer | string; - transparent?: number; - palette?: Uint16Array; -}; - -type Image = string | ImageObject | ArrayBuffer | Graphics; - -type ColorResolvable = number | `#${string}`; - -type FontName = - | "4x4" - | "4x4Numeric" - | "4x5" - | "4x5Numeric" - | "4x8Numeric" - | "5x7Numeric7Seg" - | "5x9Numeric7Seg" - | "6x8" - | "6x12" - | "7x11Numeric7Seg" - | "8x12" - | "8x16" - | "Dennis8" - | "Cherry6x10" - | "Copasectic40x58Numeric" - | "Dylex7x13" - | "HaxorNarrow7x17" - | "Sinclair" - | "Teletext10x18Mode7" - | "Teletext5x9Ascii" - | "Teletext5x9Mode7" - | "Vector"; - -type FontNameWithScaleFactor = - | FontName - | `${FontName}:${number}` - | `${FontName}:${number}x${number}`; - -type Theme = { - fg: number; - bg: number; - fg2: number; - bg2: number; - fgH: number; - bgH: number; - dark: boolean; -}; - -type NRFFilters = { - services?: string[]; - name?: string; - namePrefix?: string; - id?: string; - serviceData?: object; - manufacturerData?: object; -}; - declare const BTN1: Pin; declare const BTN2: Pin; declare const BTN3: Pin; @@ -227,12 +168,69 @@ type BangleOptions = { lockTimeout: number; lcdPowerTimeout: number; backlightTimeout: number; + btnLoadTimeout: number; }; -interface ArrayLike { - readonly length: number; - readonly [n: number]: T; -} +type NRFFilters = { + services?: string[]; + name?: string; + namePrefix?: string; + id?: string; + serviceData?: object; + manufacturerData?: object; +}; + +type ImageObject = { + width: number; + height: number; + bpp?: number; + buffer: ArrayBuffer | string; + transparent?: number; + palette?: Uint16Array; +}; + +type Image = string | ImageObject | ArrayBuffer | Graphics; + +type ColorResolvable = number | `#${string}`; + +type FontName = + | "4x4" + | "4x4Numeric" + | "4x5" + | "4x5Numeric" + | "4x8Numeric" + | "5x7Numeric7Seg" + | "5x9Numeric7Seg" + | "6x8" + | "6x12" + | "7x11Numeric7Seg" + | "8x12" + | "8x16" + | "Dennis8" + | "Cherry6x10" + | "Copasectic40x58Numeric" + | "Dylex7x13" + | "HaxorNarrow7x17" + | "Sinclair" + | "Teletext10x18Mode7" + | "Teletext5x9Ascii" + | "Teletext5x9Mode7" + | "Vector"; + +type FontNameWithScaleFactor = + | FontName + | `${FontName}:${number}` + | `${FontName}:${number}x${number}`; + +type Theme = { + fg: number; + bg: number; + fg2: number; + bg2: number; + fgH: number; + bgH: number; + dark: boolean; +}; type PinMode = | "analog" @@ -244,6 +242,11 @@ type PinMode = | "af_output" | "af_opendrain"; +interface ArrayLike { + readonly length: number; + readonly [n: number]: T; +} + type ErrorFlag = | "FIFO_FULL" | "BUFFER_FULL" @@ -276,6 +279,2513 @@ type VariableSizeInformation = { // CLASSES +/** + * A class to support some simple Queue handling for RTOS queues + * @url http://www.espruino.com/Reference#Queue + */ +declare class Queue { + /** + * Creates a Queue Object + * @constructor + * + * @param {any} queueName - Name of the queue + * @returns {any} A Queue object + * @url http://www.espruino.com/Reference#l_Queue_Queue + */ + static new(queueName: any): any; + + /** + * reads one character from queue, if available + * @url http://www.espruino.com/Reference#l_Queue_read + */ + read(): void; + + /** + * Writes one character to queue + * + * @param {any} char - char to be send + * @url http://www.espruino.com/Reference#l_Queue_writeChar + */ + writeChar(char: any): void; + + /** + * logs list of queues + * @url http://www.espruino.com/Reference#l_Queue_log + */ + log(): void; +} + +/** + * A class to support some simple Task handling for RTOS tasks + * @url http://www.espruino.com/Reference#Task + */ +declare class Task { + /** + * Creates a Task Object + * @constructor + * + * @param {any} taskName - Name of the task + * @returns {any} A Task object + * @url http://www.espruino.com/Reference#l_Task_Task + */ + static new(taskName: any): any; + + /** + * Suspend task, be careful not to suspend Espruino task itself + * @url http://www.espruino.com/Reference#l_Task_suspend + */ + suspend(): void; + + /** + * Resumes a suspended task + * @url http://www.espruino.com/Reference#l_Task_resume + */ + resume(): void; + + /** + * returns name of actual task + * @returns {any} Name of current task + * @url http://www.espruino.com/Reference#l_Task_getCurrent + */ + getCurrent(): any; + + /** + * Sends a binary notify to task + * @url http://www.espruino.com/Reference#l_Task_notify + */ + notify(): void; + + /** + * logs list of tasks + * @url http://www.espruino.com/Reference#l_Task_log + */ + log(): void; +} + +/** + * A class to handle Timer on base of ESP32 Timer + * @url http://www.espruino.com/Reference#Timer + */ +declare class Timer { + /** + * Creates a Timer Object + * @constructor + * + * @param {any} timerName - Timer Name + * @param {number} group - Timer group + * @param {number} index - Timer index + * @param {number} isrIndex - isr (0 = Espruino, 1 = test) + * @returns {any} A Timer Object + * @url http://www.espruino.com/Reference#l_Timer_Timer + */ + static new(timerName: any, group: number, index: number, isrIndex: number): any; + + /** + * Starts a timer + * + * @param {number} duration - duration of timmer in micro secs + * @url http://www.espruino.com/Reference#l_Timer_start + */ + start(duration: number): void; + + /** + * Reschedules a timer, needs to be started at least once + * + * @param {number} duration - duration of timmer in micro secs + * @url http://www.espruino.com/Reference#l_Timer_reschedule + */ + reschedule(duration: number): void; + + /** + * logs list of timers + * @url http://www.espruino.com/Reference#l_Timer_log + */ + log(): void; +} + +/** + * Class containing utility functions for the + * [ESP32](http://www.espruino.com/ESP32) + * @url http://www.espruino.com/Reference#ESP32 + */ +declare class ESP32 { + /** + * + * @param {Pin} pin - Pin for Analog read + * @param {number} atten - Attenuate factor + * @url http://www.espruino.com/Reference#l_ESP32_setAtten + */ + static setAtten(pin: Pin, atten: number): void; + + /** + * Perform a hardware reset/reboot of the ESP32. + * @url http://www.espruino.com/Reference#l_ESP32_reboot + */ + static reboot(): void; + + /** + * Put device in deepsleep state for "us" microseconds. + * + * @param {number} us - Sleeptime in us + * @url http://www.espruino.com/Reference#l_ESP32_deepSleep + */ + static deepSleep(us: number): void; + + /** + * Returns an object that contains details about the state of the ESP32 with the + * following fields: + * * `sdkVersion` - Version of the SDK. + * * `freeHeap` - Amount of free heap in bytes. + * * `BLE` - Status of BLE, enabled if true. + * * `Wifi` - Status of Wifi, enabled if true. + * * `minHeap` - Minimum heap, calculated by heap_caps_get_minimum_free_size + * @returns {any} The state of the ESP32 + * @url http://www.espruino.com/Reference#l_ESP32_getState + */ + static getState(): any; + + /** + * + * @param {number} level - which events should be shown (GAP=1, GATTS=2, GATTC=4). Use 255 for everything + * @url http://www.espruino.com/Reference#l_ESP32_setBLE_Debug + */ + static setBLE_Debug(level: number): void; + + /** + * Switches Bluetooth off/on, removes saved code from Flash, resets the board, and + * on restart creates jsVars depending on available heap (actual additional 1800) + * + * @param {boolean} enable - switches Bluetooth on or off + * @url http://www.espruino.com/Reference#l_ESP32_enableBLE + */ + static enableBLE(enable: boolean): void; + + /** + * Switches Wifi off/on, removes saved code from Flash, resets the board, and on + * restart creates jsVars depending on available heap (actual additional 3900) + * + * @param {boolean} enable - switches Wifi on or off + * @url http://www.espruino.com/Reference#l_ESP32_enableWifi + */ + static enableWifi(enable: boolean): void; + + /** + * This function is useful for ESP32 [OTA Updates](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/ota.html) + * Normally Espruino is uploaded to the `factory` partition so this isn't so useful, + * but it is possible to upload Espruino to the `ota_0` partition (or ota_1 if a different table has been added). + * If this is the case, you can use this function to mark the currently running version of Espruino as good or bad. + * * If set as valid, Espruino will continue running, and the fact that everything is ok is written to flash + * * If set as invalid (false) Espruino will mark itself as not working properly and will reboot. The ESP32 bootloader + * will then start and will load any other partition it can find that is marked as ok. + * + * @param {boolean} isValid - Set whether this app is valid or not. If `isValid==false` the device will reboot. + * @url http://www.espruino.com/Reference#l_ESP32_setOTAValid + */ + static setOTAValid(isValid: boolean): void; + + +} + +/** + * This is a built-in class to allow you to use the ESP8266 NodeMCU boards' pin + * namings to access pins. It is only available on ESP8266-based boards. + * @url http://www.espruino.com/Reference#NodeMCU + */ +declare class NodeMCU { + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_A0 + */ + static A0: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D0 + */ + static D0: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D1 + */ + static D1: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D2 + */ + static D2: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D3 + */ + static D3: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D4 + */ + static D4: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D5 + */ + static D5: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D6 + */ + static D6: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D7 + */ + static D7: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D8 + */ + static D8: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D9 + */ + static D9: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_NodeMCU_D10 + */ + static D10: Pin; + + +} + +/** + * This is the built-in class for the Arduino-style pin namings on ST Nucleo boards + * @url http://www.espruino.com/Reference#Nucleo + */ +declare class Nucleo { + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_A0 + */ + static A0: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_A1 + */ + static A1: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_A2 + */ + static A2: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_A3 + */ + static A3: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_A4 + */ + static A4: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_A5 + */ + static A5: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D0 + */ + static D0: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D1 + */ + static D1: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D2 + */ + static D2: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D3 + */ + static D3: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D4 + */ + static D4: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D5 + */ + static D5: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D6 + */ + static D6: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D7 + */ + static D7: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D8 + */ + static D8: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D9 + */ + static D9: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D10 + */ + static D10: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D11 + */ + static D11: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D12 + */ + static D12: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D13 + */ + static D13: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D14 + */ + static D14: Pin; + + /** + * @returns {Pin} A Pin + * @url http://www.espruino.com/Reference#l_Nucleo_D15 + */ + static D15: Pin; + + +} + +/** + * The NRF class is for controlling functionality of the Nordic nRF51/nRF52 chips. + * Most functionality is related to Bluetooth Low Energy, however there are also + * some functions related to NFC that apply to NRF52-based devices. + * @url http://www.espruino.com/Reference#NRF + */ +declare class NRF { + /** + * @returns {any} An object + * @url http://www.espruino.com/Reference#l_NRF_getSecurityStatus + */ + static getSecurityStatus(): any; + + /** + * @returns {any} An object + * @url http://www.espruino.com/Reference#l_NRF_getAddress + */ + static getAddress(): any; + + /** + * + * @param {any} data - The service (and characteristics) to advertise + * @param {any} options - Optional object containing options + * @url http://www.espruino.com/Reference#l_NRF_setServices + */ + static setServices(data: any, options: any): void; + + /** + * + * @param {any} data - The data to advertise as an object - see below for more info + * @param {any} [options] - [optional] An object of options + * @url http://www.espruino.com/Reference#l_NRF_setAdvertising + */ + static setAdvertising(data: any, options?: any): void; + + /** + * Called when a host device connects to Espruino. The first argument contains the + * address. + * @param {string} event - The event to listen to. + * @param {(addr: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `addr` The address of the device that has connected + * @url http://www.espruino.com/Reference#l_NRF_connect + */ + static on(event: "connect", callback: (addr: any) => void): void; + + /** + * Called when a host device disconnects from Espruino. + * The most common reason is: + * * 19 - `REMOTE_USER_TERMINATED_CONNECTION` + * * 22 - `LOCAL_HOST_TERMINATED_CONNECTION` + * @param {string} event - The event to listen to. + * @param {(reason: number) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `reason` The reason code reported back by the BLE stack - see Nordic's [`ble_hci.h` file](https://github.com/espruino/Espruino/blob/master/targetlibs/nrf5x_12/components/softdevice/s132/headers/ble_hci.h#L71) for more information + * @url http://www.espruino.com/Reference#l_NRF_disconnect + */ + static on(event: "disconnect", callback: (reason: number) => void): void; + + /** + * Contains updates on the security of the current Bluetooth link. + * See Nordic's `ble_gap_evt_auth_status_t` structure for more information. + * @param {string} event - The event to listen to. + * @param {(status: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `status` An object containing `{auth_status,bonded,lv4,kdist_own,kdist_peer} + * @url http://www.espruino.com/Reference#l_NRF_security + */ + static on(event: "security", callback: (status: any) => void): void; + + /** + * Called with a single byte value when Espruino is set up as a HID device and the + * computer it is connected to sends a HID report back to Espruino. This is usually + * used for handling indications such as the Caps Lock LED. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_NRF_HID + */ + static on(event: "HID", callback: () => void): void; + + /** + * Called with discovered services when discovery is finished + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_NRF_servicesDiscover + */ + static on(event: "servicesDiscover", callback: () => void): void; + + /** + * Called with discovered characteristics when discovery is finished + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_NRF_characteristicsDiscover + */ + static on(event: "characteristicsDiscover", callback: () => void): void; + + /** + * Called when an NFC field is detected + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_NRF_NFCon + */ + static on(event: "NFCon", callback: () => void): void; + + /** + * Called when an NFC field is no longer detected + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_NRF_NFCoff + */ + static on(event: "NFCoff", callback: () => void): void; + + /** + * When NFC is started with `NRF.nfcStart`, this is fired when NFC data is + * received. It doesn't get called if NFC is started with `NRF.nfcURL` or + * `NRF.nfcRaw` + * @param {string} event - The event to listen to. + * @param {(arr: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `arr` An ArrayBuffer containign the received data + * @url http://www.espruino.com/Reference#l_NRF_NFCrx + */ + static on(event: "NFCrx", callback: (arr: any) => void): void; + + /** + * If a device is connected to Espruino, disconnect from it. + * @url http://www.espruino.com/Reference#l_NRF_disconnect + */ + static disconnect(): void; + + /** + * Disable Bluetooth advertising and disconnect from any device that connected to + * Puck.js as a peripheral (this won't affect any devices that Puck.js initiated + * connections to). + * This makes Puck.js undiscoverable, so it can't be connected to. + * Use `NRF.wake()` to wake up and make Puck.js connectable again. + * @url http://www.espruino.com/Reference#l_NRF_sleep + */ + static sleep(): void; + + /** + * Enable Bluetooth advertising (this is enabled by default), which allows other + * devices to discover and connect to Puck.js. + * Use `NRF.sleep()` to disable advertising. + * @url http://www.espruino.com/Reference#l_NRF_wake + */ + static wake(): void; + + /** + * Restart the Bluetooth softdevice (if there is currently a BLE connection, it + * will queue a restart to be done when the connection closes). + * You shouldn't need to call this function in normal usage. However, Nordic's BLE + * softdevice has some settings that cannot be reset. For example there are only a + * certain number of unique UUIDs. Once these are all used the only option is to + * restart the softdevice to clear them all out. + * + * @param {any} [callback] - [optional] A function to be called while the softdevice is uninitialised. Use with caution - accessing console/bluetooth will almost certainly result in a crash. + * @url http://www.espruino.com/Reference#l_NRF_restart + */ + static restart(callback?: any): void; + + /** + * Get this device's default Bluetooth MAC address. + * For Puck.js, the last 5 characters of this (e.g. `ee:ff`) are used in the + * device's advertised Bluetooth name. + * @returns {any} MAC address - a string of the form 'aa:bb:cc:dd:ee:ff' + * @url http://www.espruino.com/Reference#l_NRF_getAddress + */ + static getAddress(): any; + + /** + * Set this device's default Bluetooth MAC address: + * ``` + * NRF.setAddress("ff:ee:dd:cc:bb:aa random"); + * ``` + * Addresses take the form: + * * `"ff:ee:dd:cc:bb:aa"` or `"ff:ee:dd:cc:bb:aa public"` for a public address + * * `"ff:ee:dd:cc:bb:aa random"` for a random static address (the default for + * Espruino) + * This may throw a `INVALID_BLE_ADDR` error if the upper two bits of the address + * don't match the address type. + * To change the address, Espruino must restart the softdevice. It will only do so + * when it is disconnected from other devices. + * + * @param {any} addr - The address to use (as a string) + * @url http://www.espruino.com/Reference#l_NRF_setAddress + */ + static setAddress(addr: any): void; + + /** + * Get the battery level in volts (the voltage that the NRF chip is running off + * of). + * This is the battery level of the device itself - it has nothing to with any + * device that might be connected. + * @returns {number} Battery level in volts + * @url http://www.espruino.com/Reference#l_NRF_getBattery + */ + static getBattery(): number; + + /** + * Change the data that Espruino advertises. + * Data can be of the form `{ UUID : data_as_byte_array }`. The UUID should be a + * [Bluetooth Service + * ID](https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx). + * For example to return battery level at 95%, do: + * ``` + * NRF.setAdvertising({ + * 0x180F : [95] // Service data 0x180F = 95 + * }); + * ``` + * Or you could report the current temperature: + * ``` + * setInterval(function() { + * NRF.setAdvertising({ + * 0x1809 : [Math.round(E.getTemperature())] + * }); + * }, 30000); + * ``` + * If you specify a value for the object key, Service Data is advertised. However + * if you specify `undefined`, the Service UUID is advertised: + * ``` + * NRF.setAdvertising({ + * 0x180D : undefined // Advertise service UUID 0x180D (HRM) + * }); + * ``` + * Service UUIDs can also be supplied in the second argument of `NRF.setServices`, + * but those go in the scan response packet. + * You can also supply the raw advertising data in an array. For example to + * advertise as an Eddystone beacon: + * ``` + * NRF.setAdvertising([0x03, // Length of Service List + * 0x03, // Param: Service List + * 0xAA, 0xFE, // Eddystone ID + * 0x13, // Length of Service Data + * 0x16, // Service Data + * 0xAA, 0xFE, // Eddystone ID + * 0x10, // Frame type: URL + * 0xF8, // Power + * 0x03, // https:// + * 'g','o','o','.','g','l','/','B','3','J','0','O','c'], + * {interval:100}); + * ``` + * (However for Eddystone we'd advise that you use the [Espruino Eddystone + * library](/Puck.js+Eddystone)) + * **Note:** When specifying data as an array, certain advertising options such as + * `discoverable` and `showName` won't have any effect. + * **Note:** The size of Bluetooth LE advertising packets is limited to 31 bytes. + * If you want to advertise more data, consider using an array for `data` (See + * below), or `NRF.setScanResponse`. + * You can even specify an array of arrays or objects, in which case each + * advertising packet will be used in turn - for instance to make your device + * advertise battery level and its name as well as both Eddystone and iBeacon : + * ``` + * NRF.setAdvertising([ + * {0x180F : [Puck.getBatteryPercentage()]}, // normal advertising, with battery % + * require("ble_ibeacon").get(...), // iBeacon + * require("ble_eddystone").get(...), // eddystone + * ], {interval:300}); + * ``` + * `options` is an object, which can contain: + * ``` + * { + * name: "Hello" // The name of the device + * showName: true/false // include full name, or nothing + * discoverable: true/false // general discoverable, or limited - default is limited + * connectable: true/false // whether device is connectable - default is true + * scannable : true/false // whether device can be scanned for scan response packets - default is true + * interval: 600 // Advertising interval in msec, between 20 and 10000 (default is 375ms) + * manufacturer: 0x0590 // IF sending manufacturer data, this is the manufacturer ID + * manufacturerData: [...] // IF sending manufacturer data, this is an array of data + * phy: "1mbps/2mbps/coded" // (NRF52840 only) use the long-range coded phy for transmission (1mbps default) + * } + * ``` + * Setting `connectable` and `scannable` to false gives the lowest power + * consumption as the BLE radio doesn't have to listen after sending advertising. + * **NOTE:** Non-`connectable` advertising can't have an advertising interval less + * than 100ms according to the BLE spec. + * So for instance to set the name of Puck.js without advertising any other data + * you can just use the command: + * ``` + * NRF.setAdvertising({},{name:"Hello"}); + * ``` + * You can also specify 'manufacturer data', which is another form of advertising + * data. We've registered the Manufacturer ID 0x0590 (as Pur3 Ltd) for use with + * *Official Espruino devices* - use it to advertise whatever data you'd like, but + * we'd recommend using JSON. + * For example by not advertising a device name you can send up to 24 bytes of JSON + * on Espruino's manufacturer ID: + * ``` + * var data = {a:1,b:2}; + * NRF.setAdvertising({},{ + * showName:false, + * manufacturer:0x0590, + * manufacturerData:JSON.stringify(data) + * }); + * ``` + * If you're using [EspruinoHub](https://github.com/espruino/EspruinoHub) then it + * will automatically decode this into the following MQTT topics: + * * `/ble/advertise/ma:c_:_a:dd:re:ss/espruino` -> `{"a":10,"b":15}` + * * `/ble/advertise/ma:c_:_a:dd:re:ss/a` -> `1` + * * `/ble/advertise/ma:c_:_a:dd:re:ss/b` -> `2` + * Note that **you only have 24 characters available for JSON**, so try to use the + * shortest field names possible and avoid floating point values that can be very + * long when converted to a String. + * + * @param {any} data - The service data to advertise as an object - see below for more info + * @param {any} [options] - [optional] Object of options + * @url http://www.espruino.com/Reference#l_NRF_setAdvertising + */ + static setAdvertising(data: any, options?: any): void; + + /** + * This is just like `NRF.setAdvertising`, except instead of advertising the data, + * it returns the packet that would be advertised as an array. + * + * @param {any} data - The data to advertise as an object + * @param {any} [options] - [optional] An object of options + * @returns {any} An array containing the advertising data + * @url http://www.espruino.com/Reference#l_NRF_getAdvertisingData + */ + static getAdvertisingData(data: any, options?: any): any; + + /** + * The raw scan response data should be supplied as an array. For example to return + * "Sample" for the device name: + * ``` + * NRF.setScanResponse([0x07, // Length of Data + * 0x09, // Param: Complete Local Name + * 'S', 'a', 'm', 'p', 'l', 'e']); + * ``` + * **Note:** `NRF.setServices(..., {advertise:[ ... ]})` writes advertised services + * into the scan response - so you can't use both `advertise` and `NRF.setServices` + * or one will overwrite the other. + * + * @param {any} data - The data to for the scan response + * @url http://www.espruino.com/Reference#l_NRF_setScanResponse + */ + static setScanResponse(data: any): void; + + /** + * Change the services and characteristics Espruino advertises. + * If you want to **change** the value of a characteristic, you need to use + * `NRF.updateServices()` instead + * To expose some information on Characteristic `ABCD` on service `BCDE` you could + * do: + * ``` + * NRF.setServices({ + * 0xBCDE : { + * 0xABCD : { + * value : "Hello", + * readable : true + * } + * } + * }); + * ``` + * Or to allow the 3 LEDs to be controlled by writing numbers 0 to 7 to a + * characteristic, you can do the following. `evt.data` is an ArrayBuffer. + * ``` + * NRF.setServices({ + * 0xBCDE : { + * 0xABCD : { + * writable : true, + * onWrite : function(evt) { + * digitalWrite([LED3,LED2,LED1], evt.data[0]); + * } + * } + * } + * }); + * ``` + * You can supply many different options: + * ``` + * NRF.setServices({ + * 0xBCDE : { + * 0xABCD : { + * value : "Hello", // optional + * maxLen : 5, // optional (otherwise is length of initial value) + * broadcast : false, // optional, default is false + * readable : true, // optional, default is false + * writable : true, // optional, default is false + * notify : true, // optional, default is false + * indicate : true, // optional, default is false + * description: "My Characteristic", // optional, default is null, + * security: { // optional - see NRF.setSecurity + * read: { // optional + * encrypted: false, // optional, default is false + * mitm: false, // optional, default is false + * lesc: false, // optional, default is false + * signed: false // optional, default is false + * }, + * write: { // optional + * encrypted: true, // optional, default is false + * mitm: false, // optional, default is false + * lesc: false, // optional, default is false + * signed: false // optional, default is false + * } + * }, + * onWrite : function(evt) { // optional + * console.log("Got ", evt.data); // an ArrayBuffer + * }, + * onWriteDesc : function(evt) { // optional - called when the 'cccd' descriptor is written + * // for example this is called when notifications are requested by the client: + * console.log("Notifications enabled = ", evt.data[0]&1); + * } + * } + * // more characteristics allowed + * } + * // more services allowed + * }); + * ``` + * **Note:** UUIDs can be integers between `0` and `0xFFFF`, strings of the form + * `"ABCD"`, or strings of the form `"ABCDABCD-ABCD-ABCD-ABCD-ABCDABCDABCD"` + * `options` can be of the form: + * ``` + * NRF.setServices(undefined, { + * hid : new Uint8Array(...), // optional, default is undefined. Enable BLE HID support + * uart : true, // optional, default is true. Enable BLE UART support + * advertise: [ '180D' ] // optional, list of service UUIDs to advertise + * ancs : true, // optional, Bangle.js-only, enable Apple ANCS support for notifications + * ams : true // optional, Bangle.js-only, enable Apple AMS support for media control + * }); + * ``` + * To enable BLE HID, you must set `hid` to an array which is the BLE report + * descriptor. The easiest way to do this is to use the `ble_hid_controls` or + * `ble_hid_keyboard` modules. + * **Note:** Just creating a service doesn't mean that the service will be + * advertised. It will only be available after a device connects. To advertise, + * specify the UUIDs you wish to advertise in the `advertise` field of the second + * `options` argument. For example this will create and advertise a heart rate + * service: + * ``` + * NRF.setServices({ + * 0x180D: { // heart_rate + * 0x2A37: { // heart_rate_measurement + * notify: true, + * value : [0x06, heartrate], + * } + * } + * }, { advertise: [ '180D' ] }); + * ``` + * You may specify 128 bit UUIDs to advertise, however you may get a `DATA_SIZE` + * exception because there is insufficient space in the Bluetooth LE advertising + * packet for the 128 bit UART UUID as well as the UUID you specified. In this case + * you can add `uart:false` after the `advertise` element to disable the UART, + * however you then be unable to connect to Puck.js's console via Bluetooth. + * If you absolutely require two or more 128 bit UUIDs then you will have to + * specify your own raw advertising data packets with `NRF.setAdvertising` + * **Note:** The services on Espruino can only be modified when there is no device + * connected to it as it requires a restart of the Bluetooth stack. **iOS devices + * will 'cache' the list of services** so apps like NRF Connect may incorrectly + * display the old services even after you have modified them. To fix this, disable + * and re-enable Bluetooth on your iOS device, or use an Android device to run NRF + * Connect. + * **Note:** Not all combinations of security configuration values are valid, the + * valid combinations are: encrypted, encrypted + mitm, lesc, signed, signed + + * mitm. See `NRF.setSecurity` for more information. + * + * @param {any} data - The service (and characteristics) to advertise + * @param {any} [options] - [optional] Object containing options + * @url http://www.espruino.com/Reference#l_NRF_setServices + */ + static setServices(data: { [key: number]: { [key: number]: { value?: string, maxLen?: number, broadcast?: boolean, readable?: boolean, writable?: boolean, notify?: boolean, indicate?: boolean, description?: string, security?: { read?: { encrypted?: boolean, mitm?: boolean, lesc?: boolean, signed?: boolean }, write?: { encrypted?: boolean, mitm?: boolean, lesc?: boolean, signed?: boolean } }, onWrite?: (evt: { data: ArrayBuffer }) => void } } }, options?: any): void; + + /** + * Update values for the services and characteristics Espruino advertises. Only + * services and characteristics previously declared using `NRF.setServices` are + * affected. + * To update the '0xABCD' characteristic in the '0xBCDE' service: + * ``` + * NRF.updateServices({ + * 0xBCDE : { + * 0xABCD : { + * value : "World" + * } + * } + * }); + * ``` + * You can also use 128 bit UUIDs, for example + * `"b7920001-3c1b-4b40-869f-3c0db9be80c6"`. + * To define a service and characteristic and then notify connected clients of a + * change to it when a button is pressed: + * ``` + * NRF.setServices({ + * 0xBCDE : { + * 0xABCD : { + * value : "Hello", + * maxLen : 20, + * notify: true + * } + * } + * }); + * setWatch(function() { + * NRF.updateServices({ + * 0xBCDE : { + * 0xABCD : { + * value : "World!", + * notify: true + * } + * } + * }); + * }, BTN, { repeat:true, edge:"rising", debounce: 50 }); + * ``` + * This only works if the characteristic was created with `notify: true` using + * `NRF.setServices`, otherwise the characteristic will be updated but no + * notification will be sent. + * Also note that `maxLen` was specified. If it wasn't then the maximum length of + * the characteristic would have been 5 - the length of `"Hello"`. + * To indicate (i.e. notify with ACK) connected clients of a change to the '0xABCD' + * characteristic in the '0xBCDE' service: + * ``` + * NRF.updateServices({ + * 0xBCDE : { + * 0xABCD : { + * value : "World", + * indicate: true + * } + * } + * }); + * ``` + * This only works if the characteristic was created with `indicate: true` using + * `NRF.setServices`, otherwise the characteristic will be updated but no + * notification will be sent. + * **Note:** See `NRF.setServices` for more information + * + * @param {any} data - The service (and characteristics) to update + * @url http://www.espruino.com/Reference#l_NRF_updateServices + */ + static updateServices(data: any): void; + + /** + * Start/stop listening for BLE advertising packets within range. Returns a + * `BluetoothDevice` for each advertising packet. **By default this is not an active + * scan, so Scan Response advertising data is not included (see below)** + * ``` + * // Start scanning + * packets=10; + * NRF.setScan(function(d) { + * packets--; + * if (packets<=0) + * NRF.setScan(); // stop scanning + * else + * console.log(d); // print packet info + * }); + * ``` + * Each `BluetoothDevice` will look a bit like: + * ``` + * BluetoothDevice { + * "id": "aa:bb:cc:dd:ee:ff", // address + * "rssi": -89, // signal strength + * "services": [ "128bit-uuid", ... ], // zero or more service UUIDs + * "data": new Uint8Array([ ... ]).buffer, // ArrayBuffer of returned data + * "serviceData" : { "0123" : [ 1 ] }, // if service data is in 'data', it's extracted here + * "manufacturer" : 0x1234, // if manufacturer data is in 'data', the 16 bit manufacturer ID is extracted here + * "manufacturerData" : new Uint8Array([...]).buffer, // if manufacturer data is in 'data', the data is extracted here as an ArrayBuffer + * "name": "DeviceName" // the advertised device name + * } + * ``` + * You can also supply a set of filters (as described in `NRF.requestDevice`) as a + * second argument, which will allow you to filter the devices you get a callback + * for. This helps to cut down on the time spent processing JavaScript code in + * areas with a lot of Bluetooth advertisements. For example to find only devices + * with the manufacturer data `0x0590` (Espruino's ID) you could do: + * ``` + * NRF.setScan(function(d) { + * console.log(d.manufacturerData); + * }, { filters: [{ manufacturerData:{0x0590:{}} }] }); + * ``` + * You can also specify `active:true` in the second argument to perform active + * scanning (this requests scan response packets) from any devices it finds. + * **Note:** Using a filter in `setScan` filters each advertising packet + * individually. As a result, if you filter based on a service UUID and a device + * advertises with multiple packets (or a scan response when `active:true`) only + * the packets matching the filter are returned. To aggregate multiple packets you + * can use `NRF.findDevices`. + * **Note:** BLE advertising packets can arrive quickly - faster than you'll be + * able to print them to the console. It's best only to print a few, or to use a + * function like `NRF.findDevices(..)` which will collate a list of available + * devices. + * **Note:** Using setScan turns the radio's receive mode on constantly. This can + * draw a *lot* of power (12mA or so), so you should use it sparingly or you can + * run your battery down quickly. + * + * @param {any} callback - The callback to call with received advertising packets, or undefined to stop + * @param {any} [options] - [optional] An object `{filters: ...}` (as would be passed to `NRF.requestDevice`) to filter devices by + * @url http://www.espruino.com/Reference#l_NRF_setScan + */ + static setScan(callback: any, options?: any): void; + + /** + * This function can be used to quickly filter through Bluetooth devices. + * For instance if you wish to scan for multiple different types of device at the + * same time then you could use `NRF.findDevices` with all the filters you're + * interested in. When scanning is finished you can then use `NRF.filterDevices` to + * pick out just the devices of interest. + * ``` + * // the two types of device we're interested in + * var filter1 = [{serviceData:{"fe95":{}}}]; + * var filter2 = [{namePrefix:"Pixl.js"}]; + * // the following filter will return both types of device + * var allFilters = filter1.concat(filter2); + * // now scan for both types of device, and filter them out afterwards + * NRF.findDevices(function(devices) { + * var devices1 = NRF.filterDevices(devices, filter1); + * var devices2 = NRF.filterDevices(devices, filter2); + * // ... + * }, {filters : allFilters}); + * ``` + * + * @param {any} devices - An array of `BluetoothDevice` objects, from `NRF.findDevices` or similar + * @param {any} filters - A list of filters (as would be passed to `NRF.requestDevice`) to filter devices by + * @returns {any} An array of `BluetoothDevice` objects that match the given filters + * @url http://www.espruino.com/Reference#l_NRF_filterDevices + */ + static filterDevices(devices: any, filters: any): any; + + /** + * Utility function to return a list of BLE devices detected in range. Behind the + * scenes, this uses `NRF.setScan(...)` and collates the results. + * ``` + * NRF.findDevices(function(devices) { + * console.log(devices); + * }, 1000); + * ``` + * prints something like: + * ``` + * [ + * BluetoothDevice { + * "id" : "e7:e0:57:ad:36:a2 random", + * "rssi": -45, + * "services": [ "4567" ], + * "serviceData" : { "0123" : [ 1 ] }, + * "manufacturer" : 1424, + * "manufacturerData" : new Uint8Array([ ... ]).buffer, + * "data": new ArrayBuffer([ ... ]).buffer, + * "name": "Puck.js 36a2" + * }, + * BluetoothDevice { + * "id": "c0:52:3f:50:42:c9 random", + * "rssi": -65, + * "data": new ArrayBuffer([ ... ]), + * "name": "Puck.js 8f57" + * } + * ] + * ``` + * For more information on the structure returned, see `NRF.setScan`. + * If you want to scan only for specific devices you can replace the timeout with + * an object of the form `{filters: ..., timeout : ..., active: bool}` using the + * filters described in `NRF.requestDevice`. For example to search for devices with + * Espruino's `manufacturerData`: + * ``` + * NRF.findDevices(function(devices) { + * ... + * }, {timeout : 2000, filters : [{ manufacturerData:{0x0590:{}} }] }); + * ``` + * You could then use + * [`BluetoothDevice.gatt.connect(...)`](/Reference#l_BluetoothRemoteGATTServer_connect) + * on the device returned to make a connection. + * You can also use [`NRF.connect(...)`](/Reference#l_NRF_connect) on just the `id` + * string returned, which may be useful if you always want to connect to a specific + * device. + * **Note:** Using findDevices turns the radio's receive mode on for 2000ms (or + * however long you specify). This can draw a *lot* of power (12mA or so), so you + * should use it sparingly or you can run your battery down quickly. + * **Note:** The 'data' field contains the data of *the last packet received*. + * There may have been more packets. To get data for each packet individually use + * `NRF.setScan` instead. + * + * @param {any} callback - The callback to call with received advertising packets (as `BluetoothDevice`), or undefined to stop + * @param {any} [options] - [optional] A time in milliseconds to scan for (defaults to 2000), Or an optional object `{filters: ..., timeout : ..., active: bool}` (as would be passed to `NRF.requestDevice`) to filter devices by + * @url http://www.espruino.com/Reference#l_NRF_findDevices + */ + static findDevices(callback: (devices: BluetoothDevice[]) => void, options?: number | { filters?: NRFFilters[], timeout?: number, active?: boolean }): void; + + /** + * Start/stop listening for RSSI values on the currently active connection (where + * This device is a peripheral and is being connected to by a 'central' device) + * ``` + * // Start scanning + * NRF.setRSSIHandler(function(rssi) { + * console.log(rssi); // prints -85 (or similar) + * }); + * // Stop Scanning + * NRF.setRSSIHandler(); + * ``` + * RSSI is the 'Received Signal Strength Indication' in dBm + * + * @param {any} callback - The callback to call with the RSSI value, or undefined to stop + * @url http://www.espruino.com/Reference#l_NRF_setRSSIHandler + */ + static setRSSIHandler(callback: any): void; + + /** + * Set the BLE radio transmit power. The default TX power is 0 dBm, and + * + * @param {number} power - Transmit power. Accepted values are -40(nRF52 only), -30(nRF51 only), -20, -16, -12, -8, -4, 0, and 4 dBm. On nRF52840 (eg Bangle.js 2) 5/6/7/8 dBm are available too. Others will give an error code. + * @url http://www.espruino.com/Reference#l_NRF_setTxPower + */ + static setTxPower(power: number): void; + + /** + * **THIS IS DEPRECATED** - please use `NRF.setConnectionInterval` for peripheral + * and `NRF.connect(addr, options)`/`BluetoothRemoteGATTServer.connect(options)` + * for central connections. + * This sets the connection parameters - these affect the transfer speed and power + * usage when the device is connected. + * * When not low power, the connection interval is between 7.5 and 20ms + * * When low power, the connection interval is between 500 and 1000ms + * When low power connection is enabled, transfers of data over Bluetooth will be + * very slow, however power usage while connected will be drastically decreased. + * This will only take effect after the connection is disconnected and + * re-established. + * + * @param {boolean} lowPower - Whether the connection is low power or not + * @url http://www.espruino.com/Reference#l_NRF_setLowPowerConnection + */ + static setLowPowerConnection(lowPower: boolean): void; + + /** + * Enables NFC and starts advertising the given URL. For example: + * ``` + * NRF.nfcURL("http://espruino.com"); + * ``` + * + * @param {any} url - The URL string to expose on NFC, or `undefined` to disable NFC + * @url http://www.espruino.com/Reference#l_NRF_nfcURL + */ + static nfcURL(url: any): void; + + /** + * Enables NFC and with an out of band 16 byte pairing key. + * For example the following will enable out of band pairing on BLE such that the + * device will pair when you tap the phone against it: + * ``` + * var bleKey = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00]; + * NRF.on('security',s=>print("security",JSON.stringify(s))); + * NRF.nfcPair(bleKey); + * NRF.setSecurity({oob:bleKey, mitm:true}); + * ``` + * + * @param {any} key - 16 byte out of band key + * @url http://www.espruino.com/Reference#l_NRF_nfcPair + */ + static nfcPair(key: any): void; + + /** + * Enables NFC with a record that will launch the given android app. + * For example: + * ``` + * NRF.nfcAndroidApp("no.nordicsemi.android.nrftoolbox") + * ``` + * + * @param {any} app - The unique identifier of the given Android App + * @url http://www.espruino.com/Reference#l_NRF_nfcAndroidApp + */ + static nfcAndroidApp(app: any): void; + + /** + * Enables NFC and starts advertising with Raw data. For example: + * ``` + * NRF.nfcRaw(new Uint8Array([193, 1, 0, 0, 0, 13, 85, 3, 101, 115, 112, 114, 117, 105, 110, 111, 46, 99, 111, 109])); + * // same as NRF.nfcURL("http://espruino.com"); + * ``` + * + * @param {any} payload - The NFC NDEF message to deliver to the reader + * @url http://www.espruino.com/Reference#l_NRF_nfcRaw + */ + static nfcRaw(payload: any): void; + + /** + * **Advanced NFC Functionality.** If you just want to advertise a URL, use + * `NRF.nfcURL` instead. + * Enables NFC and starts advertising. `NFCrx` events will be fired when data is + * received. + * ``` + * NRF.nfcStart(); + * ``` + * + * @param {any} payload - Optional 7 byte UID + * @returns {any} Internal tag memory (first 10 bytes of tag data) + * @url http://www.espruino.com/Reference#l_NRF_nfcStart + */ + static nfcStart(payload: any): any; + + /** + * **Advanced NFC Functionality.** If you just want to advertise a URL, use + * `NRF.nfcURL` instead. + * Disables NFC. + * ``` + * NRF.nfcStop(); + * ``` + * + * @url http://www.espruino.com/Reference#l_NRF_nfcStop + */ + static nfcStop(): void; + + /** + * **Advanced NFC Functionality.** If you just want to advertise a URL, use + * `NRF.nfcURL` instead. + * Acknowledges the last frame and optionally transmits a response. If payload is + * an array, then a array.length byte nfc frame is sent. If payload is a int, then + * a 4bit ACK/NACK is sent. **Note:** ```nfcSend``` should always be called after + * an ```NFCrx``` event. + * ``` + * NRF.nfcSend(new Uint8Array([0x01, 0x02, ...])); + * // or + * NRF.nfcSend(0x0A); + * // or + * NRF.nfcSend(); + * ``` + * + * @param {any} payload - Optional tx data + * @url http://www.espruino.com/Reference#l_NRF_nfcSend + */ + static nfcSend(payload: any): void; + + /** + * Send a USB HID report. HID must first be enabled with `NRF.setServices({}, {hid: + * hid_report})` + * + * @param {any} data - Input report data as an array + * @param {any} callback - A callback function to be called when the data is sent + * @url http://www.espruino.com/Reference#l_NRF_sendHIDReport + */ + static sendHIDReport(data: any, callback: any): void; + + /** + * Check if Apple Notification Center Service (ANCS) is currently active on the BLE + * connection + * + * @returns {boolean} True if Apple Notification Center Service (ANCS) has been initialised and is active + * @url http://www.espruino.com/Reference#l_NRF_ancsIsActive + */ + static ancsIsActive(): boolean; + + /** + * Send an ANCS action for a specific Notification UID. Corresponds to + * posaction/negaction in the 'ANCS' event that was received + * + * @param {number} uid - The UID of the notification to respond to + * @param {boolean} positive - `true` for positive action, `false` for negative + * @url http://www.espruino.com/Reference#l_NRF_ancsAction + */ + static ancsAction(uid: number, positive: boolean): void; + + /** + * Get ANCS info for a notification event received via `E.ANCS`, e.g.: + * ``` + * E.on('ANCS', event => { + * NRF.ancsGetNotificationInfo( event.uid ).then(a=>print("Notify",E.toJS(a))); + * }); + * ``` + * Returns: + * ``` + * { + * "uid" : integer, + * "appId": string, + * "title": string, + * "subtitle": string, + * "message": string, + * "messageSize": string, + * "date": string, + * "posAction": string, + * "negAction": string + * } + * ``` + * + * @param {number} uid - The UID of the notification to get information for + * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete + * @url http://www.espruino.com/Reference#l_NRF_ancsGetNotificationInfo + */ + static ancsGetNotificationInfo(uid: number): Promise; + + /** + * Get ANCS info for an app (app id is available via `NRF.ancsGetNotificationInfo`) + * Promise returns: + * ``` + * { + * "uid" : int, + * "appId" : string, + * "title" : string, + * "subtitle" : string, + * "message" : string, + * "messageSize" : string, + * "date" : string, + * "posAction" : string, + * "negAction" : string, + * "name" : string, + * } + * ``` + * + * @param {any} id - The app ID to get information for + * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete + * @url http://www.espruino.com/Reference#l_NRF_ancsGetAppInfo + */ + static ancsGetAppInfo(id: any): Promise; + + /** + * Check if Apple Media Service (AMS) is currently active on the BLE connection + * + * @returns {boolean} True if Apple Media Service (AMS) has been initialised and is active + * @url http://www.espruino.com/Reference#l_NRF_amsIsActive + */ + static amsIsActive(): boolean; + + /** + * Get Apple Media Service (AMS) info for the current media player. "playbackinfo" + * returns a concatenation of three comma-separated values: + * - PlaybackState: a string that represents the integer value of the playback + * state: + * - PlaybackStatePaused = 0 + * - PlaybackStatePlaying = 1 + * - PlaybackStateRewinding = 2 + * - PlaybackStateFastForwarding = 3 + * - PlaybackRate: a string that represents the floating point value of the + * playback rate. + * - ElapsedTime: a string that represents the floating point value of the elapsed + * time of the current track, in seconds + * + * @param {any} id - Either 'name', 'playbackinfo' or 'volume' + * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete + * @url http://www.espruino.com/Reference#l_NRF_amsGetPlayerInfo + */ + static amsGetPlayerInfo(id: any): Promise; + + /** + * Get Apple Media Service (AMS) info for the currently-playing track + * + * @param {any} id - Either 'artist', 'album', 'title' or 'duration' + * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete + * @url http://www.espruino.com/Reference#l_NRF_amsGetTrackInfo + */ + static amsGetTrackInfo(id: any): Promise; + + /** + * Send an AMS command to an Apple Media Service device to control music playback + * Command is one of play, pause, playpause, next, prev, volup, voldown, repeat, + * shuffle, skipforward, skipback, like, dislike, bookmark + * + * @param {any} id - For example, 'play', 'pause', 'volup' or 'voldown' + * @url http://www.espruino.com/Reference#l_NRF_amsCommand + */ + static amsCommand(id: any): void; + + /** + * Search for available devices matching the given filters. Since we have no UI + * here, Espruino will pick the FIRST device it finds, or it'll call `catch`. + * `options` can have the following fields: + * * `filters` - a list of filters that a device must match before it is returned + * (see below) + * * `timeout` - the maximum time to scan for in milliseconds (scanning stops when + * a match is found. e.g. `NRF.requestDevice({ timeout:2000, filters: [ ... ] })` + * * `active` - whether to perform active scanning (requesting 'scan response' + * packets from any devices that are found). e.g. `NRF.requestDevice({ active:true, + * filters: [ ... ] })` + * * `phy` - (NRF52840 only) use the long-range coded phy (`"1mbps"` default, can + * be `"1mbps/2mbps/both/coded"`) + * * `extended` - (NRF52840 only) support receiving extended-length advertising + * packets (default=true if phy isn't `"1mbps"`) + * **NOTE:** `timeout` and `active` are not part of the Web Bluetooth standard. + * The following filter types are implemented: + * * `services` - list of services as strings (all of which must match). 128 bit + * services must be in the form '01230123-0123-0123-0123-012301230123' + * * `name` - exact device name + * * `namePrefix` - starting characters of device name + * * `id` - exact device address (`id:"e9:53:86:09:89:99 random"`) (this is + * Espruino-specific, and is not part of the Web Bluetooth spec) + * * `serviceData` - an object containing service characteristics which must all + * match (`serviceData:{"1809":{}}`). Matching of actual service data is not + * supported yet. + * * `manufacturerData` - an object containing manufacturer UUIDs which must all + * match (`manufacturerData:{0x0590:{}}`). Matching of actual manufacturer data + * is not supported yet. + * ``` + * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) { ... }); + * // or + * NRF.requestDevice({ filters: [{ services: ['1823'] }] }).then(function(device) { ... }); + * // or + * NRF.requestDevice({ filters: [{ manufacturerData:{0x0590:{}} }] }).then(function(device) { ... }); + * ``` + * As a full example, to send data to another Puck.js to turn an LED on: + * ``` + * var gatt; + * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) { + * return device.gatt.connect(); + * }).then(function(g) { + * gatt = g; + * return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); + * }).then(function(service) { + * return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); + * }).then(function(characteristic) { + * return characteristic.writeValue("LED1.set()\n"); + * }).then(function() { + * gatt.disconnect(); + * console.log("Done!"); + * }); + * ``` + * Or slightly more concisely, using ES6 arrow functions: + * ``` + * var gatt; + * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }]}).then( + * device => device.gatt.connect()).then( + * g => (gatt=g).getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e")).then( + * service => service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e")).then( + * characteristic => characteristic.writeValue("LED1.reset()\n")).then( + * () => { gatt.disconnect(); console.log("Done!"); } ); + * ``` + * Note that you have to keep track of the `gatt` variable so that you can + * disconnect the Bluetooth connection when you're done. + * **Note:** Using a filter in `NRF.requestDevice` filters each advertising packet + * individually. As soon as a matching advertisement is received, + * `NRF.requestDevice` resolves the promise and stops scanning. This means that if + * you filter based on a service UUID and a device advertises with multiple packets + * (or a scan response when `active:true`) only the packet matching the filter is + * returned - you may not get the device's name is that was in a separate packet. + * To aggregate multiple packets you can use `NRF.findDevices`. + * + * @param {any} options - Options used to filter the device to use + * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete + * @url http://www.espruino.com/Reference#l_NRF_requestDevice + */ + static requestDevice(options?: { filters?: NRFFilters[], timeout?: number, active?: boolean, phy?: string, extended?: boolean }): Promise; + + /** + * Connect to a BLE device by MAC address. Returns a promise, the argument of which + * is the `BluetoothRemoteGATTServer` connection. + * ``` + * NRF.connect("aa:bb:cc:dd:ee").then(function(server) { + * // ... + * }); + * ``` + * This has the same effect as calling `BluetoothDevice.gatt.connect` on a + * `BluetoothDevice` requested using `NRF.requestDevice`. It just allows you to + * specify the address directly (without having to scan). + * You can use it as follows - this would connect to another Puck device and turn + * its LED on: + * ``` + * var gatt; + * NRF.connect("aa:bb:cc:dd:ee random").then(function(g) { + * gatt = g; + * return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); + * }).then(function(service) { + * return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); + * }).then(function(characteristic) { + * return characteristic.writeValue("LED1.set()\n"); + * }).then(function() { + * gatt.disconnect(); + * console.log("Done!"); + * }); + * ``` + * **Note:** Espruino Bluetooth devices use a type of BLE address known as 'random + * static', which is different to a 'public' address. To connect to an Espruino + * device you'll need to use an address string of the form `"aa:bb:cc:dd:ee + * random"` rather than just `"aa:bb:cc:dd:ee"`. If you scan for devices with + * `NRF.findDevices`/`NRF.setScan` then addresses are already reported in the + * correct format. + * + * @param {any} mac - The MAC address to connect to + * @param {any} options - (Espruino-specific) An object of connection options (see `BluetoothRemoteGATTServer.connect` for full details) + * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete + * @url http://www.espruino.com/Reference#l_NRF_connect + */ + static connect(mac: any, options: any): Promise; + + /** + * If set to true, whenever a device bonds it will be added to the whitelist. + * When set to false, the whitelist is cleared and newly bonded devices will not be + * added to the whitelist. + * **Note:** This is remembered between `reset()`s but isn't remembered after + * power-on (you'll have to add it to `onInit()`. + * + * @param {boolean} whitelisting - Are we using a whitelist? (default false) + * @url http://www.espruino.com/Reference#l_NRF_setWhitelist + */ + static setWhitelist(whitelisting: boolean): void; + + /** + * When connected, Bluetooth LE devices communicate at a set interval. Lowering the + * interval (e.g. more packets/second) means a lower delay when sending data, higher + * bandwidth, but also more power consumption. + * By default, when connected as a peripheral Espruino automatically adjusts the + * connection interval. When connected it's as fast as possible (7.5ms) but when + * idle for over a minute it drops to 200ms. On continued activity (>1 BLE + * operation) the interval is raised to 7.5ms again. + * The options for `interval` are: + * * `undefined` / `"auto"` : (default) automatically adjust connection interval + * * `100` : set min and max connection interval to the same number (between 7.5ms + * and 4000ms) + * * `{minInterval:20, maxInterval:100}` : set min and max connection interval as a + * range + * This configuration is not remembered during a `save()` - you will have to re-set + * it via `onInit`. + * **Note:** If connecting to another device (as Central), you can use an extra + * argument to `NRF.connect` or `BluetoothRemoteGATTServer.connect` to specify a + * connection interval. + * **Note:** This overwrites any changes imposed by the deprecated + * `NRF.setLowPowerConnection` + * + * @param {any} interval - The connection interval to use (see below) + * @url http://www.espruino.com/Reference#l_NRF_setConnectionInterval + */ + static setConnectionInterval(interval: any): void; + + /** + * Sets the security options used when connecting/pairing. This applies to both + * central *and* peripheral mode. + * ``` + * NRF.setSecurity({ + * display : bool // default false, can this device display a passkey + * // - sent via the `BluetoothDevice.passkey` event + * keyboard : bool // default false, can this device enter a passkey + * // - request sent via the `BluetoothDevice.passkeyRequest` event + * bond : bool // default true, Perform bonding + * mitm : bool // default false, Man In The Middle protection + * lesc : bool // default false, LE Secure Connections + * passkey : // default "", or a 6 digit passkey to use + * oob : [0..15] // if specified, Out Of Band pairing is enabled and + * // the 16 byte pairing code supplied here is used + * encryptUart : bool // default false (unless oob or passkey specified) + * // This sets the BLE UART service such that it + * // is encrypted and can only be used from a bonded connection + * }); + * ``` + * **NOTE:** Some combinations of arguments will cause an error. For example + * supplying a passkey without `display:1` is not allowed. If `display:1` is set + * you do not require a physical display, the user just needs to know the passkey + * you supplied. + * For instance, to require pairing and to specify a passkey, use: + * ``` + * NRF.setSecurity({passkey:"123456", mitm:1, display:1}); + * ``` + * However, while most devices will request a passkey for pairing at this point it + * is still possible for a device to connect without requiring one (e.g. using the + * 'NRF Connect' app). + * To force a passkey you need to protect each characteristic you define with + * `NRF.setSecurity`. For instance the following code will *require* that the + * passkey `123456` is entered before the characteristic + * `9d020002-bf5f-1d1a-b52a-fe52091d5b12` can be read. + * ``` + * NRF.setSecurity({passkey:"123456", mitm:1, display:1}); + * NRF.setServices({ + * "9d020001-bf5f-1d1a-b52a-fe52091d5b12" : { + * "9d020002-bf5f-1d1a-b52a-fe52091d5b12" : { + * // readable always + * value : "Not Secret" + * }, + * "9d020003-bf5f-1d1a-b52a-fe52091d5b12" : { + * // readable only once bonded + * value : "Secret", + * readable : true, + * security: { + * read: { + * mitm: true, + * encrypted: true + * } + * } + * }, + * "9d020004-bf5f-1d1a-b52a-fe52091d5b12" : { + * // readable always + * // writable only once bonded + * value : "Readable", + * readable : true, + * writable : true, + * onWrite : function(evt) { + * console.log("Wrote ", evt.data); + * }, + * security: { + * write: { + * mitm: true, + * encrypted: true + * } + * } + * } + * } + * }); + * ``` + * **Note:** If `passkey` or `oob` is specified, the Nordic UART service (if + * enabled) will automatically be set to require encryption, but otherwise it is + * open. + * + * @param {any} options - An object containing security-related options (see below) + * @url http://www.espruino.com/Reference#l_NRF_setSecurity + */ + static setSecurity(options: any): void; + + /** + * Return an object with information about the security state of the current + * peripheral connection: + * ``` + * { + * connected // The connection is active (not disconnected). + * encrypted // Communication on this link is encrypted. + * mitm_protected // The encrypted communication is also protected against man-in-the-middle attacks. + * bonded // The peer is bonded with us + * connected_addr // If connected=true, the MAC address of the currently connected device + * } + * ``` + * If there is no active connection, `{connected:false}` will be returned. + * See `NRF.setSecurity` for information about negotiating a secure connection. + * @returns {any} An object + * @url http://www.espruino.com/Reference#l_NRF_getSecurityStatus + */ + static getSecurityStatus(): any; + + /** + * + * @param {boolean} forceRepair - True if we should force repairing even if there is already valid pairing info + * @returns {any} A promise + * @url http://www.espruino.com/Reference#l_NRF_startBonding + */ + static startBonding(forceRepair: boolean): any; + + +} + +/** + * This class provides functionality to recognise gestures drawn on a touchscreen. + * It is only built into Bangle.js 2. + * Usage: + * ``` + * var strokes = { + * stroke1 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])), + * stroke2 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])), + * stroke3 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])) + * }; + * var r = Unistroke.recognise(strokes,new Uint8Array([x1, y1, x2, y2, x3, y3, ...])) + * print(r); // stroke1/stroke2/stroke3 + * ``` + * @url http://www.espruino.com/Reference#Unistroke + */ +declare class Unistroke { + /** + * Create a new Unistroke based on XY coordinates + * + * @param {any} xy - An array of interleaved XY coordinates + * @returns {any} A string of data representing this unistroke + * @url http://www.espruino.com/Reference#l_Unistroke_new + */ + static new(xy: any): any; + + /** + * Recognise based on an object of named strokes, and a list of XY coordinates + * + * @param {any} strokes - An object of named strokes : `{arrow:..., circle:...}` + * @param {any} xy - An array of interleaved XY coordinates + * @returns {any} The key name of the matched stroke + * @url http://www.espruino.com/Reference#l_Unistroke_recognise + */ + static recognise(strokes: any, xy: any): any; + + +} + +/** + * Class containing AES encryption/decryption + * **Note:** This library is currently only included in builds for boards where + * there is space. For other boards there is `crypto.js` which implements SHA1 in + * JS. + * @url http://www.espruino.com/Reference#AES + */ +declare class AES { + /** + * + * @param {any} passphrase - Message to encrypt + * @param {any} key - Key to encrypt message - must be an ArrayBuffer of 128, 192, or 256 BITS + * @param {any} [options] - [optional] An object, may specify `{ iv : new Uint8Array(16), mode : 'CBC|CFB|CTR|OFB|ECB' }` + * @returns {any} Returns an ArrayBuffer + * @url http://www.espruino.com/Reference#l_AES_encrypt + */ + static encrypt(passphrase: any, key: any, options?: any): ArrayBuffer; + + /** + * + * @param {any} passphrase - Message to decrypt + * @param {any} key - Key to encrypt message - must be an ArrayBuffer of 128, 192, or 256 BITS + * @param {any} [options] - [optional] An object, may specify `{ iv : new Uint8Array(16), mode : 'CBC|CFB|CTR|OFB|ECB' }` + * @returns {any} Returns an ArrayBuffer + * @url http://www.espruino.com/Reference#l_AES_decrypt + */ + static decrypt(passphrase: any, key: any, options?: any): ArrayBuffer; + + +} + +/** + * Class containing utility functions for + * [Pixl.js](http://www.espruino.com/Pixl.js) + * @url http://www.espruino.com/Reference#Pixl + */ +declare class Pixl { + /** + * DEPRECATED - Please use `E.getBattery()` instead. + * Return an approximate battery percentage remaining based on a normal CR2032 + * battery (2.8 - 2.2v) + * @returns {number} A percentage between 0 and 100 + * @url http://www.espruino.com/Reference#l_Pixl_getBatteryPercentage + */ + static getBatteryPercentage(): number; + + /** + * Set the LCD's contrast + * + * @param {number} c - Contrast between 0 and 1 + * @url http://www.espruino.com/Reference#l_Pixl_setContrast + */ + static setContrast(c: number): void; + + /** + * This function can be used to turn Pixl.js's LCD off or on. + * * With the LCD off, Pixl.js draws around 0.1mA + * * With the LCD on, Pixl.js draws around 0.25mA + * + * @param {boolean} isOn - True if the LCD should be on, false if not + * @url http://www.espruino.com/Reference#l_Pixl_setLCDPower + */ + static setLCDPower(isOn: boolean): void; + + /** + * Writes a command directly to the ST7567 LCD controller + * + * @param {number} c + * @url http://www.espruino.com/Reference#l_Pixl_lcdw + */ + static lcdw(c: number): void; + + /** + * Display a menu on Pixl.js's screen, and set up the buttons to navigate through + * it. + * DEPRECATED: Use `E.showMenu` + * + * @param {any} menu - An object containing name->function mappings to to be used in a menu + * @returns {any} A menu object with `draw`, `move` and `select` functions + * @url http://www.espruino.com/Reference#l_Pixl_menu + */ + static menu(menu: Menu): MenuInstance; + + +} + +/** + * This class exists in order to interface Espruino with fast-moving trigger + * wheels. Trigger wheels are physical discs with evenly spaced teeth cut into + * them, and often with one or two teeth next to each other missing. A sensor sends + * a signal whenever a tooth passed by, and this allows a device to measure not + * only RPM, but absolute position. + * This class is currently in testing - it is NOT AVAILABLE on normal boards. + * @url http://www.espruino.com/Reference#Trig + */ +declare class Trig { + /** + * Get the position of the trigger wheel at the given time (from getTime) + * + * @param {number} time - The time at which to find the position + * @returns {number} The position of the trigger wheel in degrees - as a floating point number + * @url http://www.espruino.com/Reference#l_Trig_getPosAtTime + */ + static getPosAtTime(time: number): number; + + /** + * Initialise the trigger class + * + * @param {Pin} pin - The pin to use for triggering + * @param {any} options - Additional options as an object. defaults are: ```{teethTotal:60,teethMissing:2,minRPM:30,keyPosition:0}``` + * @url http://www.espruino.com/Reference#l_Trig_setup + */ + static setup(pin: Pin, options: any): void; + + /** + * Set a trigger for a certain point in the cycle + * + * @param {number} num - The trigger number (0..7) + * @param {number} pos - The position (in degrees) to fire the trigger at + * @param {any} pins - An array of pins to pulse (max 4) + * @param {number} pulseLength - The time (in msec) to pulse for + * @url http://www.espruino.com/Reference#l_Trig_setTrigger + */ + static setTrigger(num: number, pos: number, pins: any, pulseLength: number): void; + + /** + * Disable a trigger + * + * @param {number} num - The trigger number (0..7) + * @url http://www.espruino.com/Reference#l_Trig_killTrigger + */ + static killTrigger(num: number): void; + + /** + * Get the current state of a trigger + * + * @param {number} num - The trigger number (0..7) + * @returns {any} A structure containing all information about the trigger + * @url http://www.espruino.com/Reference#l_Trig_getTrigger + */ + static getTrigger(num: number): any; + + /** + * Get the RPM of the trigger wheel + * @returns {number} The current RPM of the trigger wheel + * @url http://www.espruino.com/Reference#l_Trig_getRPM + */ + static getRPM(): number; + + /** + * Get the current error flags from the trigger wheel - and zero them + * @returns {number} The error flags + * @url http://www.espruino.com/Reference#l_Trig_getErrors + */ + static getErrors(): number; + + /** + * Get the current error flags from the trigger wheel - and zero them + * @returns {any} An array of error strings + * @url http://www.espruino.com/Reference#l_Trig_getErrorArray + */ + static getErrorArray(): any; + + +} + +/** + * This class helps to convert URLs into Objects of information ready for + * http.request/get + * @url http://www.espruino.com/Reference#url + */ +declare class url { + /** + * A utility function to split a URL into parts + * This is useful in web servers for instance when handling a request. + * For instance `url.parse("/a?b=c&d=e",true)` returns + * `{"method":"GET","host":"","path":"/a?b=c&d=e","pathname":"/a","search":"?b=c&d=e","port":80,"query":{"b":"c","d":"e"}}` + * + * @param {any} urlStr - A URL to be parsed + * @param {boolean} parseQuery - Whether to parse the query string into an object not (default = false) + * @returns {any} An object containing options for ```http.request``` or ```http.get```. Contains `method`, `host`, `path`, `pathname`, `search`, `port` and `query` + * @url http://www.espruino.com/Reference#l_url_parse + */ + static parse(urlStr: any, parseQuery: boolean): any; + + +} + +/** + * The socket server created by `require('net').createServer` + * @url http://www.espruino.com/Reference#Server + */ +declare class Server { + + + /** + * Start listening for new connections on the given port + * + * @param {number} port - The port to listen on + * @returns {any} The HTTP server instance that 'listen' was called on + * @url http://www.espruino.com/Reference#l_Server_listen + */ + listen(port: number): any; + + /** + * Stop listening for new connections + * @url http://www.espruino.com/Reference#l_Server_close + */ + close(): void; +} + +/** + * An actual socket connection - allowing transmit/receive of TCP data + * @url http://www.espruino.com/Reference#Socket + */ +declare class Socket { + /** + * The 'data' event is called when data is received. If a handler is defined with + * `X.on('data', function(data) { ... })` then it will be called, otherwise data + * will be stored in an internal buffer, where it can be retrieved with `X.read()` + * @param {string} event - The event to listen to. + * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `data` A string containing one or more characters of received data + * @url http://www.espruino.com/Reference#l_Socket_data + */ + static on(event: "data", callback: (data: any) => void): void; + + /** + * Called when the connection closes. + * @param {string} event - The event to listen to. + * @param {(had_error: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `had_error` A boolean indicating whether the connection had an error (use an error event handler to get error details). + * @url http://www.espruino.com/Reference#l_Socket_close + */ + static on(event: "close", callback: (had_error: any) => void): void; + + /** + * There was an error on this socket and it is closing (or wasn't opened in the + * first place). If a "connected" event was issued on this socket then the error + * event is always followed by a close event. The error codes are: + * * -1: socket closed (this is not really an error and will not cause an error + * callback) + * * -2: out of memory (typically while allocating a buffer to hold data) + * * -3: timeout + * * -4: no route + * * -5: busy + * * -6: not found (DNS resolution) + * * -7: max sockets (... exceeded) + * * -8: unsent data (some data could not be sent) + * * -9: connection reset (or refused) + * * -10: unknown error + * * -11: no connection + * * -12: bad argument + * * -13: SSL handshake failed + * * -14: invalid SSL data + * @param {string} event - The event to listen to. + * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `details` An error object with an error code (a negative integer) and a message. + * @url http://www.espruino.com/Reference#l_Socket_error + */ + static on(event: "error", callback: (details: any) => void): void; + + /** + * An event that is fired when the buffer is empty and it can accept more data to + * send. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_Socket_drain + */ + static on(event: "drain", callback: () => void): void; + + /** + * Return how many bytes are available to read. If there is already a listener for + * data, this will always return 0. + * @returns {number} How many bytes are available + * @url http://www.espruino.com/Reference#l_Socket_available + */ + available(): number; + + /** + * Return a string containing characters that have been received + * + * @param {number} chars - The number of characters to read, or undefined/0 for all available + * @returns {any} A string containing the required bytes. + * @url http://www.espruino.com/Reference#l_Socket_read + */ + read(chars: number): any; + + /** + * Pipe this to a stream (an object with a 'write' method) + * + * @param {any} destination - The destination file/stream that will receive content from the source. + * @param {any} [options] + * [optional] An object `{ chunkSize : int=32, end : bool=true, complete : function }` + * chunkSize : The amount of data to pipe from source to destination at a time + * complete : a function to call when the pipe activity is complete + * end : call the 'end' function on the destination when the source is finished + * @url http://www.espruino.com/Reference#l_Socket_pipe + */ + pipe(destination: any, options?: any): void; + + /** + * This function writes the `data` argument as a string. Data that is passed in + * (including arrays) will be converted to a string with the normal JavaScript + * `toString` method. + * If you wish to send binary data then you need to convert that data directly to a + * String. This can be done with `String.fromCharCode`, however it's often easier + * and faster to use the Espruino-specific `E.toString`, which will read its + * arguments as an array of bytes and convert that to a String: + * ``` + * socket.write(E.toString([0,1,2,3,4,5])); + * ``` + * If you need to send something other than bytes, you can use 'Typed Arrays', or + * even `DataView`: + * ``` + * var d = new DataView(new ArrayBuffer(8)); // 8 byte array buffer + * d.setFloat32(0, 765.3532564); // write float at bytes 0-3 + * d.setInt8(4, 42); // write int8 at byte 4 + * socket.write(E.toString(d.buffer)) + * ``` + * + * @param {any} data - A string containing data to send + * @returns {boolean} For node.js compatibility, returns the boolean false. When the send buffer is empty, a `drain` event will be sent + * @url http://www.espruino.com/Reference#l_Socket_write + */ + write(data: any): boolean; + + /** + * Close this socket - optional data to append as an argument. + * See `Socket.write` for more information about the data argument + * + * @param {any} data - A string containing data to send + * @url http://www.espruino.com/Reference#l_Socket_end + */ + end(data: any): void; +} + +/** + * An actual socket connection - allowing transmit/receive of TCP data + * @url http://www.espruino.com/Reference#dgramSocket + */ +declare class dgramSocket { + /** + * The 'message' event is called when a datagram message is received. If a handler + * is defined with `X.on('message', function(msg) { ... })` then it will be called` + * @param {string} event - The event to listen to. + * @param {(msg: any, rinfo: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `msg` A string containing the received message + * * `rinfo` Sender address,port containing information + * @url http://www.espruino.com/Reference#l_dgramSocket_message + */ + static on(event: "message", callback: (msg: any, rinfo: any) => void): void; + + /** + * Called when the connection closes. + * @param {string} event - The event to listen to. + * @param {(had_error: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `had_error` A boolean indicating whether the connection had an error (use an error event handler to get error details). + * @url http://www.espruino.com/Reference#l_dgramSocket_close + */ + static on(event: "close", callback: (had_error: any) => void): void; + + /** + * + * @param {any} buffer - A string containing message to send + * @param {any} offset - Offset in the passed string where the message starts [optional] + * @param {any} length - Number of bytes in the message [optional] + * @param {any} args - Destination port number, Destination IP address string + * @url http://www.espruino.com/Reference#l_dgramSocket_send + */ + send(buffer: any, offset: any, length: any, ...args: any[]): void; + + /** + * + * @param {number} port - The port to bind at + * @param {any} callback - A function(res) that will be called when the socket is bound. You can then call `res.on('message', function(message, info) { ... })` and `res.on('close', function() { ... })` to deal with the response. + * @returns {any} The dgramSocket instance that 'bind' was called on + * @url http://www.espruino.com/Reference#l_dgramSocket_bind + */ + bind(port: number, callback: any): any; + + /** + * Close the socket + * @url http://www.espruino.com/Reference#l_dgramSocket_close + */ + close(): void; + + /** + * + * @param {any} group - A string containing the group ip to join + * @param {any} ip - A string containing the ip to join with + * @url http://www.espruino.com/Reference#l_dgramSocket_addMembership + */ + addMembership(group: any, ip: any): void; +} + +/** + * The HTTP server created by `require('http').createServer` + * @url http://www.espruino.com/Reference#httpSrv + */ +declare class httpSrv { + + + /** + * Start listening for new HTTP connections on the given port + * + * @param {number} port - The port to listen on + * @returns {any} The HTTP server instance that 'listen' was called on + * @url http://www.espruino.com/Reference#l_httpSrv_listen + */ + listen(port: number): any; + + /** + * Stop listening for new HTTP connections + * @url http://www.espruino.com/Reference#l_httpSrv_close + */ + close(): void; +} + +/** + * The HTTP server request + * @url http://www.espruino.com/Reference#httpSRq + */ +declare class httpSRq { + /** + * The 'data' event is called when data is received. If a handler is defined with + * `X.on('data', function(data) { ... })` then it will be called, otherwise data + * will be stored in an internal buffer, where it can be retrieved with `X.read()` + * @param {string} event - The event to listen to. + * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `data` A string containing one or more characters of received data + * @url http://www.espruino.com/Reference#l_httpSRq_data + */ + static on(event: "data", callback: (data: any) => void): void; + + /** + * Called when the connection closes. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_httpSRq_close + */ + static on(event: "close", callback: () => void): void; + + /** + * The headers to sent to the server with this HTTP request. + * @returns {any} An object mapping header name to value + * @url http://www.espruino.com/Reference#l_httpSRq_headers + */ + headers: any; + + /** + * The HTTP method used with this request. Often `"GET"`. + * @returns {any} A string + * @url http://www.espruino.com/Reference#l_httpSRq_method + */ + method: any; + + /** + * The URL requested in this HTTP request, for instance: + * * `"/"` - the main page + * * `"/favicon.ico"` - the web page's icon + * @returns {any} A string representing the URL + * @url http://www.espruino.com/Reference#l_httpSRq_url + */ + url: any; + + /** + * Return how many bytes are available to read. If there is already a listener for + * data, this will always return 0. + * @returns {number} How many bytes are available + * @url http://www.espruino.com/Reference#l_httpSRq_available + */ + available(): number; + + /** + * Return a string containing characters that have been received + * + * @param {number} chars - The number of characters to read, or undefined/0 for all available + * @returns {any} A string containing the required bytes. + * @url http://www.espruino.com/Reference#l_httpSRq_read + */ + read(chars: number): any; + + /** + * Pipe this to a stream (an object with a 'write' method) + * + * @param {any} destination - The destination file/stream that will receive content from the source. + * @param {any} [options] + * [optional] An object `{ chunkSize : int=32, end : bool=true, complete : function }` + * chunkSize : The amount of data to pipe from source to destination at a time + * complete : a function to call when the pipe activity is complete + * end : call the 'end' function on the destination when the source is finished + * @url http://www.espruino.com/Reference#l_httpSRq_pipe + */ + pipe(destination: any, options?: any): void; +} + +/** + * The HTTP server response + * @url http://www.espruino.com/Reference#httpSRs + */ +declare class httpSRs { + /** + * An event that is fired when the buffer is empty and it can accept more data to + * send. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_httpSRs_drain + */ + static on(event: "drain", callback: () => void): void; + + /** + * Called when the connection closes. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_httpSRs_close + */ + static on(event: "close", callback: () => void): void; + + /** + * The headers to send back along with the HTTP response. + * The default contents are: + * ``` + * { + * "Connection": "close" + * } + * ``` + * @returns {any} An object mapping header name to value + * @url http://www.espruino.com/Reference#l_httpSRs_headers + */ + headers: any; + + /** + * This function writes the `data` argument as a string. Data that is passed in + * (including arrays) will be converted to a string with the normal JavaScript + * `toString` method. For more information about sending binary data see + * `Socket.write` + * + * @param {any} data - A string containing data to send + * @returns {boolean} For node.js compatibility, returns the boolean false. When the send buffer is empty, a `drain` event will be sent + * @url http://www.espruino.com/Reference#l_httpSRs_write + */ + write(data: any): boolean; + + /** + * See `Socket.write` for more information about the data argument + * + * @param {any} data - A string containing data to send + * @url http://www.espruino.com/Reference#l_httpSRs_end + */ + end(data: any): void; + + /** + * Send the given status code and headers. If not explicitly called this will be + * done automatically the first time data is written to the response. + * This cannot be called twice, or after data has already been sent in the + * response. + * + * @param {number} statusCode - The HTTP status code + * @param {any} headers - An object containing the headers + * @url http://www.espruino.com/Reference#l_httpSRs_writeHead + */ + writeHead(statusCode: number, headers: any): void; + + /** + * Set a value to send in the header of this HTTP response. This updates the + * `httpSRs.headers` property. + * Any headers supplied to `writeHead` will overwrite any headers with the same + * name. + * + * @param {any} name - The name of the header as a String + * @param {any} value - The value of the header as a String + * @url http://www.espruino.com/Reference#l_httpSRs_setHeader + */ + setHeader(name: any, value: any): void; +} + +/** + * The HTTP client request, returned by `http.request()` and `http.get()`. + * @url http://www.espruino.com/Reference#httpCRq + */ +declare class httpCRq { + /** + * An event that is fired when the buffer is empty and it can accept more data to + * send. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_httpCRq_drain + */ + static on(event: "drain", callback: () => void): void; + + /** + * An event that is fired if there is an error making the request and the response + * callback has not been invoked. In this case the error event concludes the + * request attempt. The error event function receives an error object as parameter + * with a `code` field and a `message` field. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_httpCRq_error + */ + static on(event: "error", callback: () => void): void; + + /** + * This function writes the `data` argument as a string. Data that is passed in + * (including arrays) will be converted to a string with the normal JavaScript + * `toString` method. For more information about sending binary data see + * `Socket.write` + * + * @param {any} data - A string containing data to send + * @returns {boolean} For node.js compatibility, returns the boolean false. When the send buffer is empty, a `drain` event will be sent + * @url http://www.espruino.com/Reference#l_httpCRq_write + */ + write(data: any): boolean; + + /** + * Finish this HTTP request - optional data to append as an argument + * See `Socket.write` for more information about the data argument + * + * @param {any} data - A string containing data to send + * @url http://www.espruino.com/Reference#l_httpCRq_end + */ + end(data: any): void; +} + +/** + * The HTTP client response, passed to the callback of `http.request()` an + * `http.get()`. + * @url http://www.espruino.com/Reference#httpCRs + */ +declare class httpCRs { + /** + * The 'data' event is called when data is received. If a handler is defined with + * `X.on('data', function(data) { ... })` then it will be called, otherwise data + * will be stored in an internal buffer, where it can be retrieved with `X.read()` + * @param {string} event - The event to listen to. + * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `data` A string containing one or more characters of received data + * @url http://www.espruino.com/Reference#l_httpCRs_data + */ + static on(event: "data", callback: (data: any) => void): void; + + /** + * Called when the connection closes with one `hadError` boolean parameter, which + * indicates whether an error occurred. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_httpCRs_close + */ + static on(event: "close", callback: () => void): void; + + /** + * An event that is fired if there is an error receiving the response. The error + * event function receives an error object as parameter with a `code` field and a + * `message` field. After the error event the close even will also be triggered to + * conclude the HTTP request/response. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_httpCRs_error + */ + static on(event: "error", callback: () => void): void; + + /** + * The headers received along with the HTTP response + * @returns {any} An object mapping header name to value + * @url http://www.espruino.com/Reference#l_httpCRs_headers + */ + headers: any; + + /** + * The HTTP response's status code - usually `"200"` if all went well + * @returns {any} The status code as a String + * @url http://www.espruino.com/Reference#l_httpCRs_statusCode + */ + statusCode: any; + + /** + * The HTTP response's status message - Usually `"OK"` if all went well + * @returns {any} An String Status Message + * @url http://www.espruino.com/Reference#l_httpCRs_statusMessage + */ + statusMessage: any; + + /** + * The HTTP version reported back by the server - usually `"1.1"` + * @returns {any} Th + * @url http://www.espruino.com/Reference#l_httpCRs_httpVersion + */ + httpVersion: any; + + /** + * Return how many bytes are available to read. If there is a 'data' event handler, + * this will always return 0. + * @returns {number} How many bytes are available + * @url http://www.espruino.com/Reference#l_httpCRs_available + */ + available(): number; + + /** + * Return a string containing characters that have been received + * + * @param {number} chars - The number of characters to read, or undefined/0 for all available + * @returns {any} A string containing the required bytes. + * @url http://www.espruino.com/Reference#l_httpCRs_read + */ + read(chars: number): any; + + /** + * Pipe this to a stream (an object with a 'write' method) + * + * @param {any} destination - The destination file/stream that will receive content from the source. + * @param {any} [options] + * [optional] An object `{ chunkSize : int=32, end : bool=true, complete : function }` + * chunkSize : The amount of data to pipe from source to destination at a time + * complete : a function to call when the pipe activity is complete + * end : call the 'end' function on the destination when the source is finished + * @url http://www.espruino.com/Reference#l_httpCRs_pipe + */ + pipe(destination: any, options?: any): void; +} + +/** + * An instantiation of an Ethernet network adaptor + * @url http://www.espruino.com/Reference#Ethernet + */ +declare class Ethernet { + + + /** + * Get the current IP address, subnet, gateway and mac address. + * + * @param {any} [options] - [optional] An `callback(err, ipinfo)` function to be called back with the IP information. + * @returns {any} + * @url http://www.espruino.com/Reference#l_Ethernet_getIP + */ + getIP(options?: any): any; + + /** + * Set the current IP address or get an IP from DHCP (if no options object is + * specified) + * If 'mac' is specified as an option, it must be a string of the form + * `"00:01:02:03:04:05"` The default mac is 00:08:DC:01:02:03. + * + * @param {any} options - Object containing IP address options `{ ip : '1.2.3.4', subnet : '...', gateway: '...', dns:'...', mac:':::::' }`, or do not supply an object in order to force DHCP. + * @param {any} [callback] - [optional] An `callback(err)` function to invoke when ip is set. `err==null` on success, or a string on failure. + * @returns {boolean} True on success + * @url http://www.espruino.com/Reference#l_Ethernet_setIP + */ + setIP(options: any, callback?: any): boolean; + + /** + * Set hostname used during the DHCP request. Minimum 8 and maximum 12 characters, + * best set before calling `eth.setIP()`. Default is WIZnet010203, 010203 is the + * default nic as part of the mac. + * + * @param {any} hostname - hostname as string + * @param {any} [callback] - [optional] An `callback(err)` function to be called back with null or error text. + * @returns {boolean} True on success + * @url http://www.espruino.com/Reference#l_Ethernet_setHostname + */ + setHostname(hostname: any, callback?: any): boolean; + + /** + * Returns the hostname + * + * @param {any} [callback] - [optional] An `callback(err,hostname)` function to be called back with the status information. + * @returns {any} + * @url http://www.espruino.com/Reference#l_Ethernet_getHostname + */ + getHostname(callback?: any): any; + + /** + * Get the current status of the ethernet device + * + * @param {any} [options] - [optional] An `callback(err, status)` function to be called back with the status information. + * @returns {any} + * @url http://www.espruino.com/Reference#l_Ethernet_getStatus + */ + getStatus(options?: any): any; +} + +/** + * An instantiation of a WiFi network adaptor + * @url http://www.espruino.com/Reference#WLAN + */ +declare class WLAN { + + + /** + * Connect to a wireless network + * + * @param {any} ap - Access point name + * @param {any} key - WPA2 key (or undefined for unsecured connection) + * @param {any} callback - Function to call back with connection status. It has one argument which is one of 'connect'/'disconnect'/'dhcp' + * @returns {boolean} True if connection succeeded, false if it didn't. + * @url http://www.espruino.com/Reference#l_WLAN_connect + */ + connect(ap: any, key: any, callback: any): boolean; + + /** + * Completely uninitialise and power down the CC3000. After this you'll have to use + * ```require("CC3000").connect()``` again. + * @url http://www.espruino.com/Reference#l_WLAN_disconnect + */ + disconnect(): void; + + /** + * Completely uninitialise and power down the CC3000, then reconnect to the old + * access point. + * @url http://www.espruino.com/Reference#l_WLAN_reconnect + */ + reconnect(): void; + + /** + * Get the current IP address + * @returns {any} + * @url http://www.espruino.com/Reference#l_WLAN_getIP + */ + getIP(): any; + + /** + * Set the current IP address for get an IP from DHCP (if no options object is + * specified). + * **Note:** Changes are written to non-volatile memory, but will only take effect + * after calling `wlan.reconnect()` + * + * @param {any} options - Object containing IP address options `{ ip : '1,2,3,4', subnet, gateway, dns }`, or do not supply an object in otder to force DHCP. + * @returns {boolean} True on success + * @url http://www.espruino.com/Reference#l_WLAN_setIP + */ + setIP(options: any): boolean; +} + /** * Class containing [micro:bit's](https://www.espruino.com/MicroBit) utility * functions. @@ -373,296 +2883,79 @@ declare class Microbit { static record(samplesPerSecond: any, callback: any, samples?: any): void; -} - -interface MathConstructor { - /** - * @returns {number} The value of E - 2.718281828459045 - * @url http://www.espruino.com/Reference#l_Math_E - */ - E: number; - - /** - * @returns {number} The value of PI - 3.141592653589793 - * @url http://www.espruino.com/Reference#l_Math_PI - */ - PI: number; - - /** - * @returns {number} The natural logarithm of 2 - 0.6931471805599453 - * @url http://www.espruino.com/Reference#l_Math_LN2 - */ - LN2: number; - - /** - * @returns {number} The natural logarithm of 10 - 2.302585092994046 - * @url http://www.espruino.com/Reference#l_Math_LN10 - */ - LN10: number; - - /** - * @returns {number} The base 2 logarithm of e - 1.4426950408889634 - * @url http://www.espruino.com/Reference#l_Math_LOG2E - */ - LOG2E: number; - - /** - * @returns {number} The base 10 logarithm of e - 0.4342944819032518 - * @url http://www.espruino.com/Reference#l_Math_LOG10E - */ - LOG10E: number; - - /** - * @returns {number} The square root of 2 - 1.4142135623730951 - * @url http://www.espruino.com/Reference#l_Math_SQRT2 - */ - SQRT2: number; - - /** - * @returns {number} The square root of 1/2 - 0.7071067811865476 - * @url http://www.espruino.com/Reference#l_Math_SQRT1_2 - */ - SQRT1_2: number; - - /** - * - * @param {number} x - A floating point value - * @returns {number} The absolute value of x (eg, ```Math.abs(2)==2```, but also ```Math.abs(-2)==2```) - * @url http://www.espruino.com/Reference#l_Math_abs - */ - abs(x: number): number; - - /** - * - * @param {number} x - The value to get the arc cosine of - * @returns {number} The arc cosine of x, between 0 and PI - * @url http://www.espruino.com/Reference#l_Math_acos - */ - acos(x: number): number; - - /** - * - * @param {number} x - The value to get the arc sine of - * @returns {number} The arc sine of x, between -PI/2 and PI/2 - * @url http://www.espruino.com/Reference#l_Math_asin - */ - asin(x: number): number; - - /** - * - * @param {number} x - The value to get the arc tangent of - * @returns {number} The arc tangent of x, between -PI/2 and PI/2 - * @url http://www.espruino.com/Reference#l_Math_atan - */ - atan(x: number): number; - - /** - * - * @param {number} y - The Y-part of the angle to get the arc tangent of - * @param {number} x - The X-part of the angle to get the arc tangent of - * @returns {number} The arctangent of Y/X, between -PI and PI - * @url http://www.espruino.com/Reference#l_Math_atan2 - */ - atan2(y: number, x: number): number; - - /** - * - * @param {number} theta - The angle to get the cosine of - * @returns {number} The cosine of theta - * @url http://www.espruino.com/Reference#l_Math_cos - */ - cos(theta: number): number; - - /** - * - * @param {number} x - The value to raise to the power - * @param {number} y - The power x should be raised to - * @returns {number} x raised to the power y (x^y) - * @url http://www.espruino.com/Reference#l_Math_pow - */ - pow(x: number, y: number): number; - - /** - * @returns {number} A random number between 0 and 1 - * @url http://www.espruino.com/Reference#l_Math_random - */ - random(): number; - - /** - * - * @param {number} x - The value to round - * @returns {any} x, rounded to the nearest integer - * @url http://www.espruino.com/Reference#l_Math_round - */ - round(x: number): any; - - /** - * - * @param {number} theta - The angle to get the sine of - * @returns {number} The sine of theta - * @url http://www.espruino.com/Reference#l_Math_sin - */ - sin(theta: number): number; - - /** - * - * @param {number} theta - The angle to get the tangent of - * @returns {number} The tangent of theta - * @url http://www.espruino.com/Reference#l_Math_tan - */ - tan(theta: number): number; - - /** - * - * @param {number} x - The value to take the square root of - * @returns {number} The square root of x - * @url http://www.espruino.com/Reference#l_Math_sqrt - */ - sqrt(x: number): number; - - /** - * - * @param {number} x - The value to round up - * @returns {number} x, rounded upwards to the nearest integer - * @url http://www.espruino.com/Reference#l_Math_ceil - */ - ceil(x: number): number; - - /** - * - * @param {number} x - The value to round down - * @returns {number} x, rounded downwards to the nearest integer - * @url http://www.espruino.com/Reference#l_Math_floor - */ - floor(x: number): number; - - /** - * - * @param {number} x - The value raise E to the power of - * @returns {number} E^x - * @url http://www.espruino.com/Reference#l_Math_exp - */ - exp(x: number): number; - - /** - * - * @param {number} x - The value to take the logarithm (base E) root of - * @returns {number} The log (base E) of x - * @url http://www.espruino.com/Reference#l_Math_log - */ - log(x: number): number; - - /** - * DEPRECATED - Please use `E.clip()` instead. Clip a number to be between min and - * max (inclusive) - * - * @param {number} x - A floating point value to clip - * @param {number} min - The smallest the value should be - * @param {number} max - The largest the value should be - * @returns {number} The value of x, clipped so as not to be below min or above max. - * @url http://www.espruino.com/Reference#l_Math_clip - */ - clip(x: number, min: number, max: number): number; - - /** - * DEPRECATED - This is not part of standard JavaScript libraries - * Wrap a number around if it is less than 0 or greater than or equal to max. For - * instance you might do: ```Math.wrap(angleInDegrees, 360)``` - * - * @param {number} x - A floating point value to wrap - * @param {number} max - The largest the value should be - * @returns {number} The value of x, wrapped so as not to be below min or above max. - * @url http://www.espruino.com/Reference#l_Math_wrap - */ - wrap(x: number, max: number): number; - - /** - * Find the minimum of a series of numbers - * - * @param {any} args - Floating point values to clip - * @returns {number} The minimum of the supplied values - * @url http://www.espruino.com/Reference#l_Math_min - */ - min(...args: any[]): number; - - /** - * Find the maximum of a series of numbers - * - * @param {any} args - Floating point values to clip - * @returns {number} The maximum of the supplied values - * @url http://www.espruino.com/Reference#l_Math_max - */ - max(...args: any[]): number; -} - -interface Math { - } /** - * This is a standard JavaScript class that contains useful Maths routines - * @url http://www.espruino.com/Reference#Math + * This is the File object - it allows you to stream data to and from files (As + * opposed to the `require('fs').readFile(..)` style functions that read an entire + * file). + * To create a File object, you must type ```var fd = + * E.openFile('filepath','mode')``` - see [E.openFile](#l_E_openFile) for more + * information. + * **Note:** If you want to remove an SD card after you have started using it, you + * *must* call `E.unmountSD()` or you may cause damage to the card. + * @url http://www.espruino.com/Reference#File */ -declare const Math: MathConstructor - -/** - * Class containing an instance of TFMicroInterpreter - * @url http://www.espruino.com/Reference#TFMicroInterpreter - */ -declare class TFMicroInterpreter { +declare class File { /** - * @returns {any} An arraybuffer referencing the input data - * @url http://www.espruino.com/Reference#l_TFMicroInterpreter_getInput + * Close an open file. + * @url http://www.espruino.com/Reference#l_File_close */ - getInput(): ArrayBufferView; + close(): void; /** - * @returns {any} An arraybuffer referencing the output data - * @url http://www.espruino.com/Reference#l_TFMicroInterpreter_getOutput - */ - getOutput(): ArrayBufferView; - - /** - * @url http://www.espruino.com/Reference#l_TFMicroInterpreter_invoke - */ - invoke(): void; -} - -/** - * Class containing utility functions for accessing IO on the hexagonal badge - * @url http://www.espruino.com/Reference#Badge - */ -declare class Badge { - /** - * Capacitive sense - the higher the capacitance, the higher the number returned. - * Supply a corner number between 1 and 6, and an integer value will be returned - * that is proportional to the capacitance + * Write data to a file. + * **Note:** By default this function flushes all changes to the SD card, which + * makes it slow (but also safe!). You can use `E.setFlags({unsyncFiles:1})` to + * disable this behaviour and really speed up writes - but then you must be sure to + * close all files you are writing before power is lost or you will cause damage to + * your SD card's filesystem. * - * @param {number} corner - The corner to use - * @returns {number} Capacitive sense counter - * @url http://www.espruino.com/Reference#l_Badge_capSense + * @param {any} buffer - A string containing the bytes to write + * @returns {number} the number of bytes written + * @url http://www.espruino.com/Reference#l_File_write */ - static capSense(corner: number): number; + write(buffer: any): number; /** - * Return an approximate battery percentage remaining based on a normal CR2032 - * battery (2.8 - 2.2v) - * @returns {number} A percentage between 0 and 100 - * @url http://www.espruino.com/Reference#l_Badge_getBatteryPercentage - */ - static getBatteryPercentage(): number; - - /** - * Set the LCD's contrast + * Read data in a file in byte size chunks * - * @param {number} c - Contrast between 0 and 1 - * @url http://www.espruino.com/Reference#l_Badge_setContrast + * @param {number} length - is an integer specifying the number of bytes to read. + * @returns {any} A string containing the characters that were read + * @url http://www.espruino.com/Reference#l_File_read */ - static setContrast(c: number): void; + read(length: number): any; + /** + * Skip the specified number of bytes forward in the file + * + * @param {number} nBytes - is a positive integer specifying the number of bytes to skip forwards. + * @url http://www.espruino.com/Reference#l_File_skip + */ + skip(nBytes: number): void; + /** + * Seek to a certain position in the file + * + * @param {number} nBytes - is an integer specifying the number of bytes to skip forwards. + * @url http://www.espruino.com/Reference#l_File_seek + */ + seek(nBytes: number): void; + + /** + * Pipe this file to a stream (an object with a 'write' method) + * + * @param {any} destination - The destination file/stream that will receive content from the source. + * @param {any} [options] + * [optional] An object `{ chunkSize : int=32, end : bool=true, complete : function }` + * chunkSize : The amount of data to pipe from source to destination at a time + * complete : a function to call when the pipe activity is complete + * end : call the 'end' function on the destination when the source is finished + * @url http://www.espruino.com/Reference#l_File_pipe + */ + pipe(destination: any, options?: any): void; } /** @@ -897,11 +3190,11 @@ declare class Puck { * `Puck.IR(pulseTimes, led_anode)` (on 2v05 and above). * * @param {any} data - An array of pulse lengths, in milliseconds - * @param {Pin} cathode - (optional) pin to use for IR LED cathode - if not defined, the built-in IR LED is used - * @param {Pin} anode - (optional) pin to use for IR LED anode - if not defined, the built-in IR LED is used + * @param {Pin} [cathode] - [optional] pin to use for IR LED cathode - if not defined, the built-in IR LED is used + * @param {Pin} [anode] - [optional] pin to use for IR LED anode - if not defined, the built-in IR LED is used * @url http://www.espruino.com/Reference#l_Puck_IR */ - static IR(data: any, cathode: Pin, anode: Pin): void; + static IR(data: any, cathode?: Pin, anode?: Pin): void; /** * Capacitive sense - the higher the capacitance, the higher the number returned. @@ -957,163 +3250,1076 @@ declare class Puck { } /** - * This is the File object - it allows you to stream data to and from files (As - * opposed to the `require('fs').readFile(..)` style functions that read an entire - * file). - * To create a File object, you must type ```var fd = - * E.openFile('filepath','mode')``` - see [E.openFile](#l_E_openFile) for more - * information. - * **Note:** If you want to remove an SD card after you have started using it, you - * *must* call `E.unmountSD()` or you may cause damage to the card. - * @url http://www.espruino.com/Reference#File + * Class containing utility functions for the [Bangle.js Smart + * Watch](http://www.espruino.com/Bangle.js) + * @url http://www.espruino.com/Reference#Bangle */ -declare class File { - - +declare class Bangle { /** - * Close an open file. - * @url http://www.espruino.com/Reference#l_File_close + * Accelerometer data available with `{x,y,z,diff,mag}` object as a parameter. + * * `x` is X axis (left-right) in `g` + * * `y` is Y axis (up-down) in `g` + * * `z` is Z axis (in-out) in `g` + * * `diff` is difference between this and the last reading in `g` + * * `mag` is the magnitude of the acceleration in `g` + * You can also retrieve the most recent reading with `Bangle.getAccel()`. + * @param {string} event - The event to listen to. + * @param {(xyz: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `xyz` + * @url http://www.espruino.com/Reference#l_Bangle_accel */ - close(): void; + static on(event: "accel", callback: (xyz: AccelData) => void): void; /** - * Write data to a file. - * **Note:** By default this function flushes all changes to the SD card, which - * makes it slow (but also safe!). You can use `E.setFlags({unsyncFiles:1})` to - * disable this behaviour and really speed up writes - but then you must be sure to - * close all files you are writing before power is lost or you will cause damage to - * your SD card's filesystem. - * - * @param {any} buffer - A string containing the bytes to write - * @returns {number} the number of bytes written - * @url http://www.espruino.com/Reference#l_File_write + * Called whenever a step is detected by Bangle.js's pedometer. + * @param {string} event - The event to listen to. + * @param {(up: number) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `up` The number of steps since Bangle.js was last reset + * @url http://www.espruino.com/Reference#l_Bangle_step */ - write(buffer: any): number; + static on(event: "step", callback: (up: number) => void): void; /** - * Read data in a file in byte size chunks - * - * @param {number} length - is an integer specifying the number of bytes to read. - * @returns {any} A string containing the characters that were read - * @url http://www.espruino.com/Reference#l_File_read + * See `Bangle.getHealthStatus()` for more information. This is used for health + * tracking to allow Bangle.js to record historical exercise data. + * @param {string} event - The event to listen to. + * @param {(info: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `info` An object containing the last 10 minutes health data + * @url http://www.espruino.com/Reference#l_Bangle_health */ - read(length: number): any; + static on(event: "health", callback: (info: HealthStatus) => void): void; /** - * Skip the specified number of bytes forward in the file - * - * @param {number} nBytes - is a positive integer specifying the number of bytes to skip forwards. - * @url http://www.espruino.com/Reference#l_File_skip + * Has the watch been moved so that it is face-up, or not face up? + * @param {string} event - The event to listen to. + * @param {(up: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `up` `true` if face-up + * @url http://www.espruino.com/Reference#l_Bangle_faceUp */ - skip(nBytes: number): void; + static on(event: "faceUp", callback: (up: boolean) => void): void; /** - * Seek to a certain position in the file - * - * @param {number} nBytes - is an integer specifying the number of bytes to skip forwards. - * @url http://www.espruino.com/Reference#l_File_seek + * This event happens when the watch has been twisted around it's axis - for + * instance as if it was rotated so someone could look at the time. + * To tweak when this happens, see the `twist*` options in `Bangle.setOptions()` + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_Bangle_twist */ - seek(nBytes: number): void; + static on(event: "twist", callback: () => void): void; /** - * Pipe this file to a stream (an object with a 'write' method) + * Is the battery charging or not? + * @param {string} event - The event to listen to. + * @param {(charging: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `charging` `true` if charging + * @url http://www.espruino.com/Reference#l_Bangle_charging + */ + static on(event: "charging", callback: (charging: boolean) => void): void; + + /** + * Magnetometer/Compass data available with `{x,y,z,dx,dy,dz,heading}` object as a + * parameter + * * `x/y/z` raw x,y,z magnetometer readings + * * `dx/dy/dz` readings based on calibration since magnetometer turned on + * * `heading` in degrees based on calibrated readings (will be NaN if magnetometer + * hasn't been rotated around 360 degrees). + * **Note:** In 2v15 firmware and earlier the heading is inverted (360-heading). There's + * a fix in the bootloader which will apply a fix for those headings, but old apps may + * still expect an inverted value. + * To get this event you must turn the compass on with `Bangle.setCompassPower(1)`. + * You can also retrieve the most recent reading with `Bangle.getCompass()`. + * @param {string} event - The event to listen to. + * @param {(xyz: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `xyz` + * @url http://www.espruino.com/Reference#l_Bangle_mag + */ + static on(event: "mag", callback: (xyz: CompassData) => void): void; + + /** + * Raw NMEA GPS / u-blox data messages received as a string + * To get this event you must turn the GPS on with `Bangle.setGPSPower(1)`. + * @param {string} event - The event to listen to. + * @param {(nmea: any, dataLoss: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `nmea` A string containing the raw NMEA data from the GPS + * * `dataLoss` This is set to true if some lines of GPS data have previously been lost (eg because system was too busy to queue up a GPS-raw event) + * @url http://www.espruino.com/Reference#l_Bangle_GPS-raw + */ + static on(event: "GPS-raw", callback: (nmea: string, dataLoss: boolean) => void): void; + + /** + * GPS data, as an object. Contains: + * ``` + * { "lat": number, // Latitude in degrees + * "lon": number, // Longitude in degrees + * "alt": number, // altitude in M + * "speed": number, // Speed in kph + * "course": number, // Course in degrees + * "time": Date, // Current Time (or undefined if not known) + * "satellites": 7, // Number of satellites + * "fix": 1 // NMEA Fix state - 0 is no fix + * "hdop": number, // Horizontal Dilution of Precision + * } + * ``` + * If a value such as `lat` is not known because there is no fix, it'll be `NaN`. + * `hdop` is a value from the GPS receiver that gives a rough idea of accuracy of + * lat/lon based on the geometry of the satellites in range. Multiply by 5 to get a + * value in meters. This is just a ballpark estimation and should not be considered + * remotely accurate. + * To get this event you must turn the GPS on with `Bangle.setGPSPower(1)`. + * @param {string} event - The event to listen to. + * @param {(fix: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `fix` An object with fix info (see below) + * @url http://www.espruino.com/Reference#l_Bangle_GPS + */ + static on(event: "GPS", callback: (fix: GPSFix) => void): void; + + /** + * Heat rate data, as an object. Contains: + * ``` + * { "bpm": number, // Beats per minute + * "confidence": number, // 0-100 percentage confidence in the heart rate + * "raw": Uint8Array, // raw samples from heart rate monitor + * } + * ``` + * To get this event you must turn the heart rate monitor on with + * `Bangle.setHRMPower(1)`. + * @param {string} event - The event to listen to. + * @param {(hrm: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `hrm` An object with heart rate info (see below) + * @url http://www.espruino.com/Reference#l_Bangle_HRM + */ + static on(event: "HRM", callback: (hrm: { bpm: number, confidence: number, raw: Uint8Array }) => void): void; + + /** + * Called when heart rate sensor data is available - see `Bangle.setHRMPower(1)`. + * `hrm` is of the form: + * ``` + * { "raw": -1, // raw value from sensor + * "filt": -1, // bandpass-filtered raw value from sensor + * "bpm": 88.9, // last BPM value measured + * "confidence": 0 // confidence in the BPM value + * } + * ``` + * @param {string} event - The event to listen to. + * @param {(hrm: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `hrm` A object containing instant readings from the heart rate sensor + * @url http://www.espruino.com/Reference#l_Bangle_HRM-raw + */ + static on(event: "HRM-raw", callback: (hrm: { raw: number, filt: number, bpm: number, confidence: number }) => void): void; + + /** + * When `Bangle.setBarometerPower(true)` is called, this event is fired containing + * barometer readings. + * Same format as `Bangle.getPressure()` + * @param {string} event - The event to listen to. + * @param {(e: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `e` An object containing `{temperature,pressure,altitude}` + * @url http://www.espruino.com/Reference#l_Bangle_pressure + */ + static on(event: "pressure", callback: (e: PressureData) => void): void; + + /** + * Has the screen been turned on or off? Can be used to stop tasks that are no + * longer useful if nothing is displayed. Also see `Bangle.isLCDOn()` + * @param {string} event - The event to listen to. + * @param {(on: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `on` `true` if screen is on + * @url http://www.espruino.com/Reference#l_Bangle_lcdPower + */ + static on(event: "lcdPower", callback: (on: boolean) => void): void; + + /** + * Has the screen been locked? Also see `Bangle.isLocked()` + * @param {string} event - The event to listen to. + * @param {(on: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `on` `true` if screen is locked, `false` if it is unlocked and touchscreen/buttons will work + * @url http://www.espruino.com/Reference#l_Bangle_lock + */ + static on(event: "lock", callback: (on: boolean) => void): void; + + /** + * If the watch is tapped, this event contains information on the way it was + * tapped. + * `dir` reports the side of the watch that was tapped (not the direction it was + * tapped in). + * ``` + * { + * dir : "left/right/top/bottom/front/back", + * double : true/false // was this a double-tap? + * x : -2 .. 2, // the axis of the tap + * y : -2 .. 2, // the axis of the tap + * z : -2 .. 2 // the axis of the tap + * ``` + * @param {string} event - The event to listen to. + * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `data` `{dir, double, x, y, z}` + * @url http://www.espruino.com/Reference#l_Bangle_tap + */ + static on(event: "tap", callback: (data: { dir: "left" | "right" | "top" | "bottom" | "front" | "back", double: boolean, x: TapAxis, y: TapAxis, z: TapAxis }) => void): void; + + /** + * Emitted when a 'gesture' (fast movement) is detected + * @param {string} event - The event to listen to. + * @param {(xyz: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `xyz` An Int8Array of XYZXYZXYZ data + * @url http://www.espruino.com/Reference#l_Bangle_gesture + */ + static on(event: "gesture", callback: (xyz: Int8Array) => void): void; + + /** + * Emitted when a 'gesture' (fast movement) is detected, and a Tensorflow model is + * in storage in the `".tfmodel"` file. + * If a `".tfnames"` file is specified as a comma-separated list of names, it will + * be used to decode `gesture` from a number into a string. + * @param {string} event - The event to listen to. + * @param {(gesture: any, weights: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `gesture` The name of the gesture (if '.tfnames' exists, or the index. 'undefined' if not matching + * * `weights` An array of floating point values output by the model + * @url http://www.espruino.com/Reference#l_Bangle_aiGesture + */ + static on(event: "aiGesture", callback: (gesture: string | undefined, weights: number[]) => void): void; + + /** + * Emitted when a swipe on the touchscreen is detected (a movement from + * left->right, right->left, down->up or up->down) + * Bangle.js 1 is only capable of detecting left/right swipes as it only contains a + * 2 zone touchscreen. + * @param {string} event - The event to listen to. + * @param {(directionLR: number, directionUD: number) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `directionLR` `-1` for left, `1` for right, `0` for up/down + * * `directionUD` `-1` for up, `1` for down, `0` for left/right (Bangle.js 2 only) + * @url http://www.espruino.com/Reference#l_Bangle_swipe + */ + static on(event: "swipe", callback: SwipeCallback): void; + + /** + * Emitted when the touchscreen is pressed + * @param {string} event - The event to listen to. + * @param {(button: number, xy: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `button` `1` for left, `2` for right + * * `xy` Object of form `{x,y}` containing touch coordinates (if the device supports full touch). Clipped to 0..175 (LCD pixel coordinates) on firmware 2v13 and later. + * @url http://www.espruino.com/Reference#l_Bangle_touch + */ + static on(event: "touch", callback: TouchCallback): void; + + /** + * Emitted when the touchscreen is dragged or released + * The touchscreen extends past the edge of the screen and while `x` and `y` + * coordinates are arranged such that they align with the LCD's pixels, if your + * finger goes towards the edge of the screen, `x` and `y` could end up larger than + * 175 (the screen's maximum pixel coordinates) or smaller than 0. Coordinates from + * the `touch` event are clipped. + * @param {string} event - The event to listen to. + * @param {(event: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `event` Object of form `{x,y,dx,dy,b}` containing touch coordinates, difference in touch coordinates, and an integer `b` containing number of touch points (currently 1 or 0) + * @url http://www.espruino.com/Reference#l_Bangle_drag + */ + static on(event: "drag", callback: DragCallback): void; + + /** + * Emitted when the touchscreen is dragged for a large enough distance to count as + * a gesture. + * If Bangle.strokes is defined and populated with data from `Unistroke.new`, the + * `event` argument will also contain a `stroke` field containing the most closely + * matching stroke name. + * For example: + * ``` + * Bangle.strokes = { + * up : Unistroke.new(new Uint8Array([57, 151, ... 158, 137])), + * alpha : Unistroke.new(new Uint8Array([161, 55, ... 159, 161])), + * }; + * Bangle.on('stroke',o=>{ + * print(o.stroke); + * g.clear(1).drawPoly(o.xy); + * }); + * // Might print something like + * { + * "xy": new Uint8Array([149, 50, ... 107, 136]), + * "stroke": "alpha" + * } + * ``` + * @param {string} event - The event to listen to. + * @param {(event: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `event` Object of form `{xy:Uint8Array([x1,y1,x2,y2...])}` containing touch coordinates + * @url http://www.espruino.com/Reference#l_Bangle_stroke + */ + static on(event: "stroke", callback: (event: { xy: Uint8Array, stroke?: string }) => void): void; + + /** + * Emitted at midnight (at the point the `day` health info is reset to 0). + * Can be used for housekeeping tasks that don't want to be run during the day. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_Bangle_midnight + */ + static on(event: "midnight", callback: () => void): void; + + /** + * This function can be used to turn Bangle.js's LCD off or on. + * This function resets the Bangle's 'activity timer' (like pressing a button or + * the screen would) so after a time period of inactivity set by + * `Bangle.setLCDTimeout` the screen will turn off. + * If you want to keep the screen on permanently (until apps are changed) you can + * do: + * ``` + * Bangle.setLCDTimeout(0); // turn off the timeout + * Bangle.setLCDPower(1); // keep screen on + * ``` + * **When on full, the LCD draws roughly 40mA.** You can adjust When brightness + * using `Bangle.setLCDBrightness`. + * + * @param {boolean} isOn - True if the LCD should be on, false if not + * @url http://www.espruino.com/Reference#l_Bangle_setLCDPower + */ + static setLCDPower(isOn: boolean): void; + + /** + * This function can be used to adjust the brightness of Bangle.js's display, and + * hence prolong its battery life. + * Due to hardware design constraints, software PWM has to be used which means that + * the display may flicker slightly when Bluetooth is active and the display is not + * at full power. + * **Power consumption** + * * 0 = 7mA + * * 0.1 = 12mA + * * 0.2 = 18mA + * * 0.5 = 28mA + * * 0.9 = 40mA (switching overhead) + * * 1 = 40mA + * + * @param {number} brightness - The brightness of Bangle.js's display - from 0(off) to 1(on full) + * @url http://www.espruino.com/Reference#l_Bangle_setLCDBrightness + */ + static setLCDBrightness(brightness: number): void; + + /** + * This function can be used to change the way graphics is handled on Bangle.js. + * Available options for `Bangle.setLCDMode` are: + * * `Bangle.setLCDMode()` or `Bangle.setLCDMode("direct")` (the default) - The + * drawable area is 240x240 16 bit. Unbuffered, so draw calls take effect + * immediately. Terminal and vertical scrolling work (horizontal scrolling + * doesn't). + * * `Bangle.setLCDMode("doublebuffered")` - The drawable area is 240x160 16 bit, + * terminal and scrolling will not work. `g.flip()` must be called for draw + * operations to take effect. + * * `Bangle.setLCDMode("120x120")` - The drawable area is 120x120 8 bit, + * `g.getPixel`, terminal, and full scrolling work. Uses an offscreen buffer + * stored on Bangle.js, `g.flip()` must be called for draw operations to take + * effect. + * * `Bangle.setLCDMode("80x80")` - The drawable area is 80x80 8 bit, `g.getPixel`, + * terminal, and full scrolling work. Uses an offscreen buffer stored on + * Bangle.js, `g.flip()` must be called for draw operations to take effect. + * You can also call `Bangle.setLCDMode()` to return to normal, unbuffered + * `"direct"` mode. + * + * @param {any} mode - The LCD mode (See below) + * @url http://www.espruino.com/Reference#l_Bangle_setLCDMode + */ + static setLCDMode(mode?: LCDMode): void; + + /** + * The current LCD mode. + * See `Bangle.setLCDMode` for examples. + * @returns {any} The LCD mode as a String + * @url http://www.espruino.com/Reference#l_Bangle_getLCDMode + */ + static getLCDMode(): LCDMode; + + /** + * This can be used to move the displayed memory area up or down temporarily. It's + * used for displaying notifications while keeping the main display contents + * intact. + * + * @param {number} y - The amount of pixels to shift the LCD up or down + * @url http://www.espruino.com/Reference#l_Bangle_setLCDOffset + */ + static setLCDOffset(y: number): void; + + /** + * Overlay an image or graphics instance on top of the contents of the graphics buffer. + * This only works on Bangle.js 2 because Bangle.js 1 doesn't have an offscreen buffer accessible from the CPU. + * ``` + * // display an alarm clock icon on the screen + * var img = require("heatshrink").decompress(atob(`lss4UBvvv///ovBlMyqoADv/VAwlV//1qtfAQX/BINXDoPVq/9DAP + * /AYIKDrWq0oREAYPW1QAB1IWCBQXaBQWq04WCAQP6BQeqA4P1AQPq1WggEK1WrBAIkBBQJsCBYO///fBQOoPAcqCwP3BQnwgECCwP9 + * GwIKCngWC14sB7QKCh4CBCwN/64KDgfACwWn6vWGwYsBCwOputWJgYsCgGqytVBQYsCLYOlqtqwAsFEINVrR4BFgghBBQosDEINWIQ + * YsDEIQ3DFgYhCG4msSYeVFgnrFhMvOAgsEkE/FhEggYWCFgIhDkEACwQKBEIYKBCwSGFBQJxCQwYhBBQTKDqohCBQhCCEIJlDXwrKE + * BQoWHBQdaCwuqJoI4CCwgKECwJ9CJgIKDq+qBYUq1WtBQf+BYIAC3/VBQX/tQKDz/9BQY5BAAVV/4WCBQJcBKwVf+oHBv4wCAAYhB`)); + * Bangle.setLCDOverlay(img,66,66); + * ``` + * Or use a `Graphics` instance: + * ``` + * var ovr = Graphics.createArrayBuffer(100,100,1,{msb:true}); // 1bpp + * ovr.drawLine(0,0,100,100); + * ovr.drawRect(0,0,99,99); + * Bangle.setLCDOverlay(ovr,38,38); + * ``` + * Although `Graphics` can be specified directly, it can often make more sense to + * create an Image from the `Graphics` instance, as this gives you access + * to color palettes and transparent colors. For instance this will draw a colored + * overlay with rounded corners: + * ``` + * var ovr = Graphics.createArrayBuffer(100,100,2,{msb:true}); + * ovr.setColor(1).fillRect({x:0,y:0,w:99,h:99,r:8}); + * ovr.setColor(3).fillRect({x:2,y:2,w:95,h:95,r:7}); + * ovr.setColor(2).setFont("Vector:30").setFontAlign(0,0).drawString("Hi",50,50); + * Bangle.setLCDOverlay({ + * width:ovr.getWidth(), height:ovr.getHeight(), + * bpp:2, transparent:0, + * palette:new Uint16Array([0,0,g.toColor("#F00"),g.toColor("#FFF")]), + * buffer:ovr.buffer + * },38,38); + * ``` + * + * @param {any} img - An image + * @param {number} x - The X offset the graphics instance should be overlaid on the screen with + * @param {number} y - The Y offset the graphics instance should be overlaid on the screen with + * @url http://www.espruino.com/Reference#l_Bangle_setLCDOverlay + */ + static setLCDOverlay(img: any, x: number, y: number): void; + + /** + * This function can be used to turn Bangle.js's LCD power saving on or off. + * With power saving off, the display will remain in the state you set it with + * `Bangle.setLCDPower`. + * With power saving on, the display will turn on if a button is pressed, the watch + * is turned face up, or the screen is updated (see `Bangle.setOptions` for + * configuration). It'll turn off automatically after the given timeout. + * **Note:** This function also sets the Backlight and Lock timeout (the time at + * which the touchscreen/buttons start being ignored). To set both separately, use + * `Bangle.setOptions` + * + * @param {number} isOn - The timeout of the display in seconds, or `0`/`undefined` to turn power saving off. Default is 10 seconds. + * @url http://www.espruino.com/Reference#l_Bangle_setLCDTimeout + */ + static setLCDTimeout(isOn: number): void; + + /** + * Set how often the watch should poll for new acceleration/gyro data and kick the + * Watchdog timer. It isn't recommended that you make this interval much larger + * than 1000ms, but values up to 4000ms are allowed. + * Calling this will set `Bangle.setOptions({powerSave: false})` - disabling the + * dynamic adjustment of poll interval to save battery power when Bangle.js is + * stationary. + * + * @param {number} interval - Polling interval in milliseconds (Default is 80ms - 12.5Hz to match accelerometer) + * @url http://www.espruino.com/Reference#l_Bangle_setPollInterval + */ + static setPollInterval(interval: number): void; + + /** + * Set internal options used for gestures, etc... + * * `wakeOnBTN1` should the LCD turn on when BTN1 is pressed? default = `true` + * * `wakeOnBTN2` (Bangle.js 1) should the LCD turn on when BTN2 is pressed? + * default = `true` + * * `wakeOnBTN3` (Bangle.js 1) should the LCD turn on when BTN3 is pressed? + * default = `true` + * * `wakeOnFaceUp` should the LCD turn on when the watch is turned face up? + * default = `false` + * * `wakeOnTouch` should the LCD turn on when the touchscreen is pressed? default + * = `false` + * * `wakeOnTwist` should the LCD turn on when the watch is twisted? default = + * `true` + * * `twistThreshold` How much acceleration to register a twist of the watch strap? + * Can be negative for opposite direction. default = `800` + * * `twistMaxY` Maximum acceleration in Y to trigger a twist (low Y means watch is + * facing the right way up). default = `-800` + * * `twistTimeout` How little time (in ms) must a twist take from low->high + * acceleration? default = `1000` + * * `gestureStartThresh` how big a difference before we consider a gesture + * started? default = `sqr(800)` + * * `gestureEndThresh` how small a difference before we consider a gesture ended? + * default = `sqr(2000)` + * * `gestureInactiveCount` how many samples do we keep after a gesture has ended? + * default = `4` + * * `gestureMinLength` how many samples must a gesture have before we notify about + * it? default = `10` + * * `powerSave` after a minute of not being moved, Bangle.js will change the + * accelerometer poll interval down to 800ms (10x accelerometer samples). On + * movement it'll be raised to the default 80ms. If `Bangle.setPollInterval` is + * used this is disabled, and for it to work the poll interval must be either + * 80ms or 800ms. default = `true`. Setting `powerSave:false` will disable this + * automatic power saving, but will **not** change the poll interval from its + * current value. If you desire a specific interval (e.g. the default 80ms) you + * must set it manually with `Bangle.setPollInterval(80)` after setting + * `powerSave:false`. + * * `lockTimeout` how many milliseconds before the screen locks + * * `lcdPowerTimeout` how many milliseconds before the screen turns off + * * `backlightTimeout` how many milliseconds before the screen's backlight turns + * off + * * `btnLoadTimeout` how many milliseconds does the home button have to be pressed + * for before the clock is reloaded? 1500ms default, or 0 means never. + * * `hrmPollInterval` set the requested poll interval (in milliseconds) for the + * heart rate monitor. On Bangle.js 2 only 10,20,40,80,160,200 ms are supported, + * and polling rate may not be exact. The algorithm's filtering is tuned for + * 20-40ms poll intervals, so higher/lower intervals may effect the reliability + * of the BPM reading. + * * `seaLevelPressure` (Bangle.js 2) Normally 1013.25 millibars - this is used for + * calculating altitude with the pressure sensor + * Where accelerations are used they are in internal units, where `8192 = 1g` * - * @param {any} destination - The destination file/stream that will receive content from the source. * @param {any} options - * An optional object `{ chunkSize : int=32, end : bool=true, complete : function }` - * chunkSize : The amount of data to pipe from source to destination at a time - * complete : a function to call when the pipe activity is complete - * end : call the 'end' function on the destination when the source is finished - * @url http://www.espruino.com/Reference#l_File_pipe + * @url http://www.espruino.com/Reference#l_Bangle_setOptions */ - pipe(destination: any, options: any): void; + static setOptions(options: { [key in keyof BangleOptions]?: BangleOptions[key] }): void; + + /** + * Return the current state of options as set by `Bangle.setOptions` + * @returns {any} The current state of all options + * @url http://www.espruino.com/Reference#l_Bangle_getOptions + */ + static getOptions(): BangleOptions; + + /** + * Also see the `Bangle.lcdPower` event + * @returns {boolean} Is the display on or not? + * @url http://www.espruino.com/Reference#l_Bangle_isLCDOn + */ + static isLCDOn(): boolean; + + /** + * This function can be used to lock or unlock Bangle.js (e.g. whether buttons and + * touchscreen work or not) + * + * @param {boolean} isLocked - `true` if the Bangle is locked (no user input allowed) + * @url http://www.espruino.com/Reference#l_Bangle_setLocked + */ + static setLocked(isLocked: boolean): void; + + /** + * Also see the `Bangle.lock` event + * @returns {boolean} Is the screen locked or not? + * @url http://www.espruino.com/Reference#l_Bangle_isLocked + */ + static isLocked(): boolean; + + /** + * @returns {boolean} Is the battery charging or not? + * @url http://www.espruino.com/Reference#l_Bangle_isCharging + */ + static isCharging(): boolean; + + /** + * Writes a command directly to the ST7735 LCD controller + * + * @param {number} cmd + * @param {any} data + * @url http://www.espruino.com/Reference#l_Bangle_lcdWr + */ + static lcdWr(cmd: number, data: any): void; + + /** + * Set the power to the Heart rate monitor + * When on, data is output via the `HRM` event on `Bangle`: + * ``` + * Bangle.setHRMPower(true, "myapp"); + * Bangle.on('HRM',print); + * ``` + * *When on, the Heart rate monitor draws roughly 5mA* + * + * @param {boolean} isOn - True if the heart rate monitor should be on, false if not + * @param {any} appID - A string with the app's name in, used to ensure one app can't turn off something another app is using + * @returns {boolean} Is HRM on? + * @url http://www.espruino.com/Reference#l_Bangle_setHRMPower + */ + static setHRMPower(isOn: boolean, appID: string): boolean; + + /** + * Is the Heart rate monitor powered? + * Set power with `Bangle.setHRMPower(...);` + * @returns {boolean} Is HRM on? + * @url http://www.espruino.com/Reference#l_Bangle_isHRMOn + */ + static isHRMOn(): boolean; + + /** + * Set the power to the GPS. + * When on, data is output via the `GPS` event on `Bangle`: + * ``` + * Bangle.setGPSPower(true, "myapp"); + * Bangle.on('GPS',print); + * ``` + * *When on, the GPS draws roughly 20mA* + * + * @param {boolean} isOn - True if the GPS should be on, false if not + * @param {any} appID - A string with the app's name in, used to ensure one app can't turn off something another app is using + * @returns {boolean} Is the GPS on? + * @url http://www.espruino.com/Reference#l_Bangle_setGPSPower + */ + static setGPSPower(isOn: boolean, appID: string): boolean; + + /** + * Is the GPS powered? + * Set power with `Bangle.setGPSPower(...);` + * @returns {boolean} Is the GPS on? + * @url http://www.espruino.com/Reference#l_Bangle_isGPSOn + */ + static isGPSOn(): boolean; + + /** + * Get the last available GPS fix info (or `undefined` if GPS is off). + * The fix info received is the same as you'd get from the `Bangle.GPS` event. + * @returns {any} A GPS fix object with `{lat,lon,...}` + * @url http://www.espruino.com/Reference#l_Bangle_getGPSFix + */ + static getGPSFix(): GPSFix; + + /** + * Set the power to the Compass + * When on, data is output via the `mag` event on `Bangle`: + * ``` + * Bangle.setCompassPower(true, "myapp"); + * Bangle.on('mag',print); + * ``` + * *When on, the compass draws roughly 2mA* + * + * @param {boolean} isOn - True if the Compass should be on, false if not + * @param {any} appID - A string with the app's name in, used to ensure one app can't turn off something another app is using + * @returns {boolean} Is the Compass on? + * @url http://www.espruino.com/Reference#l_Bangle_setCompassPower + */ + static setCompassPower(isOn: boolean, appID: string): boolean; + + /** + * Is the compass powered? + * Set power with `Bangle.setCompassPower(...);` + * @returns {boolean} Is the Compass on? + * @url http://www.espruino.com/Reference#l_Bangle_isCompassOn + */ + static isCompassOn(): boolean; + + /** + * Resets the compass minimum/maximum values. Can be used if the compass isn't + * providing a reliable heading any more. + * + * @url http://www.espruino.com/Reference#l_Bangle_resetCompass + */ + static resetCompass(): void; + + /** + * Set the power to the barometer IC. Once enabled, `Bangle.pressure` events are + * fired each time a new barometer reading is available. + * When on, the barometer draws roughly 50uA + * + * @param {boolean} isOn - True if the barometer IC should be on, false if not + * @param {any} appID - A string with the app's name in, used to ensure one app can't turn off something another app is using + * @returns {boolean} Is the Barometer on? + * @url http://www.espruino.com/Reference#l_Bangle_setBarometerPower + */ + static setBarometerPower(isOn: boolean, appID: string): boolean; + + /** + * Is the Barometer powered? + * Set power with `Bangle.setBarometerPower(...);` + * @returns {boolean} Is the Barometer on? + * @url http://www.espruino.com/Reference#l_Bangle_isBarometerOn + */ + static isBarometerOn(): boolean; + + /** + * Returns the current amount of steps recorded by the step counter + * @returns {number} The number of steps recorded by the step counter + * @url http://www.espruino.com/Reference#l_Bangle_getStepCount + */ + static getStepCount(): number; + + /** + * Sets the current value of the step counter + * + * @param {number} count - The value with which to reload the step counter + * @url http://www.espruino.com/Reference#l_Bangle_setStepCount + */ + static setStepCount(count: number): void; + + /** + * Get the most recent Magnetometer/Compass reading. Data is in the same format as + * the `Bangle.on('mag',` event. + * Returns an `{x,y,z,dx,dy,dz,heading}` object + * * `x/y/z` raw x,y,z magnetometer readings + * * `dx/dy/dz` readings based on calibration since magnetometer turned on + * * `heading` in degrees based on calibrated readings (will be NaN if magnetometer + * hasn't been rotated around 360 degrees). + * **Note:** In 2v15 firmware and earlier the heading is inverted (360-heading). There's + * a fix in the bootloader which will apply a fix for those headings, but old apps may + * still expect an inverted value. + * To get this event you must turn the compass on with `Bangle.setCompassPower(1)`. + * @returns {any} An object containing magnetometer readings (as below) + * @url http://www.espruino.com/Reference#l_Bangle_getCompass + */ + static getCompass(): CompassData; + + /** + * Get the most recent accelerometer reading. Data is in the same format as the + * `Bangle.on('accel',` event. + * * `x` is X axis (left-right) in `g` + * * `y` is Y axis (up-down) in `g` + * * `z` is Z axis (in-out) in `g` + * * `diff` is difference between this and the last reading in `g` (calculated by + * comparing vectors, not magnitudes) + * * `td` is the elapsed + * * `mag` is the magnitude of the acceleration in `g` + * @returns {any} An object containing accelerometer readings (as below) + * @url http://www.espruino.com/Reference#l_Bangle_getAccel + */ + static getAccel(): AccelData & { td: number }; + + /** + * `range` is one of: + * * `undefined` or `'10min'` - health data so far in this 10 minute block (eg. 9:00.00 - 9:09.59) + * * `'last'` - health data during the last 10 minute block + * * `'day'` - the health data so far for the day + * `getHealthStatus` returns an object containing: + * * `movement` is the 32 bit sum of all `acc.diff` readings since power on (and + * rolls over). It is the difference in accelerometer values as `g*8192` + * * `steps` is the number of steps during this period + * * `bpm` the best BPM reading from HRM sensor during this period + * * `bpmConfidence` best BPM confidence (0-100%) during this period + * + * @param {any} range - What time period to return data for, see below: + * @returns {any} Returns an object containing various health info + * @url http://www.espruino.com/Reference#l_Bangle_getHealthStatus + */ + static getHealthStatus(range?: "current" | "last" | "day"): HealthStatus; + + /** + * Reads debug info. Exposes the current values of `accHistoryIdx`, `accGestureCount`, `accIdleCount` and `pollInterval`. + * @returns {any} + * @url http://www.espruino.com/Reference#l_Bangle_dbg + */ + static dbg(): any; + + /** + * Writes a register on the accelerometer + * + * @param {number} reg + * @param {number} data + * @url http://www.espruino.com/Reference#l_Bangle_accelWr + */ + static accelWr(reg: number, data: number): void; + + /** + * Reads a register from the accelerometer + * **Note:** On Espruino 2v06 and before this function only returns a number (`cnt` + * is ignored). + * + * @param {number} reg + * @param {number} cnt - If specified, returns an array of the given length (max 128). If not (or 0) it returns a number + * @returns {any} + * @url http://www.espruino.com/Reference#l_Bangle_accelRd + */ + static accelRd(reg: number, cnt?: 0): number; + static accelRd(reg: number, cnt: number): number[]; + + /** + * Writes a register on the barometer IC + * + * @param {number} reg + * @param {number} data + * @url http://www.espruino.com/Reference#l_Bangle_barometerWr + */ + static barometerWr(reg: number, data: number): void; + + /** + * Reads a register from the barometer IC + * + * @param {number} reg + * @param {number} cnt - If specified, returns an array of the given length (max 128). If not (or 0) it returns a number + * @returns {any} + * @url http://www.espruino.com/Reference#l_Bangle_barometerRd + */ + static barometerRd(reg: number, cnt?: 0): number; + static barometerRd(reg: number, cnt: number): number[]; + + /** + * Writes a register on the Magnetometer/Compass + * + * @param {number} reg + * @param {number} data + * @url http://www.espruino.com/Reference#l_Bangle_compassWr + */ + static compassWr(reg: number, data: number): void; + + /** + * Read a register on the Magnetometer/Compass + * + * @param {number} reg + * @param {number} cnt - If specified, returns an array of the given length (max 128). If not (or 0) it returns a number + * @returns {any} + * @url http://www.espruino.com/Reference#l_Bangle_compassRd + */ + static compassRd(reg: number, cnt?: 0): number; + static compassRd(reg: number, cnt: number): number[]; + + /** + * Writes a register on the Heart rate monitor + * + * @param {number} reg + * @param {number} data + * @url http://www.espruino.com/Reference#l_Bangle_hrmWr + */ + static hrmWr(reg: number, data: number): void; + + /** + * Read a register on the Heart rate monitor + * + * @param {number} reg + * @param {number} cnt - If specified, returns an array of the given length (max 128). If not (or 0) it returns a number + * @returns {any} + * @url http://www.espruino.com/Reference#l_Bangle_hrmRd + */ + static hrmRd(reg: number, cnt?: 0): number; + static hrmRd(reg: number, cnt: number): number[]; + + /** + * Changes a pin state on the IO expander + * + * @param {number} mask + * @param {number} isOn + * @url http://www.espruino.com/Reference#l_Bangle_ioWr + */ + static ioWr(mask: number, isOn: number): void; + + /** + * Read temperature, pressure and altitude data. A promise is returned which will + * be resolved with `{temperature, pressure, altitude}`. + * If the Barometer has been turned on with `Bangle.setBarometerPower` then this + * will return almost immediately with the reading. If the Barometer is off, + * conversions take between 500-750ms. + * Altitude assumes a sea-level pressure of 1013.25 hPa + * ``` + * Bangle.getPressure().then(d=>{ + * console.log(d); + * // {temperature, pressure, altitude} + * }); + * ``` + * @returns {any} A promise that will be resolved with `{temperature, pressure, altitude}` + * @url http://www.espruino.com/Reference#l_Bangle_getPressure + */ + static getPressure(): PressureData; + + /** + * Perform a Spherical [Web Mercator + * projection](https://en.wikipedia.org/wiki/Web_Mercator_projection) of latitude + * and longitude into `x` and `y` coordinates, which are roughly equivalent to + * meters from `{lat:0,lon:0}`. + * This is the formula used for most online mapping and is a good way to compare + * GPS coordinates to work out the distance between them. + * + * @param {any} latlong - `{lat:..., lon:...}` + * @returns {any} {x:..., y:...} + * @url http://www.espruino.com/Reference#l_Bangle_project + */ + static project(latlong: { lat: number, lon: number }): { x: number, y: number }; + + /** + * Use the piezo speaker to Beep for a certain time period and frequency + * + * @param {number} [time] - [optional] Time in ms (default 200) + * @param {number} [freq] - [optional] Frequency in hz (default 4000) + * @returns {any} A promise, completed when beep is finished + * @url http://www.espruino.com/Reference#l_Bangle_beep + */ + static beep(time?: number, freq?: number): Promise; + + /** + * Use the vibration motor to buzz for a certain time period + * + * @param {number} [time] - [optional] Time in ms (default 200) + * @param {number} [strength] - [optional] Power of vibration from 0 to 1 (Default 1) + * @returns {any} A promise, completed when vibration is finished + * @url http://www.espruino.com/Reference#l_Bangle_buzz + */ + static buzz(time?: number, strength?: number): Promise; + + /** + * Turn Bangle.js off. It can only be woken by pressing BTN1. + * @url http://www.espruino.com/Reference#l_Bangle_off + */ + static off(): void; + + /** + * Turn Bangle.js (mostly) off, but keep the CPU in sleep mode until BTN1 is + * pressed to preserve the RTC (current time). + * @url http://www.espruino.com/Reference#l_Bangle_softOff + */ + static softOff(): void; + + /** + * * On platforms with an LCD of >=8bpp this is 222 x 104 x 2 bits + * * Otherwise it's 119 x 56 x 1 bits + * @returns {any} An image to be used with `g.drawImage` (as a String) + * @url http://www.espruino.com/Reference#l_Bangle_getLogo + */ + static getLogo(): string; + + /** + * Load all widgets from flash Storage. Call this once at the beginning of your + * application if you want any on-screen widgets to be loaded. + * They will be loaded into a global `WIDGETS` array, and can be rendered with + * `Bangle.drawWidgets`. + * @url http://www.espruino.com/Reference#l_Bangle_loadWidgets + */ + static loadWidgets(): void; + + /** + * Draw any onscreen widgets that were loaded with `Bangle.loadWidgets()`. + * Widgets should redraw themselves when something changes - you'll only need to + * call drawWidgets if you decide to clear the entire screen with `g.clear()`. + * @url http://www.espruino.com/Reference#l_Bangle_drawWidgets + */ + static drawWidgets(): void; + + /** + * @url http://www.espruino.com/Reference#l_Bangle_drawWidgets + */ + static drawWidgets(): void; + + /** + * Load the Bangle.js app launcher, which will allow the user to select an + * application to launch. + * @url http://www.espruino.com/Reference#l_Bangle_showLauncher + */ + static showLauncher(): void; + + /** + * Load the Bangle.js clock - this has the same effect as calling `Bangle.load()`. + * @url http://www.espruino.com/Reference#l_Bangle_showClock + */ + static showClock(): void; + + /** + * This behaves the same as the global `load()` function, but if fast + * loading is possible (`Bangle.setUI` was called with a `remove` handler) + * then instead of a complete reload, the `remove` handler will be + * called and the new app will be loaded straight after with `eval`. + * **This should only be used if the app being loaded also uses widgets** + * (eg it contains a `Bangle.loadWidgets()` call). + * `load()` is slower, but safer. As such, care should be taken + * when using `Bangle.load()` with `Bangle.setUI({..., remove:...})` + * as if your remove handler doesn't completely clean up after your app, + * memory leaks or other issues could occur - see `Bangle.setUI` for more + * information. + * + * @param {any} [file] - [optional] A string containing the file name for the app to be loaded + * @url http://www.espruino.com/Reference#l_Bangle_load + */ + static load(file: string): void; + static load(): void; + + /** + * This puts Bangle.js into the specified UI input mode, and calls the callback + * provided when there is user input. + * Currently supported interface types are: + * * 'updown' - UI input with upwards motion `cb(-1)`, downwards motion `cb(1)`, + * and select `cb()` + * * Bangle.js 1 uses BTN1/3 for up/down and BTN2 for select + * * Bangle.js 2 uses touchscreen swipe up/down and tap + * * 'leftright' - UI input with left motion `cb(-1)`, right motion `cb(1)`, and + * select `cb()` + * * Bangle.js 1 uses BTN1/3 for left/right and BTN2 for select + * * Bangle.js 2 uses touchscreen swipe left/right and tap/BTN1 for select + * * 'clock' - called for clocks. Sets `Bangle.CLOCK=1` and allows a button to + * start the launcher + * * Bangle.js 1 BTN2 starts the launcher + * * Bangle.js 2 BTN1 starts the launcher + * * 'clockupdown' - called for clocks. Sets `Bangle.CLOCK=1`, allows a button to + * start the launcher, but also provides up/down functionality + * * Bangle.js 1 BTN2 starts the launcher, BTN1/BTN3 call `cb(-1)` and `cb(1)` + * * Bangle.js 2 BTN1 starts the launcher, touchscreen tap in top/bottom right + * hand side calls `cb(-1)` and `cb(1)` + * * `{mode:"custom", ...}` allows you to specify custom handlers for different + * interactions. See below. + * * `undefined` removes all user interaction code + * While you could use setWatch/etc manually, the benefit here is that you don't + * end up with multiple `setWatch` instances, and the actual input method (touch, + * or buttons) is implemented dependent on the watch (Bangle.js 1 or 2) + * **Note:** You can override this function in boot code to change the interaction + * mode with the watch. For instance you could make all clocks start the launcher + * with a swipe by using: + * ``` + * (function() { + * var sui = Bangle.setUI; + * Bangle.setUI = function(mode, cb) { + * if (mode!="clock") return sui(mode,cb); + * sui(); // clear + * Bangle.CLOCK=1; + * Bangle.swipeHandler = Bangle.showLauncher; + * Bangle.on("swipe", Bangle.swipeHandler); + * }; + * })(); + * ``` + * The first argument can also be an object, in which case more options can be + * specified: + * ``` + * Bangle.setUI({ + * mode : "custom", + * back : function() {}, // optional - add a 'back' icon in top-left widget area and call this function when it is pressed , also call it when the hardware button is clicked (does not override btn if defined) + * remove : function() {}, // optional - add a handler for when the UI should be removed (eg stop any intervals/timers here) + * touch : function(n,e) {}, // optional - handler for 'touch' events + * swipe : function(dir) {}, // optional - handler for 'swipe' events + * drag : function(e) {}, // optional - handler for 'drag' events (Bangle.js 2 only) + * btn : function(n) {}, // optional - handler for 'button' events (n==1 on Bangle.js 2, n==1/2/3 depending on button for Bangle.js 1) + * clock : 0 // optional - if set the behavior of 'clock' mode is added (does not override btn if defined) + * }); + * ``` + * If `remove` is specified, `Bangle.showLauncher`, `Bangle.showClock`, `Bangle.load` and some apps + * may choose to just call the `remove` function and then load a new app without resetting Bangle.js. + * As a result, **if you specify 'remove' you should make sure you test that after calling `Bangle.setUI()` + * without arguments your app is completely unloaded**, otherwise you may end up with memory leaks or + * other issues when switching apps. + * + * @param {any} type - The type of UI input: 'updown', 'leftright', 'clock', 'clockupdown' or undefined to cancel. Can also be an object (see below) + * @param {any} callback - A function with one argument which is the direction + * @url http://www.espruino.com/Reference#l_Bangle_setUI + */ + static setUI(type?: "updown" | "leftright" | "clock" | "clockupdown" | { mode: "custom"; back?: () => void; touch?: TouchCallback; swipe?: SwipeCallback; drag?: DragCallback; btn?: (n: number) => void, remove?: () => void, clock?: boolean }, callback?: (direction?: -1 | 1) => void): void; + + /** + * @url http://www.espruino.com/Reference#l_Bangle_setUI + */ + static setUI(): void; + + /** + * Erase all storage and reload it with the default contents. + * This is only available on Bangle.js 2.0. On Bangle.js 1.0 you need to use + * `Install Default Apps` under the `More...` tab of http://banglejs.com/apps + * @url http://www.espruino.com/Reference#l_Bangle_factoryReset + */ + static factoryReset(): void; + + /** + * Returns the rectangle on the screen that is currently reserved for the app. + * @returns {any} An object of the form `{x,y,w,h,x2,y2}` + * @url http://www.espruino.com/Reference#l_Bangle_appRect + */ + static appRect: { x: number, y: number, w: number, h: number, x2: number, y2: number }; + + static CLOCK: boolean; + static strokes: undefined | { [key: string]: Unistroke }; } /** - * Class containing utility functions for the Seeed WIO LTE board - * @url http://www.espruino.com/Reference#WioLTE + * Class containing utility functions for accessing IO on the hexagonal badge + * @url http://www.espruino.com/Reference#Badge */ -declare class WioLTE { +declare class Badge { /** - * Set the WIO's LED + * Capacitive sense - the higher the capacitance, the higher the number returned. + * Supply a corner number between 1 and 6, and an integer value will be returned + * that is proportional to the capacitance * - * @param {number} red - 0-255, red LED intensity - * @param {number} green - 0-255, green LED intensity - * @param {number} blue - 0-255, blue LED intensity - * @url http://www.espruino.com/Reference#l_WioLTE_LED + * @param {number} corner - The corner to use + * @returns {number} Capacitive sense counter + * @url http://www.espruino.com/Reference#l_Badge_capSense */ - static LED(red: number, green: number, blue: number): void; + static capSense(corner: number): number; /** - * Set the power of Grove connectors, except for `D38` and `D39` which are always - * on. - * - * @param {boolean} onoff - Whether to turn the Grove connectors power on or off (D38/D39 are always powered) - * @url http://www.espruino.com/Reference#l_WioLTE_setGrovePower - */ - static setGrovePower(onoff: boolean): void; - - /** - * Turn power to the WIO's LED on or off. - * Turning the LED on won't immediately display a color - that must be done with - * `WioLTE.LED(r,g,b)` - * - * @param {boolean} onoff - true = on, false = off - * @url http://www.espruino.com/Reference#l_WioLTE_setLEDPower - */ - static setLEDPower(onoff: boolean): void; - - /** - * @returns {any} - * @url http://www.espruino.com/Reference#l_WioLTE_D38 - */ - static D38: any; - - /** - * @returns {any} - * @url http://www.espruino.com/Reference#l_WioLTE_D20 - */ - static D20: any; - - /** - * @returns {any} - * @url http://www.espruino.com/Reference#l_WioLTE_A6 - */ - static A6: any; - - /** - * @returns {any} - * @url http://www.espruino.com/Reference#l_WioLTE_I2C - */ - static I2C: any; - - /** - * @returns {any} - * @url http://www.espruino.com/Reference#l_WioLTE_UART - */ - static UART: any; - - /** - * @returns {any} - * @url http://www.espruino.com/Reference#l_WioLTE_A4 - */ - static A4: any; - - -} - -/** - * Class containing utility functions for - * [Pixl.js](http://www.espruino.com/Pixl.js) - * @url http://www.espruino.com/Reference#Pixl - */ -declare class Pixl { - /** - * DEPRECATED - Please use `E.getBattery()` instead. * Return an approximate battery percentage remaining based on a normal CR2032 * battery (2.8 - 2.2v) * @returns {number} A percentage between 0 and 100 - * @url http://www.espruino.com/Reference#l_Pixl_getBatteryPercentage + * @url http://www.espruino.com/Reference#l_Badge_getBatteryPercentage */ static getBatteryPercentage(): number; @@ -1121,151 +4327,458 @@ declare class Pixl { * Set the LCD's contrast * * @param {number} c - Contrast between 0 and 1 - * @url http://www.espruino.com/Reference#l_Pixl_setContrast + * @url http://www.espruino.com/Reference#l_Badge_setContrast */ static setContrast(c: number): void; - /** - * This function can be used to turn Pixl.js's LCD off or on. - * * With the LCD off, Pixl.js draws around 0.1mA - * * With the LCD on, Pixl.js draws around 0.25mA - * - * @param {boolean} isOn - True if the LCD should be on, false if not - * @url http://www.espruino.com/Reference#l_Pixl_setLCDPower - */ - static setLCDPower(isOn: boolean): void; - - /** - * Writes a command directly to the ST7567 LCD controller - * - * @param {number} c - * @url http://www.espruino.com/Reference#l_Pixl_lcdw - */ - static lcdw(c: number): void; - - /** - * Display a menu on Pixl.js's screen, and set up the buttons to navigate through - * it. - * DEPRECATED: Use `E.showMenu` - * - * @param {any} menu - An object containing name->function mappings to to be used in a menu - * @returns {any} A menu object with `draw`, `move` and `select` functions - * @url http://www.espruino.com/Reference#l_Pixl_menu - */ - static menu(menu: Menu): MenuInstance; - } /** - * This class exists in order to interface Espruino with fast-moving trigger - * wheels. Trigger wheels are physical discs with evenly spaced teeth cut into - * them, and often with one or two teeth next to each other missing. A sensor sends - * a signal whenever a tooth passed by, and this allows a device to measure not - * only RPM, but absolute position. - * This class is currently in testing - it is NOT AVAILABLE on normal boards. - * @url http://www.espruino.com/Reference#Trig + * A Web Bluetooth-style device - you can request one using + * `NRF.requestDevice(address)` + * For example: + * ``` + * var gatt; + * NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) { + * console.log("found device"); + * return device.gatt.connect(); + * }).then(function(g) { + * gatt = g; + * console.log("connected"); + * return gatt.startBonding(); + * }).then(function() { + * console.log("bonded", gatt.getSecurityStatus()); + * gatt.disconnect(); + * }).catch(function(e) { + * console.log("ERROR",e); + * }); + * ``` + * @url http://www.espruino.com/Reference#BluetoothDevice */ -declare class Trig { +declare class BluetoothDevice { /** - * Get the position of the trigger wheel at the given time (from getTime) + * Called when the device gets disconnected. + * To connect and then print `Disconnected` when the device is disconnected, just + * do the following: + * ``` + * var gatt; + * NRF.connect("aa:bb:cc:dd:ee:ff").then(function(gatt) { + * gatt.device.on('gattserverdisconnected', function(reason) { + * console.log("Disconnected ",reason); + * }); + * }); + * ``` + * Or: + * ``` + * var gatt; + * NRF.requestDevice(...).then(function(device) { + * device.on('gattserverdisconnected', function(reason) { + * console.log("Disconnected ",reason); + * }); + * }); + * ``` + * @param {string} event - The event to listen to. + * @param {(reason: number) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `reason` The reason code reported back by the BLE stack - see Nordic's `ble_hci.h` file for more information + * @url http://www.espruino.com/Reference#l_BluetoothDevice_gattserverdisconnected + */ + static on(event: "gattserverdisconnected", callback: (reason: number) => void): void; + + /** + * Called when the device pairs and sends a passkey that Espruino should display. + * For this to be used, you'll have to specify that there's a display using + * `NRF.setSecurity` + * **This is not part of the Web Bluetooth Specification.** It has been added + * specifically for Espruino. + * @param {string} event - The event to listen to. + * @param {(passkey: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `passkey` A 6 character numeric String to be displayed + * @url http://www.espruino.com/Reference#l_BluetoothDevice_passkey + */ + static on(event: "passkey", callback: (passkey: any) => void): void; + + /** + * Called when the device pairs, displays a passkey, and wants Espruino to tell it + * what the passkey was. + * Respond with `BluetoothDevice.sendPasskey()` with a 6 character string + * containing only `0..9`. + * For this to be used, you'll have to specify that there's a keyboard using + * `NRF.setSecurity` + * **This is not part of the Web Bluetooth Specification.** It has been added + * specifically for Espruino. + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_BluetoothDevice_passkeyRequest + */ + static on(event: "passkeyRequest", callback: () => void): void; + + /** + * @returns {any} A `BluetoothRemoteGATTServer` for this device + * @url http://www.espruino.com/Reference#l_BluetoothDevice_gatt + */ + gatt: any; + + /** + * @returns {boolean} The last received RSSI (signal strength) for this device + * @url http://www.espruino.com/Reference#l_BluetoothDevice_rssi + */ + rssi: boolean; + + /** + * To be used as a response when the event `BluetoothDevice.sendPasskey` has been + * received. + * **This is not part of the Web Bluetooth Specification.** It has been added + * specifically for Espruino. * - * @param {number} time - The time at which to find the position - * @returns {number} The position of the trigger wheel in degrees - as a floating point number - * @url http://www.espruino.com/Reference#l_Trig_getPosAtTime + * @param {any} passkey - A 6 character numeric String to be returned to the device + * @url http://www.espruino.com/Reference#l_BluetoothDevice_sendPasskey */ - static getPosAtTime(time: number): number; - - /** - * Initialise the trigger class - * - * @param {Pin} pin - The pin to use for triggering - * @param {any} options - Additional options as an object. defaults are: ```{teethTotal:60,teethMissing:2,minRPM:30,keyPosition:0}``` - * @url http://www.espruino.com/Reference#l_Trig_setup - */ - static setup(pin: Pin, options: any): void; - - /** - * Set a trigger for a certain point in the cycle - * - * @param {number} num - The trigger number (0..7) - * @param {number} pos - The position (in degrees) to fire the trigger at - * @param {any} pins - An array of pins to pulse (max 4) - * @param {number} pulseLength - The time (in msec) to pulse for - * @url http://www.espruino.com/Reference#l_Trig_setTrigger - */ - static setTrigger(num: number, pos: number, pins: any, pulseLength: number): void; - - /** - * Disable a trigger - * - * @param {number} num - The trigger number (0..7) - * @url http://www.espruino.com/Reference#l_Trig_killTrigger - */ - static killTrigger(num: number): void; - - /** - * Get the current state of a trigger - * - * @param {number} num - The trigger number (0..7) - * @returns {any} A structure containing all information about the trigger - * @url http://www.espruino.com/Reference#l_Trig_getTrigger - */ - static getTrigger(num: number): any; - - /** - * Get the RPM of the trigger wheel - * @returns {number} The current RPM of the trigger wheel - * @url http://www.espruino.com/Reference#l_Trig_getRPM - */ - static getRPM(): number; - - /** - * Get the current error flags from the trigger wheel - and zero them - * @returns {number} The error flags - * @url http://www.espruino.com/Reference#l_Trig_getErrors - */ - static getErrors(): number; - - /** - * Get the current error flags from the trigger wheel - and zero them - * @returns {any} An array of error strings - * @url http://www.espruino.com/Reference#l_Trig_getErrorArray - */ - static getErrorArray(): any; - - + sendPasskey(passkey: any): void; } /** - * Class containing AES encryption/decryption - * **Note:** This library is currently only included in builds for boards where - * there is space. For other boards there is `crypto.js` which implements SHA1 in - * JS. - * @url http://www.espruino.com/Reference#AES + * Web Bluetooth-style GATT server - get this using `NRF.connect(address)` or + * `NRF.requestDevice(options)` and `response.gatt.connect` + * https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver + * @url http://www.espruino.com/Reference#BluetoothRemoteGATTServer */ -declare class AES { - /** - * - * @param {any} passphrase - Message to encrypt - * @param {any} key - Key to encrypt message - must be an ArrayBuffer of 128, 192, or 256 BITS - * @param {any} options - An optional object, may specify `{ iv : new Uint8Array(16), mode : 'CBC|CFB|CTR|OFB|ECB' }` - * @returns {any} Returns an ArrayBuffer - * @url http://www.espruino.com/Reference#l_AES_encrypt - */ - static encrypt(passphrase: any, key: any, options: any): ArrayBuffer; +declare class BluetoothRemoteGATTServer { + /** + * Connect to a BLE device - returns a promise, the argument of which is the + * `BluetoothRemoteGATTServer` connection. + * See [`NRF.requestDevice`](/Reference#l_NRF_requestDevice) for usage examples. + * `options` is an optional object containing: + * ``` + * { + * minInterval // min connection interval in milliseconds, 7.5 ms to 4 s + * maxInterval // max connection interval in milliseconds, 7.5 ms to 4 s + * } + * ``` + * By default the interval is 20-200ms (or 500-1000ms if + * `NRF.setLowPowerConnection(true)` was called. During connection Espruino + * negotiates with the other device to find a common interval that can be used. + * For instance calling: + * ``` + * NRF.requestDevice({ filters: [{ namePrefix: 'Pixl.js' }] }).then(function(device) { + * return device.gatt.connect({minInterval:7.5, maxInterval:7.5}); + * }).then(function(g) { + * ``` + * will force the connection to use the fastest connection interval possible (as + * long as the device at the other end supports it). + * **Note:** The Web Bluetooth spec states that if a device hasn't advertised its + * name, when connected to a device the central (in this case Espruino) should + * automatically retrieve the name from the corresponding characteristic (`0x2a00` + * on service `0x1800`). Espruino does not automatically do this. * - * @param {any} passphrase - Message to decrypt - * @param {any} key - Key to encrypt message - must be an ArrayBuffer of 128, 192, or 256 BITS - * @param {any} options - An optional object, may specify `{ iv : new Uint8Array(16), mode : 'CBC|CFB|CTR|OFB|ECB' }` - * @returns {any} Returns an ArrayBuffer - * @url http://www.espruino.com/Reference#l_AES_decrypt + * @param {any} [options] - [optional] (Espruino-specific) An object of connection options (see below) + * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_connect */ - static decrypt(passphrase: any, key: any, options: any): ArrayBuffer; + connect(options?: any): Promise; + + /** + * @returns {boolean} Whether the device is connected or not + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_connected + */ + connected: boolean; + + /** + * @returns {number} The handle to this device (if it is currently connected) - the handle is an internal value used by the Bluetooth Stack + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_handle + */ + handle: number; + + /** + * Disconnect from a previously connected BLE device connected with + * `BluetoothRemoteGATTServer.connect` - this does not disconnect from something + * that has connected to the Espruino. + * **Note:** While `.disconnect` is standard Web Bluetooth, in the spec it returns + * undefined not a `Promise` for implementation reasons. In Espruino we return a + * `Promise` to make it easier to detect when Espruino is free to connect to + * something else. + * @returns {any} A `Promise` that is resolved (or rejected) when the disconnection is complete (non-standard) + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_disconnect + */ + disconnect(): Promise; + + /** + * Start negotiating bonding (secure communications) with the connected device, and + * return a Promise that is completed on success or failure. + * ``` + * var gatt; + * NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) { + * console.log("found device"); + * return device.gatt.connect(); + * }).then(function(g) { + * gatt = g; + * console.log("connected"); + * return gatt.startBonding(); + * }).then(function() { + * console.log("bonded", gatt.getSecurityStatus()); + * gatt.disconnect(); + * }).catch(function(e) { + * console.log("ERROR",e); + * }); + * ``` + * **This is not part of the Web Bluetooth Specification.** It has been added + * specifically for Espruino. + * + * @param {boolean} forceRePair - If the device is already bonded, re-pair it + * @returns {any} A `Promise` that is resolved (or rejected) when the bonding is complete + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_startBonding + */ + startBonding(forceRePair: boolean): Promise; + + /** + * Return an object with information about the security state of the current + * connection: + * ``` + * { + * connected // The connection is active (not disconnected). + * encrypted // Communication on this link is encrypted. + * mitm_protected // The encrypted communication is also protected against man-in-the-middle attacks. + * bonded // The peer is bonded with us + * } + * ``` + * See `BluetoothRemoteGATTServer.startBonding` for information about negotiating a + * secure connection. + * **This is not part of the Web Bluetooth Specification.** It has been added + * specifically for Puck.js. + * @returns {any} An object + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_getSecurityStatus + */ + getSecurityStatus(): any; + + /** + * See `NRF.connect` for usage examples. + * + * @param {any} service - The service UUID + * @returns {any} A `Promise` that is resolved (or rejected) when the primary service is found (the argument contains a `BluetoothRemoteGATTService`) + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_getPrimaryService + */ + getPrimaryService(service: any): Promise; + + /** + * @returns {any} A `Promise` that is resolved (or rejected) when the primary services are found (the argument contains an array of `BluetoothRemoteGATTService`) + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_getPrimaryServices + */ + getPrimaryServices(): Promise; + + /** + * Start/stop listening for RSSI values on the active GATT connection + * ``` + * // Start listening for RSSI value updates + * gattServer.setRSSIHandler(function(rssi) { + * console.log(rssi); // prints -85 (or similar) + * }); + * // Stop listening + * gattServer.setRSSIHandler(); + * ``` + * RSSI is the 'Received Signal Strength Indication' in dBm + * + * @param {any} callback - The callback to call with the RSSI value, or undefined to stop + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_setRSSIHandler + */ + setRSSIHandler(callback: any): void; +} + +/** + * Web Bluetooth-style GATT service - get this using + * `BluetoothRemoteGATTServer.getPrimaryService(s)` + * https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice + * @url http://www.espruino.com/Reference#BluetoothRemoteGATTService + */ +declare class BluetoothRemoteGATTService { + /** + * @returns {any} The `BluetoothDevice` this Service came from + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTService_device + */ + device: any; + + /** + * See `NRF.connect` for usage examples. + * + * @param {any} characteristic - The characteristic UUID + * @returns {any} A `Promise` that is resolved (or rejected) when the characteristic is found (the argument contains a `BluetoothRemoteGATTCharacteristic`) + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTService_getCharacteristic + */ + getCharacteristic(characteristic: any): Promise; + + /** + * @returns {any} A `Promise` that is resolved (or rejected) when the characteristic is found (the argument contains an array of `BluetoothRemoteGATTCharacteristic`) + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTService_getCharacteristics + */ + getCharacteristics(): Promise; +} + +/** + * Web Bluetooth-style GATT characteristic - get this using + * `BluetoothRemoteGATTService.getCharacteristic(s)` + * https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattcharacteristic + * @url http://www.espruino.com/Reference#BluetoothRemoteGATTCharacteristic + */ +declare class BluetoothRemoteGATTCharacteristic { + /** + * Called when a characteristic's value changes, *after* + * `BluetoothRemoteGATTCharacteristic.startNotifications` has been called. + * ``` + * ... + * return service.getCharacteristic("characteristic_uuid"); + * }).then(function(c) { + * c.on('characteristicvaluechanged', function(event) { + * console.log("-> "+event.target.value); + * }); + * return c.startNotifications(); + * }).then(... + * ``` + * The first argument is of the form `{target : + * BluetoothRemoteGATTCharacteristic}`, and + * `BluetoothRemoteGATTCharacteristic.value` will then contain the new value (as a + * DataView). + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_characteristicvaluechanged + */ + static on(event: "characteristicvaluechanged", callback: () => void): void; + + /** + * @returns {any} The `BluetoothRemoteGATTService` this Service came from + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_service + */ + service: any; + + /** + * Write a characteristic's value + * ``` + * var device; + * NRF.connect(device_address).then(function(d) { + * device = d; + * return d.getPrimaryService("service_uuid"); + * }).then(function(s) { + * console.log("Service ",s); + * return s.getCharacteristic("characteristic_uuid"); + * }).then(function(c) { + * return c.writeValue("Hello"); + * }).then(function(d) { + * device.disconnect(); + * }).catch(function() { + * console.log("Something's broken."); + * }); + * ``` + * + * @param {any} data - The data to write + * @returns {any} A `Promise` that is resolved (or rejected) when the characteristic is written + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_writeValue + */ + writeValue(data: any): Promise; + + /** + * Read a characteristic's value, return a promise containing a `DataView` + * ``` + * var device; + * NRF.connect(device_address).then(function(d) { + * device = d; + * return d.getPrimaryService("service_uuid"); + * }).then(function(s) { + * console.log("Service ",s); + * return s.getCharacteristic("characteristic_uuid"); + * }).then(function(c) { + * return c.readValue(); + * }).then(function(d) { + * console.log("Got:", JSON.stringify(d.buffer)); + * device.disconnect(); + * }).catch(function() { + * console.log("Something's broken."); + * }); + * ``` + * @returns {any} A `Promise` that is resolved (or rejected) with a `DataView` when the characteristic is read + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_readValue + */ + readValue(): Promise; + + /** + * Starts notifications - whenever this characteristic's value changes, a + * `characteristicvaluechanged` event is fired and `characteristic.value` will then + * contain the new value as a `DataView`. + * ``` + * var device; + * NRF.connect(device_address).then(function(d) { + * device = d; + * return d.getPrimaryService("service_uuid"); + * }).then(function(s) { + * console.log("Service ",s); + * return s.getCharacteristic("characteristic_uuid"); + * }).then(function(c) { + * c.on('characteristicvaluechanged', function(event) { + * console.log("-> ",event.target.value); // this is a DataView + * }); + * return c.startNotifications(); + * }).then(function(d) { + * console.log("Waiting for notifications"); + * }).catch(function() { + * console.log("Something's broken."); + * }); + * ``` + * For example, to listen to the output of another Puck.js's Nordic Serial port + * service, you can use: + * ``` + * var gatt; + * NRF.connect("pu:ck:js:ad:dr:es random").then(function(g) { + * gatt = g; + * return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); + * }).then(function(service) { + * return service.getCharacteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); + * }).then(function(characteristic) { + * characteristic.on('characteristicvaluechanged', function(event) { + * console.log("RX: "+JSON.stringify(event.target.value.buffer)); + * }); + * return characteristic.startNotifications(); + * }).then(function() { + * console.log("Done!"); + * }); + * ``` + * @returns {any} A `Promise` that is resolved (or rejected) with data when notifications have been added + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_startNotifications + */ + startNotifications(): Promise; + + /** + * Stop notifications (that were requested with + * `BluetoothRemoteGATTCharacteristic.startNotifications`) + * @returns {any} A `Promise` that is resolved (or rejected) with data when notifications have been removed + * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_stopNotifications + */ + stopNotifications(): Promise; +} + +/** + * Class containing an instance of TFMicroInterpreter + * @url http://www.espruino.com/Reference#TFMicroInterpreter + */ +declare class TFMicroInterpreter { + + + /** + * @returns {any} An arraybuffer referencing the input data + * @url http://www.espruino.com/Reference#l_TFMicroInterpreter_getInput + */ + getInput(): ArrayBufferView; + + /** + * @returns {any} An arraybuffer referencing the output data + * @url http://www.espruino.com/Reference#l_TFMicroInterpreter_getOutput + */ + getOutput(): ArrayBufferView; + + /** + * @url http://www.espruino.com/Reference#l_TFMicroInterpreter_invoke + */ + invoke(): void; } /** @@ -1273,9 +4786,9 @@ declare class AES { * Use Graphics.createXXX to create a graphics object that renders in the way you * want. See [the Graphics page](https://www.espruino.com/Graphics) for more * information. - * **Note:** On boards that contain an LCD, there is a built-in 'LCD' object of - * type Graphics. For instance to draw a line you'd type: - * ```LCD.drawLine(0,0,100,100)``` + * **Note:** On boards that contain an LCD, there is a built-in `g` object of + * type `Graphics`. For instance to draw a line you'd type: + * ```g.drawLine(0,0,100,100)``` * @url http://www.espruino.com/Reference#Graphics */ declare class Graphics { @@ -1358,20 +4871,20 @@ declare class Graphics { /** * Set the current font * - * @param {number} scale - (optional) If >1 the font will be scaled up by that amount + * @param {number} [scale] - [optional] If >1 the font will be scaled up by that amount * @returns {any} The instance of Graphics this was called on, to allow call chaining - * @url http://www.espruino.com/Reference#l_Graphics_setFont6x15 + * @url http://www.espruino.com/Reference#l_Graphics_setFont12x20 */ - setFont6x15(scale: number): Graphics; + setFont12x20(scale?: number): Graphics; /** * Set the current font * - * @param {number} scale - (optional) If >1 the font will be scaled up by that amount + * @param {number} [scale] - [optional] If >1 the font will be scaled up by that amount * @returns {any} The instance of Graphics this was called on, to allow call chaining - * @url http://www.espruino.com/Reference#l_Graphics_setFont12x20 + * @url http://www.espruino.com/Reference#l_Graphics_setFont6x15 */ - setFont12x20(scale: number): Graphics; + setFont6x15(scale?: number): Graphics; /** * On instances of graphics that drive a display with an offscreen buffer, calling @@ -1635,8 +5148,8 @@ declare class Graphics { * @returns {any} The instance of Graphics this was called on, to allow call chaining * @url http://www.espruino.com/Reference#l_Graphics_setColor */ - setColor(r: number, g: number, b: number): number; - setColor(col: ColorResolvable): number; + setColor(r: number, g: number, b: number): Graphics; + setColor(col: ColorResolvable): Graphics; /** * Set the background color to use for subsequent drawing operations. @@ -1650,8 +5163,8 @@ declare class Graphics { * @returns {any} The instance of Graphics this was called on, to allow call chaining * @url http://www.espruino.com/Reference#l_Graphics_setBgColor */ - setBgColor(r: number, g: number, b: number): number; - setBgColor(col: ColorResolvable): number; + setBgColor(r: number, g: number, b: number): Graphics; + setBgColor(col: ColorResolvable): Graphics; /** * Get the color to use for subsequent drawing operations @@ -1844,6 +5357,23 @@ declare class Graphics { */ drawString(str: string, x: number, y: number, solid?: boolean): Graphics; + /** + * Return the current string as a series of polygons (using the current vector font). `options` is as follows: + * * `x` - X offset of font (default 0) + * * `y` - Y offset of font (default 0) + * * `w` - Width of font (default 256) - the actual width will likely be less than this as most characters are non-square + * * `h` - Height of font (default 256) - the actual height will likely be less than this as most characters don't fully fill the font box + * ``` + * g.getVectorFontPolys("Hi", {x:-80,y:-128}); + * ``` + * + * @param {any} str - The string + * @param {any} [options] - [optional] `{x,y,w,h}` (see below) + * @returns {any} An array of Uint8Arrays for vector font polygons + * @url http://www.espruino.com/Reference#l_Graphics_getVectorFontPolys + */ + getVectorFontPolys(str: any, options?: any): any[]; + /** * Draw a line between x1,y1 and x2,y2 in the current foreground color * @@ -2239,3827 +5769,455 @@ declare class Graphics { } /** - * This class helps to convert URLs into Objects of information ready for - * http.request/get - * @url http://www.espruino.com/Reference#url + * Class containing utility functions for the Seeed WIO LTE board + * @url http://www.espruino.com/Reference#WioLTE */ -declare class url { +declare class WioLTE { /** - * A utility function to split a URL into parts - * This is useful in web servers for instance when handling a request. - * For instance `url.parse("/a?b=c&d=e",true)` returns - * `{"method":"GET","host":"","path":"/a?b=c&d=e","pathname":"/a","search":"?b=c&d=e","port":80,"query":{"b":"c","d":"e"}}` + * Set the WIO's LED * - * @param {any} urlStr - A URL to be parsed - * @param {boolean} parseQuery - Whether to parse the query string into an object not (default = false) - * @returns {any} An object containing options for ```http.request``` or ```http.get```. Contains `method`, `host`, `path`, `pathname`, `search`, `port` and `query` - * @url http://www.espruino.com/Reference#l_url_parse + * @param {number} red - 0-255, red LED intensity + * @param {number} green - 0-255, green LED intensity + * @param {number} blue - 0-255, blue LED intensity + * @url http://www.espruino.com/Reference#l_WioLTE_LED */ - static parse(urlStr: any, parseQuery: boolean): any; - - -} - -/** - * The socket server created by `require('net').createServer` - * @url http://www.espruino.com/Reference#Server - */ -declare class Server { - + static LED(red: number, green: number, blue: number): void; /** - * Start listening for new connections on the given port + * Set the power of Grove connectors, except for `D38` and `D39` which are always + * on. * - * @param {number} port - The port to listen on - * @returns {any} The HTTP server instance that 'listen' was called on - * @url http://www.espruino.com/Reference#l_Server_listen + * @param {boolean} onoff - Whether to turn the Grove connectors power on or off (D38/D39 are always powered) + * @url http://www.espruino.com/Reference#l_WioLTE_setGrovePower */ - listen(port: number): any; + static setGrovePower(onoff: boolean): void; /** - * Stop listening for new connections - * @url http://www.espruino.com/Reference#l_Server_close - */ - close(): void; -} - -/** - * An actual socket connection - allowing transmit/receive of TCP data - * @url http://www.espruino.com/Reference#Socket - */ -declare class Socket { - /** - * The 'data' event is called when data is received. If a handler is defined with - * `X.on('data', function(data) { ... })` then it will be called, otherwise data - * will be stored in an internal buffer, where it can be retrieved with `X.read()` - * @param {string} event - The event to listen to. - * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `data` A string containing one or more characters of received data - * @url http://www.espruino.com/Reference#l_Socket_data - */ - static on(event: "data", callback: (data: any) => void): void; - - /** - * Called when the connection closes. - * @param {string} event - The event to listen to. - * @param {(had_error: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `had_error` A boolean indicating whether the connection had an error (use an error event handler to get error details). - * @url http://www.espruino.com/Reference#l_Socket_close - */ - static on(event: "close", callback: (had_error: any) => void): void; - - /** - * There was an error on this socket and it is closing (or wasn't opened in the - * first place). If a "connected" event was issued on this socket then the error - * event is always followed by a close event. The error codes are: - * * -1: socket closed (this is not really an error and will not cause an error - * callback) - * * -2: out of memory (typically while allocating a buffer to hold data) - * * -3: timeout - * * -4: no route - * * -5: busy - * * -6: not found (DNS resolution) - * * -7: max sockets (... exceeded) - * * -8: unsent data (some data could not be sent) - * * -9: connection reset (or refused) - * * -10: unknown error - * * -11: no connection - * * -12: bad argument - * * -13: SSL handshake failed - * * -14: invalid SSL data - * @param {string} event - The event to listen to. - * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `details` An error object with an error code (a negative integer) and a message. - * @url http://www.espruino.com/Reference#l_Socket_error - */ - static on(event: "error", callback: (details: any) => void): void; - - /** - * An event that is fired when the buffer is empty and it can accept more data to - * send. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_Socket_drain - */ - static on(event: "drain", callback: () => void): void; - - /** - * Return how many bytes are available to read. If there is already a listener for - * data, this will always return 0. - * @returns {number} How many bytes are available - * @url http://www.espruino.com/Reference#l_Socket_available - */ - available(): number; - - /** - * Return a string containing characters that have been received + * Turn power to the WIO's LED on or off. + * Turning the LED on won't immediately display a color - that must be done with + * `WioLTE.LED(r,g,b)` * - * @param {number} chars - The number of characters to read, or undefined/0 for all available - * @returns {any} A string containing the required bytes. - * @url http://www.espruino.com/Reference#l_Socket_read + * @param {boolean} onoff - true = on, false = off + * @url http://www.espruino.com/Reference#l_WioLTE_setLEDPower */ - read(chars: number): any; + static setLEDPower(onoff: boolean): void; /** - * Pipe this to a stream (an object with a 'write' method) - * - * @param {any} destination - The destination file/stream that will receive content from the source. - * @param {any} options - * An optional object `{ chunkSize : int=32, end : bool=true, complete : function }` - * chunkSize : The amount of data to pipe from source to destination at a time - * complete : a function to call when the pipe activity is complete - * end : call the 'end' function on the destination when the source is finished - * @url http://www.espruino.com/Reference#l_Socket_pipe - */ - pipe(destination: any, options: any): void; - - /** - * This function writes the `data` argument as a string. Data that is passed in - * (including arrays) will be converted to a string with the normal JavaScript - * `toString` method. - * If you wish to send binary data then you need to convert that data directly to a - * String. This can be done with `String.fromCharCode`, however it's often easier - * and faster to use the Espruino-specific `E.toString`, which will read its - * arguments as an array of bytes and convert that to a String: - * ``` - * socket.write(E.toString([0,1,2,3,4,5])); - * ``` - * If you need to send something other than bytes, you can use 'Typed Arrays', or - * even `DataView`: - * ``` - * var d = new DataView(new ArrayBuffer(8)); // 8 byte array buffer - * d.setFloat32(0, 765.3532564); // write float at bytes 0-3 - * d.setInt8(4, 42); // write int8 at byte 4 - * socket.write(E.toString(d.buffer)) - * ``` - * - * @param {any} data - A string containing data to send - * @returns {boolean} For node.js compatibility, returns the boolean false. When the send buffer is empty, a `drain` event will be sent - * @url http://www.espruino.com/Reference#l_Socket_write - */ - write(data: any): boolean; - - /** - * Close this socket - optional data to append as an argument. - * See `Socket.write` for more information about the data argument - * - * @param {any} data - A string containing data to send - * @url http://www.espruino.com/Reference#l_Socket_end - */ - end(data: any): void; -} - -/** - * An actual socket connection - allowing transmit/receive of TCP data - * @url http://www.espruino.com/Reference#dgramSocket - */ -declare class dgramSocket { - /** - * The 'message' event is called when a datagram message is received. If a handler - * is defined with `X.on('message', function(msg) { ... })` then it will be called` - * @param {string} event - The event to listen to. - * @param {(msg: any, rinfo: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `msg` A string containing the received message - * * `rinfo` Sender address,port containing information - * @url http://www.espruino.com/Reference#l_dgramSocket_message - */ - static on(event: "message", callback: (msg: any, rinfo: any) => void): void; - - /** - * Called when the connection closes. - * @param {string} event - The event to listen to. - * @param {(had_error: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `had_error` A boolean indicating whether the connection had an error (use an error event handler to get error details). - * @url http://www.espruino.com/Reference#l_dgramSocket_close - */ - static on(event: "close", callback: (had_error: any) => void): void; - - /** - * - * @param {any} buffer - A string containing message to send - * @param {any} offset - Offset in the passed string where the message starts [optional] - * @param {any} length - Number of bytes in the message [optional] - * @param {any} args - Destination port number, Destination IP address string - * @url http://www.espruino.com/Reference#l_dgramSocket_send - */ - send(buffer: any, offset: any, length: any, ...args: any[]): void; - - /** - * - * @param {number} port - The port to bind at - * @param {any} callback - A function(res) that will be called when the socket is bound. You can then call `res.on('message', function(message, info) { ... })` and `res.on('close', function() { ... })` to deal with the response. - * @returns {any} The dgramSocket instance that 'bind' was called on - * @url http://www.espruino.com/Reference#l_dgramSocket_bind - */ - bind(port: number, callback: any): any; - - /** - * Close the socket - * @url http://www.espruino.com/Reference#l_dgramSocket_close - */ - close(): void; - - /** - * - * @param {any} group - A string containing the group ip to join - * @param {any} ip - A string containing the ip to join with - * @url http://www.espruino.com/Reference#l_dgramSocket_addMembership - */ - addMembership(group: any, ip: any): void; -} - -/** - * An instantiation of a WiFi network adaptor - * @url http://www.espruino.com/Reference#WLAN - */ -declare class WLAN { - - - /** - * Connect to a wireless network - * - * @param {any} ap - Access point name - * @param {any} key - WPA2 key (or undefined for unsecured connection) - * @param {any} callback - Function to call back with connection status. It has one argument which is one of 'connect'/'disconnect'/'dhcp' - * @returns {boolean} True if connection succeeded, false if it didn't. - * @url http://www.espruino.com/Reference#l_WLAN_connect - */ - connect(ap: any, key: any, callback: any): boolean; - - /** - * Completely uninitialise and power down the CC3000. After this you'll have to use - * ```require("CC3000").connect()``` again. - * @url http://www.espruino.com/Reference#l_WLAN_disconnect - */ - disconnect(): void; - - /** - * Completely uninitialise and power down the CC3000, then reconnect to the old - * access point. - * @url http://www.espruino.com/Reference#l_WLAN_reconnect - */ - reconnect(): void; - - /** - * Get the current IP address * @returns {any} - * @url http://www.espruino.com/Reference#l_WLAN_getIP + * @url http://www.espruino.com/Reference#l_WioLTE_D38 */ - getIP(): any; + static D38: any; /** - * Set the current IP address for get an IP from DHCP (if no options object is - * specified). - * **Note:** Changes are written to non-volatile memory, but will only take effect - * after calling `wlan.reconnect()` - * - * @param {any} options - Object containing IP address options `{ ip : '1,2,3,4', subnet, gateway, dns }`, or do not supply an object in otder to force DHCP. - * @returns {boolean} True on success - * @url http://www.espruino.com/Reference#l_WLAN_setIP - */ - setIP(options: any): boolean; -} - -/** - * Class containing utility functions for the - * [ESP8266](http://www.espruino.com/EspruinoESP8266) - * @url http://www.espruino.com/Reference#ESP8266 - */ -declare class ESP8266 { - /** - * **DEPRECATED** - please use `Wifi.ping` instead. - * Perform a network ping request. The parameter can be either a String or a - * numeric IP address. - * - * @param {any} ipAddr - A string representation of an IP address. - * @param {any} pingCallback - Optional callback function. - * @url http://www.espruino.com/Reference#l_ESP8266_ping - */ - static ping(ipAddr: any, pingCallback: any): void; - - /** - * Perform a hardware reset/reboot of the esp8266. - * @url http://www.espruino.com/Reference#l_ESP8266_reboot - */ - static reboot(): void; - - /** - * At boot time the esp8266's firmware captures the cause of the reset/reboot. This - * function returns this information in an object with the following fields: - * * `reason`: "power on", "wdt reset", "exception", "soft wdt", "restart", "deep - * sleep", or "reset pin" - * * `exccause`: exception cause - * * `epc1`, `epc2`, `epc3`: instruction pointers - * * `excvaddr`: address being accessed - * * `depc`: (?) - * @returns {any} An object with the reset cause information - * @url http://www.espruino.com/Reference#l_ESP8266_getResetInfo - */ - static getResetInfo(): any; - - /** - * Enable or disable the logging of debug information. A value of `true` enables - * debug logging while a value of `false` disables debug logging. Debug output is - * sent to UART1 (gpio2). - * - * @param {boolean} enable - Enable or disable the debug logging. - * @url http://www.espruino.com/Reference#l_ESP8266_logDebug - */ - static logDebug(enable: boolean): void; - - /** - * Set the debug logging mode. It can be disabled (which frees ~1.2KB of heap), - * enabled in-memory only, or in-memory and output to a UART. - * - * @param {number} mode - Debug log mode: 0=off, 1=in-memory only, 2=in-mem and uart0, 3=in-mem and uart1. - * @url http://www.espruino.com/Reference#l_ESP8266_setLog - */ - static setLog(mode: number): void; - - /** - * Prints the contents of the debug log to the console. - * @url http://www.espruino.com/Reference#l_ESP8266_printLog - */ - static printLog(): void; - - /** - * Returns one line from the log or up to 128 characters. - * @url http://www.espruino.com/Reference#l_ESP8266_readLog - */ - static readLog(): void; - - /** - * Dumps info about all sockets to the log. This is for troubleshooting the socket - * implementation. - * @url http://www.espruino.com/Reference#l_ESP8266_dumpSocketInfo - */ - static dumpSocketInfo(): void; - - /** - * **Note:** This is deprecated. Use `E.setClock(80/160)` **Note:** Set the - * operating frequency of the ESP8266 processor. The default is 160Mhz. - * **Warning**: changing the cpu frequency affects the timing of some I/O - * operations, notably of software SPI and I2C, so things may be a bit slower at - * 80Mhz. - * - * @param {any} freq - Desired frequency - either 80 or 160. - * @url http://www.espruino.com/Reference#l_ESP8266_setCPUFreq - */ - static setCPUFreq(freq: any): void; - - /** - * Returns an object that contains details about the state of the ESP8266 with the - * following fields: - * * `sdkVersion` - Version of the SDK. - * * `cpuFrequency` - CPU operating frequency in Mhz. - * * `freeHeap` - Amount of free heap in bytes. - * * `maxCon` - Maximum number of concurrent connections. - * * `flashMap` - Configured flash size&map: '512KB:256/256' .. '4MB:512/512' - * * `flashKB` - Configured flash size in KB as integer - * * `flashChip` - Type of flash chip as string with manufacturer & chip, ex: '0xEF - * 0x4016` - * @returns {any} The state of the ESP8266 - * @url http://www.espruino.com/Reference#l_ESP8266_getState - */ - static getState(): any; - - /** - * **Note:** This is deprecated. Use `require("Flash").getFree()` - * @returns {any} Array of objects with `addr` and `length` properties describing the free flash areas available - * @url http://www.espruino.com/Reference#l_ESP8266_getFreeFlash - */ - static getFreeFlash(): any; - - /** - * - * @param {any} arrayOfData - Array of data to CRC - * @returns {any} 32-bit CRC - * @url http://www.espruino.com/Reference#l_ESP8266_crc32 - */ - static crc32(arrayOfData: any): any; - - /** - * **This function is deprecated.** Please use `require("neopixel").write(pin, - * data)` instead - * - * @param {Pin} pin - Pin for output signal. - * @param {any} arrayOfData - Array of LED data. - * @url http://www.espruino.com/Reference#l_ESP8266_neopixelWrite - */ - static neopixelWrite(pin: Pin, arrayOfData: any): void; - - /** - * Put the ESP8266 into 'deep sleep' for the given number of microseconds, reducing - * power consumption drastically. - * meaning of option values: - * 0 - the 108th Byte of init parameter decides whether RF calibration will be - * performed or not. - * 1 - run RF calibration after waking up. Power consumption is high. - * 2 - no RF calibration after waking up. Power consumption is low. - * 4 - no RF after waking up. Power consumption is the lowest. - * **Note:** unlike normal Espruino boards' 'deep sleep' mode, ESP8266 deep sleep - * actually turns off the processor. After the given number of microseconds have - * elapsed, the ESP8266 will restart as if power had been turned off and then back - * on. *All contents of RAM will be lost*. Connect GPIO 16 to RST to enable wakeup. - * **Special:** 0 microseconds cause sleep forever until external wakeup RST pull - * down occurs. - * - * @param {any} micros - Number of microseconds to sleep. - * @param {any} option - posible values are 0, 1, 2 or 4 - * @url http://www.espruino.com/Reference#l_ESP8266_deepSleep - */ - static deepSleep(micros: any, option: any): void; - - -} - -/** - * An instantiation of an Ethernet network adaptor - * @url http://www.espruino.com/Reference#Ethernet - */ -declare class Ethernet { - - - /** - * Get the current IP address, subnet, gateway and mac address. - * - * @param {any} options - An optional `callback(err, ipinfo)` function to be called back with the IP information. * @returns {any} - * @url http://www.espruino.com/Reference#l_Ethernet_getIP + * @url http://www.espruino.com/Reference#l_WioLTE_D20 */ - getIP(options: any): any; + static D20: any; /** - * Set the current IP address or get an IP from DHCP (if no options object is - * specified) - * If 'mac' is specified as an option, it must be a string of the form - * `"00:01:02:03:04:05"` The default mac is 00:08:DC:01:02:03. - * - * @param {any} options - Object containing IP address options `{ ip : '1.2.3.4', subnet : '...', gateway: '...', dns:'...', mac:':::::' }`, or do not supply an object in order to force DHCP. - * @param {any} callback - An optional `callback(err)` function to invoke when ip is set. `err==null` on success, or a string on failure. - * @returns {boolean} True on success - * @url http://www.espruino.com/Reference#l_Ethernet_setIP - */ - setIP(options: any, callback: any): boolean; - - /** - * Set hostname allow to set the hosname used during the dhcp request. min 8 and - * max 12 char, best set before calling `eth.setIP()` Default is WIZnet010203, - * 010203 is the default nic as part of the mac. Best to set the hosname before - * calling setIP(). - * - * @param {any} hostname - hostname as string - * @param {any} callback - An optional `callback(err)` function to be called back with null or error text. - * @returns {boolean} True on success - * @url http://www.espruino.com/Reference#l_Ethernet_setHostname - */ - setHostname(hostname: any, callback: any): boolean; - - /** - * Returns the hostname - * - * @param {any} callback - An optional `callback(err,hostname)` function to be called back with the status information. * @returns {any} - * @url http://www.espruino.com/Reference#l_Ethernet_getHostname + * @url http://www.espruino.com/Reference#l_WioLTE_A6 */ - getHostname(callback: any): any; + static A6: any; /** - * Get the current status of the ethernet device - * - * @param {any} options - An optional `callback(err, status)` function to be called back with the status information. * @returns {any} - * @url http://www.espruino.com/Reference#l_Ethernet_getStatus + * @url http://www.espruino.com/Reference#l_WioLTE_I2C */ - getStatus(options: any): any; -} - -/** - * The HTTP server created by `require('http').createServer` - * @url http://www.espruino.com/Reference#httpSrv - */ -declare class httpSrv { - - - /** - * Start listening for new HTTP connections on the given port - * - * @param {number} port - The port to listen on - * @returns {any} The HTTP server instance that 'listen' was called on - * @url http://www.espruino.com/Reference#l_httpSrv_listen - */ - listen(port: number): any; - - /** - * Stop listening for new HTTP connections - * @url http://www.espruino.com/Reference#l_httpSrv_close - */ - close(): void; -} - -/** - * The HTTP server request - * @url http://www.espruino.com/Reference#httpSRq - */ -declare class httpSRq { - /** - * The 'data' event is called when data is received. If a handler is defined with - * `X.on('data', function(data) { ... })` then it will be called, otherwise data - * will be stored in an internal buffer, where it can be retrieved with `X.read()` - * @param {string} event - The event to listen to. - * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `data` A string containing one or more characters of received data - * @url http://www.espruino.com/Reference#l_httpSRq_data - */ - static on(event: "data", callback: (data: any) => void): void; - - /** - * Called when the connection closes. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_httpSRq_close - */ - static on(event: "close", callback: () => void): void; - - /** - * The headers to sent to the server with this HTTP request. - * @returns {any} An object mapping header name to value - * @url http://www.espruino.com/Reference#l_httpSRq_headers - */ - headers: any; - - /** - * The HTTP method used with this request. Often `"GET"`. - * @returns {any} A string - * @url http://www.espruino.com/Reference#l_httpSRq_method - */ - method: any; - - /** - * The URL requested in this HTTP request, for instance: - * * `"/"` - the main page - * * `"/favicon.ico"` - the web page's icon - * @returns {any} A string representing the URL - * @url http://www.espruino.com/Reference#l_httpSRq_url - */ - url: any; - - /** - * Return how many bytes are available to read. If there is already a listener for - * data, this will always return 0. - * @returns {number} How many bytes are available - * @url http://www.espruino.com/Reference#l_httpSRq_available - */ - available(): number; - - /** - * Return a string containing characters that have been received - * - * @param {number} chars - The number of characters to read, or undefined/0 for all available - * @returns {any} A string containing the required bytes. - * @url http://www.espruino.com/Reference#l_httpSRq_read - */ - read(chars: number): any; - - /** - * Pipe this to a stream (an object with a 'write' method) - * - * @param {any} destination - The destination file/stream that will receive content from the source. - * @param {any} options - * An optional object `{ chunkSize : int=32, end : bool=true, complete : function }` - * chunkSize : The amount of data to pipe from source to destination at a time - * complete : a function to call when the pipe activity is complete - * end : call the 'end' function on the destination when the source is finished - * @url http://www.espruino.com/Reference#l_httpSRq_pipe - */ - pipe(destination: any, options: any): void; -} - -/** - * The HTTP server response - * @url http://www.espruino.com/Reference#httpSRs - */ -declare class httpSRs { - /** - * An event that is fired when the buffer is empty and it can accept more data to - * send. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_httpSRs_drain - */ - static on(event: "drain", callback: () => void): void; - - /** - * Called when the connection closes. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_httpSRs_close - */ - static on(event: "close", callback: () => void): void; - - /** - * The headers to send back along with the HTTP response. - * The default contents are: - * ``` - * { - * "Connection": "close" - * } - * ``` - * @returns {any} An object mapping header name to value - * @url http://www.espruino.com/Reference#l_httpSRs_headers - */ - headers: any; - - /** - * This function writes the `data` argument as a string. Data that is passed in - * (including arrays) will be converted to a string with the normal JavaScript - * `toString` method. For more information about sending binary data see - * `Socket.write` - * - * @param {any} data - A string containing data to send - * @returns {boolean} For node.js compatibility, returns the boolean false. When the send buffer is empty, a `drain` event will be sent - * @url http://www.espruino.com/Reference#l_httpSRs_write - */ - write(data: any): boolean; - - /** - * See `Socket.write` for more information about the data argument - * - * @param {any} data - A string containing data to send - * @url http://www.espruino.com/Reference#l_httpSRs_end - */ - end(data: any): void; - - /** - * Send the given status code and headers. If not explicitly called this will be - * done automatically the first time data is written to the response. - * This cannot be called twice, or after data has already been sent in the - * response. - * - * @param {number} statusCode - The HTTP status code - * @param {any} headers - An object containing the headers - * @url http://www.espruino.com/Reference#l_httpSRs_writeHead - */ - writeHead(statusCode: number, headers: any): void; - - /** - * Set a value to send in the header of this HTTP response. This updates the - * `httpSRs.headers` property. - * Any headers supplied to `writeHead` will overwrite any headers with the same - * name. - * - * @param {any} name - The name of the header as a String - * @param {any} value - The value of the header as a String - * @url http://www.espruino.com/Reference#l_httpSRs_setHeader - */ - setHeader(name: any, value: any): void; -} - -/** - * The HTTP client request, returned by `http.request()` and `http.get()`. - * @url http://www.espruino.com/Reference#httpCRq - */ -declare class httpCRq { - /** - * An event that is fired when the buffer is empty and it can accept more data to - * send. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_httpCRq_drain - */ - static on(event: "drain", callback: () => void): void; - - /** - * An event that is fired if there is an error making the request and the response - * callback has not been invoked. In this case the error event concludes the - * request attempt. The error event function receives an error object as parameter - * with a `code` field and a `message` field. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_httpCRq_error - */ - static on(event: "error", callback: () => void): void; - - /** - * This function writes the `data` argument as a string. Data that is passed in - * (including arrays) will be converted to a string with the normal JavaScript - * `toString` method. For more information about sending binary data see - * `Socket.write` - * - * @param {any} data - A string containing data to send - * @returns {boolean} For node.js compatibility, returns the boolean false. When the send buffer is empty, a `drain` event will be sent - * @url http://www.espruino.com/Reference#l_httpCRq_write - */ - write(data: any): boolean; - - /** - * Finish this HTTP request - optional data to append as an argument - * See `Socket.write` for more information about the data argument - * - * @param {any} data - A string containing data to send - * @url http://www.espruino.com/Reference#l_httpCRq_end - */ - end(data: any): void; -} - -/** - * The HTTP client response, passed to the callback of `http.request()` an - * `http.get()`. - * @url http://www.espruino.com/Reference#httpCRs - */ -declare class httpCRs { - /** - * The 'data' event is called when data is received. If a handler is defined with - * `X.on('data', function(data) { ... })` then it will be called, otherwise data - * will be stored in an internal buffer, where it can be retrieved with `X.read()` - * @param {string} event - The event to listen to. - * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `data` A string containing one or more characters of received data - * @url http://www.espruino.com/Reference#l_httpCRs_data - */ - static on(event: "data", callback: (data: any) => void): void; - - /** - * Called when the connection closes with one `hadError` boolean parameter, which - * indicates whether an error occurred. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_httpCRs_close - */ - static on(event: "close", callback: () => void): void; - - /** - * An event that is fired if there is an error receiving the response. The error - * event function receives an error object as parameter with a `code` field and a - * `message` field. After the error event the close even will also be triggered to - * conclude the HTTP request/response. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_httpCRs_error - */ - static on(event: "error", callback: () => void): void; - - /** - * The headers received along with the HTTP response - * @returns {any} An object mapping header name to value - * @url http://www.espruino.com/Reference#l_httpCRs_headers - */ - headers: any; - - /** - * The HTTP response's status code - usually `"200"` if all went well - * @returns {any} The status code as a String - * @url http://www.espruino.com/Reference#l_httpCRs_statusCode - */ - statusCode: any; - - /** - * The HTTP response's status message - Usually `"OK"` if all went well - * @returns {any} An String Status Message - * @url http://www.espruino.com/Reference#l_httpCRs_statusMessage - */ - statusMessage: any; - - /** - * The HTTP version reported back by the server - usually `"1.1"` - * @returns {any} Th - * @url http://www.espruino.com/Reference#l_httpCRs_httpVersion - */ - httpVersion: any; - - /** - * Return how many bytes are available to read. If there is a 'data' event handler, - * this will always return 0. - * @returns {number} How many bytes are available - * @url http://www.espruino.com/Reference#l_httpCRs_available - */ - available(): number; - - /** - * Return a string containing characters that have been received - * - * @param {number} chars - The number of characters to read, or undefined/0 for all available - * @returns {any} A string containing the required bytes. - * @url http://www.espruino.com/Reference#l_httpCRs_read - */ - read(chars: number): any; - - /** - * Pipe this to a stream (an object with a 'write' method) - * - * @param {any} destination - The destination file/stream that will receive content from the source. - * @param {any} options - * An optional object `{ chunkSize : int=32, end : bool=true, complete : function }` - * chunkSize : The amount of data to pipe from source to destination at a time - * complete : a function to call when the pipe activity is complete - * end : call the 'end' function on the destination when the source is finished - * @url http://www.espruino.com/Reference#l_httpCRs_pipe - */ - pipe(destination: any, options: any): void; -} - -/** - * This class provides functionality to recognise gestures drawn on a touchscreen. - * It is only built into Bangle.js 2. - * Usage: - * ``` - * var strokes = { - * stroke1 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])), - * stroke2 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])), - * stroke3 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])) - * }; - * var r = Unistroke.recognise(strokes,new Uint8Array([x1, y1, x2, y2, x3, y3, ...])) - * print(r); // stroke1/stroke2/stroke3 - * ``` - * @url http://www.espruino.com/Reference#Unistroke - */ -declare class Unistroke { - /** - * Create a new Unistroke based on XY coordinates - * - * @param {any} xy - An array of interleaved XY coordinates - * @returns {any} A string of data representing this unistroke - * @url http://www.espruino.com/Reference#l_Unistroke_new - */ - static new(xy: any): any; - - /** - * Recognise based on an object of named strokes, and a list of XY coordinates - * - * @param {any} strokes - An object of named strokes : `{arrow:..., circle:...}` - * @param {any} xy - An array of interleaved XY coordinates - * @returns {any} The key name of the matched stroke - * @url http://www.espruino.com/Reference#l_Unistroke_recognise - */ - static recognise(strokes: any, xy: any): any; - - -} - -/** - * The NRF class is for controlling functionality of the Nordic nRF51/nRF52 chips. - * Most functionality is related to Bluetooth Low Energy, however there are also - * some functions related to NFC that apply to NRF52-based devices. - * @url http://www.espruino.com/Reference#NRF - */ -declare class NRF { - /** - * @returns {any} An object - * @url http://www.espruino.com/Reference#l_NRF_getSecurityStatus - */ - static getSecurityStatus(): any; - - /** - * @returns {any} An object - * @url http://www.espruino.com/Reference#l_NRF_getAddress - */ - static getAddress(): any; - - /** - * - * @param {any} data - The service (and characteristics) to advertise - * @param {any} options - Optional object containing options - * @url http://www.espruino.com/Reference#l_NRF_setServices - */ - static setServices(data: any, options: any): void; - - /** - * - * @param {any} data - The data to advertise as an object - see below for more info - * @param {any} options - An optional object of options - * @url http://www.espruino.com/Reference#l_NRF_setAdvertising - */ - static setAdvertising(data: any, options: any): void; - - /** - * Called when a host device connects to Espruino. The first argument contains the - * address. - * @param {string} event - The event to listen to. - * @param {(addr: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `addr` The address of the device that has connected - * @url http://www.espruino.com/Reference#l_NRF_connect - */ - static on(event: "connect", callback: (addr: any) => void): void; - - /** - * Called when a host device disconnects from Espruino. - * The most common reason is: - * * 19 - `REMOTE_USER_TERMINATED_CONNECTION` - * * 22 - `LOCAL_HOST_TERMINATED_CONNECTION` - * @param {string} event - The event to listen to. - * @param {(reason: number) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `reason` The reason code reported back by the BLE stack - see Nordic's [`ble_hci.h` file](https://github.com/espruino/Espruino/blob/master/targetlibs/nrf5x_12/components/softdevice/s132/headers/ble_hci.h#L71) for more information - * @url http://www.espruino.com/Reference#l_NRF_disconnect - */ - static on(event: "disconnect", callback: (reason: number) => void): void; - - /** - * Contains updates on the security of the current Bluetooth link. - * See Nordic's `ble_gap_evt_auth_status_t` structure for more information. - * @param {string} event - The event to listen to. - * @param {(status: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `status` An object containing `{auth_status,bonded,lv4,kdist_own,kdist_peer} - * @url http://www.espruino.com/Reference#l_NRF_security - */ - static on(event: "security", callback: (status: any) => void): void; - - /** - * Called with a single byte value when Espruino is set up as a HID device and the - * computer it is connected to sends a HID report back to Espruino. This is usually - * used for handling indications such as the Caps Lock LED. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_NRF_HID - */ - static on(event: "HID", callback: () => void): void; - - /** - * Called with discovered services when discovery is finished - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_NRF_servicesDiscover - */ - static on(event: "servicesDiscover", callback: () => void): void; - - /** - * Called with discovered characteristics when discovery is finished - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_NRF_characteristicsDiscover - */ - static on(event: "characteristicsDiscover", callback: () => void): void; - - /** - * Called when an NFC field is detected - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_NRF_NFCon - */ - static on(event: "NFCon", callback: () => void): void; - - /** - * Called when an NFC field is no longer detected - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_NRF_NFCoff - */ - static on(event: "NFCoff", callback: () => void): void; - - /** - * When NFC is started with `NRF.nfcStart`, this is fired when NFC data is - * received. It doesn't get called if NFC is started with `NRF.nfcURL` or - * `NRF.nfcRaw` - * @param {string} event - The event to listen to. - * @param {(arr: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `arr` An ArrayBuffer containign the received data - * @url http://www.espruino.com/Reference#l_NRF_NFCrx - */ - static on(event: "NFCrx", callback: (arr: any) => void): void; - - /** - * If a device is connected to Espruino, disconnect from it. - * @url http://www.espruino.com/Reference#l_NRF_disconnect - */ - static disconnect(): void; - - /** - * Disable Bluetooth advertising and disconnect from any device that connected to - * Puck.js as a peripheral (this won't affect any devices that Puck.js initiated - * connections to). - * This makes Puck.js undiscoverable, so it can't be connected to. - * Use `NRF.wake()` to wake up and make Puck.js connectable again. - * @url http://www.espruino.com/Reference#l_NRF_sleep - */ - static sleep(): void; - - /** - * Enable Bluetooth advertising (this is enabled by default), which allows other - * devices to discover and connect to Puck.js. - * Use `NRF.sleep()` to disable advertising. - * @url http://www.espruino.com/Reference#l_NRF_wake - */ - static wake(): void; - - /** - * Restart the Bluetooth softdevice (if there is currently a BLE connection, it - * will queue a restart to be done when the connection closes). - * You shouldn't need to call this function in normal usage. However, Nordic's BLE - * softdevice has some settings that cannot be reset. For example there are only a - * certain number of unique UUIDs. Once these are all used the only option is to - * restart the softdevice to clear them all out. - * - * @param {any} callback - An optional function to be called while the softdevice is uninitialised. Use with caution - accessing console/bluetooth will almost certainly result in a crash. - * @url http://www.espruino.com/Reference#l_NRF_restart - */ - static restart(callback: any): void; - - /** - * Get this device's default Bluetooth MAC address. - * For Puck.js, the last 5 characters of this (eg. `ee:ff`) are used in the - * device's advertised Bluetooth name. - * @returns {any} MAC address - a string of the form 'aa:bb:cc:dd:ee:ff' - * @url http://www.espruino.com/Reference#l_NRF_getAddress - */ - static getAddress(): any; - - /** - * Set this device's default Bluetooth MAC address: - * ``` - * NRF.setAddress("ff:ee:dd:cc:bb:aa random"); - * ``` - * Addresses take the form: - * * `"ff:ee:dd:cc:bb:aa"` or `"ff:ee:dd:cc:bb:aa public"` for a public address - * * `"ff:ee:dd:cc:bb:aa random"` for a random static address (the default for - * Espruino) - * This may throw a `INVALID_BLE_ADDR` error if the upper two bits of the address - * don't match the address type. - * To change the address, Espruino must restart the softdevice. It will only do so - * when it is disconnected from other devices. - * - * @param {any} addr - The address to use (as a string) - * @url http://www.espruino.com/Reference#l_NRF_setAddress - */ - static setAddress(addr: any): void; - - /** - * Get the battery level in volts (the voltage that the NRF chip is running off - * of). - * This is the battery level of the device itself - it has nothing to with any - * device that might be connected. - * @returns {number} Battery level in volts - * @url http://www.espruino.com/Reference#l_NRF_getBattery - */ - static getBattery(): number; - - /** - * Change the data that Espruino advertises. - * Data can be of the form `{ UUID : data_as_byte_array }`. The UUID should be a - * [Bluetooth Service - * ID](https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx). - * For example to return battery level at 95%, do: - * ``` - * NRF.setAdvertising({ - * 0x180F : [95] // Service data 0x180F = 95 - * }); - * ``` - * Or you could report the current temperature: - * ``` - * setInterval(function() { - * NRF.setAdvertising({ - * 0x1809 : [Math.round(E.getTemperature())] - * }); - * }, 30000); - * ``` - * If you specify a value for the object key, Service Data is advertised. However - * if you specify `undefined`, the Service UUID is advertised: - * ``` - * NRF.setAdvertising({ - * 0x180D : undefined // Advertise service UUID 0x180D (HRM) - * }); - * ``` - * Service UUIDs can also be supplied in the second argument of `NRF.setServices`, - * but those go in the scan response packet. - * You can also supply the raw advertising data in an array. For example to - * advertise as an Eddystone beacon: - * ``` - * NRF.setAdvertising([0x03, // Length of Service List - * 0x03, // Param: Service List - * 0xAA, 0xFE, // Eddystone ID - * 0x13, // Length of Service Data - * 0x16, // Service Data - * 0xAA, 0xFE, // Eddystone ID - * 0x10, // Frame type: URL - * 0xF8, // Power - * 0x03, // https:// - * 'g','o','o','.','g','l','/','B','3','J','0','O','c'], - * {interval:100}); - * ``` - * (However for Eddystone we'd advise that you use the [Espruino Eddystone - * library](/Puck.js+Eddystone)) - * **Note:** When specifying data as an array, certain advertising options such as - * `discoverable` and `showName` won't have any effect. - * **Note:** The size of Bluetooth LE advertising packets is limited to 31 bytes. - * If you want to advertise more data, consider using an array for `data` (See - * below), or `NRF.setScanResponse`. - * You can even specify an array of arrays or objects, in which case each - * advertising packet will be used in turn - for instance to make your device - * advertise battery level and its name as well as both Eddystone and iBeacon : - * ``` - * NRF.setAdvertising([ - * {0x180F : [Puck.getBatteryPercentage()]}, // normal advertising, with battery % - * require("ble_ibeacon").get(...), // iBeacon - * require("ble_eddystone").get(...), // eddystone - * ], {interval:300}); - * ``` - * `options` is an object, which can contain: - * ``` - * { - * name: "Hello" // The name of the device - * showName: true/false // include full name, or nothing - * discoverable: true/false // general discoverable, or limited - default is limited - * connectable: true/false // whether device is connectable - default is true - * scannable : true/false // whether device can be scanned for scan response packets - default is true - * interval: 600 // Advertising interval in msec, between 20 and 10000 (default is 375ms) - * manufacturer: 0x0590 // IF sending manufacturer data, this is the manufacturer ID - * manufacturerData: [...] // IF sending manufacturer data, this is an array of data - * phy: "1mbps/2mbps/coded" // (NRF52840 only) use the long-range coded phy for transmission (1mbps default) - * } - * ``` - * Setting `connectable` and `scannable` to false gives the lowest power - * consumption as the BLE radio doesn't have to listen after sending advertising. - * **NOTE:** Non-`connectable` advertising can't have an advertising interval less - * than 100ms according to the BLE spec. - * So for instance to set the name of Puck.js without advertising any other data - * you can just use the command: - * ``` - * NRF.setAdvertising({},{name:"Hello"}); - * ``` - * You can also specify 'manufacturer data', which is another form of advertising - * data. We've registered the Manufacturer ID 0x0590 (as Pur3 Ltd) for use with - * *Official Espruino devices* - use it to advertise whatever data you'd like, but - * we'd recommend using JSON. - * For example by not advertising a device name you can send up to 24 bytes of JSON - * on Espruino's manufacturer ID: - * ``` - * var data = {a:1,b:2}; - * NRF.setAdvertising({},{ - * showName:false, - * manufacturer:0x0590, - * manufacturerData:JSON.stringify(data) - * }); - * ``` - * If you're using [EspruinoHub](https://github.com/espruino/EspruinoHub) then it - * will automatically decode this into the folling MQTT topics: - * * `/ble/advertise/ma:c_:_a:dd:re:ss/espruino` -> `{"a":10,"b":15}` - * * `/ble/advertise/ma:c_:_a:dd:re:ss/a` -> `1` - * * `/ble/advertise/ma:c_:_a:dd:re:ss/b` -> `2` - * Note that **you only have 24 characters available for JSON**, so try to use the - * shortest field names possible and avoid floating point values that can be very - * long when converted to a String. - * - * @param {any} data - The service data to advertise as an object - see below for more info - * @param {any} options - An optional object of options - * @url http://www.espruino.com/Reference#l_NRF_setAdvertising - */ - static setAdvertising(data: any, options: any): void; - - /** - * This is just like `NRF.setAdvertising`, except instead of advertising the data, - * it returns the packet that would be advertised as an array. - * - * @param {any} data - The data to advertise as an object - * @param {any} options - An optional object of options - * @returns {any} An array containing the advertising data - * @url http://www.espruino.com/Reference#l_NRF_getAdvertisingData - */ - static getAdvertisingData(data: any, options: any): any; - - /** - * The raw scan response data should be supplied as an array. For example to return - * "Sample" for the device name: - * ``` - * NRF.setScanResponse([0x07, // Length of Data - * 0x09, // Param: Complete Local Name - * 'S', 'a', 'm', 'p', 'l', 'e']); - * ``` - * **Note:** `NRF.setServices(..., {advertise:[ ... ]})` writes advertised services - * into the scan response - so you can't use both `advertise` and `NRF.setServices` - * or one will overwrite the other. - * - * @param {any} data - The data to for the scan response - * @url http://www.espruino.com/Reference#l_NRF_setScanResponse - */ - static setScanResponse(data: any): void; - - /** - * Change the services and characteristics Espruino advertises. - * If you want to **change** the value of a characteristic, you need to use - * `NRF.updateServices()` instead - * To expose some information on Characteristic `ABCD` on service `BCDE` you could - * do: - * ``` - * NRF.setServices({ - * 0xBCDE : { - * 0xABCD : { - * value : "Hello", - * readable : true - * } - * } - * }); - * ``` - * Or to allow the 3 LEDs to be controlled by writing numbers 0 to 7 to a - * characteristic, you can do the following. `evt.data` is an ArrayBuffer. - * ``` - * NRF.setServices({ - * 0xBCDE : { - * 0xABCD : { - * writable : true, - * onWrite : function(evt) { - * digitalWrite([LED3,LED2,LED1], evt.data[0]); - * } - * } - * } - * }); - * ``` - * You can supply many different options: - * ``` - * NRF.setServices({ - * 0xBCDE : { - * 0xABCD : { - * value : "Hello", // optional - * maxLen : 5, // optional (otherwise is length of initial value) - * broadcast : false, // optional, default is false - * readable : true, // optional, default is false - * writable : true, // optional, default is false - * notify : true, // optional, default is false - * indicate : true, // optional, default is false - * description: "My Characteristic", // optional, default is null, - * security: { // optional - see NRF.setSecurity - * read: { // optional - * encrypted: false, // optional, default is false - * mitm: false, // optional, default is false - * lesc: false, // optional, default is false - * signed: false // optional, default is false - * }, - * write: { // optional - * encrypted: true, // optional, default is false - * mitm: false, // optional, default is false - * lesc: false, // optional, default is false - * signed: false // optional, default is false - * } - * }, - * onWrite : function(evt) { // optional - * console.log("Got ", evt.data); // an ArrayBuffer - * }, - * onWriteDesc : function(evt) { // optional - called when the 'cccd' descriptor is written - * // for example this is called when notifications are requested by the client: - * console.log("Notifications enabled = ", evt.data[0]&1); - * } - * } - * // more characteristics allowed - * } - * // more services allowed - * }); - * ``` - * **Note:** UUIDs can be integers between `0` and `0xFFFF`, strings of the form - * `"ABCD"`, or strings of the form `"ABCDABCD-ABCD-ABCD-ABCD-ABCDABCDABCD"` - * `options` can be of the form: - * ``` - * NRF.setServices(undefined, { - * hid : new Uint8Array(...), // optional, default is undefined. Enable BLE HID support - * uart : true, // optional, default is true. Enable BLE UART support - * advertise: [ '180D' ] // optional, list of service UUIDs to advertise - * ancs : true, // optional, Bangle.js-only, enable Apple ANCS support for notifications - * ams : true // optional, Bangle.js-only, enable Apple AMS support for media control - * }); - * ``` - * To enable BLE HID, you must set `hid` to an array which is the BLE report - * descriptor. The easiest way to do this is to use the `ble_hid_controls` or - * `ble_hid_keyboard` modules. - * **Note:** Just creating a service doesn't mean that the service will be - * advertised. It will only be available after a device connects. To advertise, - * specify the UUIDs you wish to advertise in the `advertise` field of the second - * `options` argument. For example this will create and advertise a heart rate - * service: - * ``` - * NRF.setServices({ - * 0x180D: { // heart_rate - * 0x2A37: { // heart_rate_measurement - * notify: true, - * value : [0x06, heartrate], - * } - * } - * }, { advertise: [ '180D' ] }); - * ``` - * You may specify 128 bit UUIDs to advertise, however you may get a `DATA_SIZE` - * exception because there is insufficient space in the Bluetooth LE advertising - * packet for the 128 bit UART UUID as well as the UUID you specified. In this case - * you can add `uart:false` after the `advertise` element to disable the UART, - * however you then be unable to connect to Puck.js's console via Bluetooth. - * If you absolutely require two or more 128 bit UUIDs then you will have to - * specify your own raw advertising data packets with `NRF.setAdvertising` - * **Note:** The services on Espruino can only be modified when there is no device - * connected to it as it requires a restart of the Bluetooth stack. **iOS devices - * will 'cache' the list of services** so apps like NRF Connect may incorrectly - * display the old services even after you have modified them. To fix this, disable - * and re-enable Bluetooth on your iOS device, or use an Android device to run NRF - * Connect. - * **Note:** Not all combinations of security configuration values are valid, the - * valid combinations are: encrypted, encrypted + mitm, lesc, signed, signed + - * mitm. See `NRF.setSecurity` for more information. - * - * @param {any} data - The service (and characteristics) to advertise - * @param {any} options - Optional object containing options - * @url http://www.espruino.com/Reference#l_NRF_setServices - */ - static setServices(data: any, options: any): void; - - /** - * Update values for the services and characteristics Espruino advertises. Only - * services and characteristics previously declared using `NRF.setServices` are - * affected. - * To update the '0xABCD' characteristic in the '0xBCDE' service: - * ``` - * NRF.updateServices({ - * 0xBCDE : { - * 0xABCD : { - * value : "World" - * } - * } - * }); - * ``` - * You can also use 128 bit UUIDs, for example - * `"b7920001-3c1b-4b40-869f-3c0db9be80c6"`. - * To define a service and characteristic and then notify connected clients of a - * change to it when a button is pressed: - * ``` - * NRF.setServices({ - * 0xBCDE : { - * 0xABCD : { - * value : "Hello", - * maxLen : 20, - * notify: true - * } - * } - * }); - * setWatch(function() { - * NRF.updateServices({ - * 0xBCDE : { - * 0xABCD : { - * value : "World!", - * notify: true - * } - * } - * }); - * }, BTN, { repeat:true, edge:"rising", debounce: 50 }); - * ``` - * This only works if the characteristic was created with `notify: true` using - * `NRF.setServices`, otherwise the characteristic will be updated but no - * notification will be sent. - * Also note that `maxLen` was specified. If it wasn't then the maximum length of - * the characteristic would have been 5 - the length of `"Hello"`. - * To indicate (i.e. notify with ACK) connected clients of a change to the '0xABCD' - * characteristic in the '0xBCDE' service: - * ``` - * NRF.updateServices({ - * 0xBCDE : { - * 0xABCD : { - * value : "World", - * indicate: true - * } - * } - * }); - * ``` - * This only works if the characteristic was created with `indicate: true` using - * `NRF.setServices`, otherwise the characteristic will be updated but no - * notification will be sent. - * **Note:** See `NRF.setServices` for more information - * - * @param {any} data - The service (and characteristics) to update - * @url http://www.espruino.com/Reference#l_NRF_updateServices - */ - static updateServices(data: any): void; - - /** - * Start/stop listening for BLE advertising packets within range. Returns a - * `BluetoothDevice` for each advertsing packet. **By default this is not an active - * scan, so Scan Response advertising data is not included (see below)** - * ``` - * // Start scanning - * packets=10; - * NRF.setScan(function(d) { - * packets--; - * if (packets<=0) - * NRF.setScan(); // stop scanning - * else - * console.log(d); // print packet info - * }); - * ``` - * Each `BluetoothDevice` will look a bit like: - * ``` - * BluetoothDevice { - * "id": "aa:bb:cc:dd:ee:ff", // address - * "rssi": -89, // signal strength - * "services": [ "128bit-uuid", ... ], // zero or more service UUIDs - * "data": new Uint8Array([ ... ]).buffer, // ArrayBuffer of returned data - * "serviceData" : { "0123" : [ 1 ] }, // if service data is in 'data', it's extracted here - * "manufacturer" : 0x1234, // if manufacturer data is in 'data', the 16 bit manufacturer ID is extracted here - * "manufacturerData" : new Uint8Array([...]).buffer, // if manufacturer data is in 'data', the data is extracted here as an ArrayBuffer - * "name": "DeviceName" // the advertised device name - * } - * ``` - * You can also supply a set of filters (as described in `NRF.requestDevice`) as a - * second argument, which will allow you to filter the devices you get a callback - * for. This helps to cut down on the time spent processing JavaScript code in - * areas with a lot of Bluetooth advertisements. For example to find only devices - * with the manufacturer data `0x0590` (Espruino's ID) you could do: - * ``` - * NRF.setScan(function(d) { - * console.log(d.manufacturerData); - * }, { filters: [{ manufacturerData:{0x0590:{}} }] }); - * ``` - * You can also specify `active:true` in the second argument to perform active - * scanning (this requests scan response packets) from any devices it finds. - * **Note:** Using a filter in `setScan` filters each advertising packet - * individually. As a result, if you filter based on a service UUID and a device - * advertises with multiple packets (or a scan response when `active:true`) only - * the packets matching the filter are returned. To aggregate multiple packets you - * can use `NRF.findDevices`. - * **Note:** BLE advertising packets can arrive quickly - faster than you'll be - * able to print them to the console. It's best only to print a few, or to use a - * function like `NRF.findDevices(..)` which will collate a list of available - * devices. - * **Note:** Using setScan turns the radio's receive mode on constantly. This can - * draw a *lot* of power (12mA or so), so you should use it sparingly or you can - * run your battery down quickly. - * - * @param {any} callback - The callback to call with received advertising packets, or undefined to stop - * @param {any} options - An optional object `{filters: ...}` (as would be passed to `NRF.requestDevice`) to filter devices by - * @url http://www.espruino.com/Reference#l_NRF_setScan - */ - static setScan(callback: any, options: any): void; - - /** - * This function can be used to quickly filter through Bluetooth devices. - * For instance if you wish to scan for multiple different types of device at the - * same time then you could use `NRF.findDevices` with all the filters you're - * interested in. When scanning is finished you can then use `NRF.filterDevices` to - * pick out just the devices of interest. - * ``` - * // the two types of device we're interested in - * var filter1 = [{serviceData:{"fe95":{}}}]; - * var filter2 = [{namePrefix:"Pixl.js"}]; - * // the following filter will return both types of device - * var allFilters = filter1.concat(filter2); - * // now scan for both types of device, and filter them out afterwards - * NRF.findDevices(function(devices) { - * var devices1 = NRF.filterDevices(devices, filter1); - * var devices2 = NRF.filterDevices(devices, filter2); - * // ... - * }, {filters : allFilters}); - * ``` - * - * @param {any} devices - An array of `BluetoothDevice` objects, from `NRF.findDevices` or similar - * @param {any} filters - A list of filters (as would be passed to `NRF.requestDevice`) to filter devices by - * @returns {any} An array of `BluetoothDevice` objects that match the given filters - * @url http://www.espruino.com/Reference#l_NRF_filterDevices - */ - static filterDevices(devices: any, filters: any): any; - - /** - * Utility function to return a list of BLE devices detected in range. Behind the - * scenes, this uses `NRF.setScan(...)` and collates the results. - * ``` - * NRF.findDevices(function(devices) { - * console.log(devices); - * }, 1000); - * ``` - * prints something like: - * ``` - * [ - * BluetoothDevice { - * "id" : "e7:e0:57:ad:36:a2 random", - * "rssi": -45, - * "services": [ "4567" ], - * "serviceData" : { "0123" : [ 1 ] }, - * "manufacturer" : 1424, - * "manufacturerData" : new Uint8Array([ ... ]).buffer, - * "data": new ArrayBuffer([ ... ]).buffer, - * "name": "Puck.js 36a2" - * }, - * BluetoothDevice { - * "id": "c0:52:3f:50:42:c9 random", - * "rssi": -65, - * "data": new ArrayBuffer([ ... ]), - * "name": "Puck.js 8f57" - * } - * ] - * ``` - * For more information on the structure returned, see `NRF.setScan`. - * If you want to scan only for specific devices you can replace the timeout with - * an object of the form `{filters: ..., timeout : ..., active: bool}` using the - * filters described in `NRF.requestDevice`. For example to search for devices with - * Espruino's `manufacturerData`: - * ``` - * NRF.findDevices(function(devices) { - * ... - * }, {timeout : 2000, filters : [{ manufacturerData:{0x0590:{}} }] }); - * ``` - * You could then use - * [`BluetoothDevice.gatt.connect(...)`](/Reference#l_BluetoothRemoteGATTServer_connect) - * on the device returned to make a connection. - * You can also use [`NRF.connect(...)`](/Reference#l_NRF_connect) on just the `id` - * string returned, which may be useful if you always want to connect to a specific - * device. - * **Note:** Using findDevices turns the radio's receive mode on for 2000ms (or - * however long you specify). This can draw a *lot* of power (12mA or so), so you - * should use it sparingly or you can run your battery down quickly. - * **Note:** The 'data' field contains the data of *the last packet received*. - * There may have been more packets. To get data for each packet individually use - * `NRF.setScan` instead. - * - * @param {any} callback - The callback to call with received advertising packets (as `BluetoothDevice`), or undefined to stop - * @param {any} [options] - [optional] A time in milliseconds to scan for (defaults to 2000), Or an optional object `{filters: ..., timeout : ..., active: bool}` (as would be passed to `NRF.requestDevice`) to filter devices by - * @url http://www.espruino.com/Reference#l_NRF_findDevices - */ - static findDevices(callback: (devices: BluetoothDevice[]) => void, options?: number | { filters?: NRFFilters, timeout?: number, active?: boolean }): void; - - /** - * Start/stop listening for RSSI values on the currently active connection (where - * This device is a peripheral and is being connected to by a 'central' device) - * ``` - * // Start scanning - * NRF.setRSSIHandler(function(rssi) { - * console.log(rssi); // prints -85 (or similar) - * }); - * // Stop Scanning - * NRF.setRSSIHandler(); - * ``` - * RSSI is the 'Received Signal Strength Indication' in dBm - * - * @param {any} callback - The callback to call with the RSSI value, or undefined to stop - * @url http://www.espruino.com/Reference#l_NRF_setRSSIHandler - */ - static setRSSIHandler(callback: any): void; - - /** - * Set the BLE radio transmit power. The default TX power is 0 dBm, and - * - * @param {number} power - Transmit power. Accepted values are -40(nRF52 only), -30(nRF51 only), -20, -16, -12, -8, -4, 0, and 4 dBm. On nRF52840 (eg Bangle.js 2) 5/6/7/8 dBm are available too. Others will give an error code. - * @url http://www.espruino.com/Reference#l_NRF_setTxPower - */ - static setTxPower(power: number): void; - - /** - * **THIS IS DEPRECATED** - please use `NRF.setConnectionInterval` for peripheral - * and `NRF.connect(addr, options)`/`BluetoothRemoteGATTServer.connect(options)` - * for central connections. - * This sets the connection parameters - these affect the transfer speed and power - * usage when the device is connected. - * * When not low power, the connection interval is between 7.5 and 20ms - * * When low power, the connection interval is between 500 and 1000ms - * When low power connection is enabled, transfers of data over Bluetooth will be - * very slow, however power usage while connected will be drastically decreased. - * This will only take effect after the connection is disconnected and - * re-established. - * - * @param {boolean} lowPower - Whether the connection is low power or not - * @url http://www.espruino.com/Reference#l_NRF_setLowPowerConnection - */ - static setLowPowerConnection(lowPower: boolean): void; - - /** - * Enables NFC and starts advertising the given URL. For example: - * ``` - * NRF.nfcURL("http://espruino.com"); - * ``` - * - * @param {any} url - The URL string to expose on NFC, or `undefined` to disable NFC - * @url http://www.espruino.com/Reference#l_NRF_nfcURL - */ - static nfcURL(url: any): void; - - /** - * Enables NFC and with an out of band 16 byte pairing key. - * For example the following will enable out of band pairing on BLE such that the - * device will pair when you tap the phone against it: - * ``` - * var bleKey = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00]; - * NRF.on('security',s=>print("security",JSON.stringify(s))); - * NRF.nfcPair(bleKey); - * NRF.setSecurity({oob:bleKey, mitm:true}); - * ``` - * - * @param {any} key - 16 byte out of band key - * @url http://www.espruino.com/Reference#l_NRF_nfcPair - */ - static nfcPair(key: any): void; - - /** - * Enables NFC with a record that will launch the given android app. - * For example: - * ``` - * NRF.nfcAndroidApp("no.nordicsemi.android.nrftoolbox") - * ``` - * - * @param {any} app - The unique identifier of the given Android App - * @url http://www.espruino.com/Reference#l_NRF_nfcAndroidApp - */ - static nfcAndroidApp(app: any): void; - - /** - * Enables NFC and starts advertising with Raw data. For example: - * ``` - * NRF.nfcRaw(new Uint8Array([193, 1, 0, 0, 0, 13, 85, 3, 101, 115, 112, 114, 117, 105, 110, 111, 46, 99, 111, 109])); - * // same as NRF.nfcURL("http://espruino.com"); - * ``` - * - * @param {any} payload - The NFC NDEF message to deliver to the reader - * @url http://www.espruino.com/Reference#l_NRF_nfcRaw - */ - static nfcRaw(payload: any): void; - - /** - * **Advanced NFC Functionality.** If you just want to advertise a URL, use - * `NRF.nfcURL` instead. - * Enables NFC and starts advertising. `NFCrx` events will be fired when data is - * received. - * ``` - * NRF.nfcStart(); - * ``` - * - * @param {any} payload - Optional 7 byte UID - * @returns {any} Internal tag memory (first 10 bytes of tag data) - * @url http://www.espruino.com/Reference#l_NRF_nfcStart - */ - static nfcStart(payload: any): any; - - /** - * **Advanced NFC Functionality.** If you just want to advertise a URL, use - * `NRF.nfcURL` instead. - * Disables NFC. - * ``` - * NRF.nfcStop(); - * ``` - * - * @url http://www.espruino.com/Reference#l_NRF_nfcStop - */ - static nfcStop(): void; - - /** - * **Advanced NFC Functionality.** If you just want to advertise a URL, use - * `NRF.nfcURL` instead. - * Acknowledges the last frame and optionally transmits a response. If payload is - * an array, then a array.length byte nfc frame is sent. If payload is a int, then - * a 4bit ACK/NACK is sent. **Note:** ```nfcSend``` should always be called after - * an ```NFCrx``` event. - * ``` - * NRF.nfcSend(new Uint8Array([0x01, 0x02, ...])); - * // or - * NRF.nfcSend(0x0A); - * // or - * NRF.nfcSend(); - * ``` - * - * @param {any} payload - Optional tx data - * @url http://www.espruino.com/Reference#l_NRF_nfcSend - */ - static nfcSend(payload: any): void; - - /** - * Send a USB HID report. HID must first be enabled with `NRF.setServices({}, {hid: - * hid_report})` - * - * @param {any} data - Input report data as an array - * @param {any} callback - A callback function to be called when the data is sent - * @url http://www.espruino.com/Reference#l_NRF_sendHIDReport - */ - static sendHIDReport(data: any, callback: any): void; - - /** - * Check if Apple Notification Center Service (ANCS) is currently active on the BLE - * connection - * - * @returns {boolean} True if Apple Notification Center Service (ANCS) has been initialised and is active - * @url http://www.espruino.com/Reference#l_NRF_ancsIsActive - */ - static ancsIsActive(): boolean; - - /** - * Send an ANCS action for a specific Notification UID. Corresponds to - * posaction/negaction in the 'ANCS' event that was received - * - * @param {number} uid - The UID of the notification to respond to - * @param {boolean} positive - `true` for positive action, `false` for negative - * @url http://www.espruino.com/Reference#l_NRF_ancsAction - */ - static ancsAction(uid: number, positive: boolean): void; - - /** - * Get ANCS info for a notification, eg: - * - * @param {number} uid - The UID of the notification to get information for - * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete - * @url http://www.espruino.com/Reference#l_NRF_ancsGetNotificationInfo - */ - static ancsGetNotificationInfo(uid: number): Promise; - - /** - * Get ANCS info for an app (add id is available via `ancsGetNotificationInfo`) - * Promise returns: - * ``` - * { - * "uid" : int, - * "appId" : string, - * "title" : string, - * "subtitle" : string, - * "message" : string, - * "messageSize" : string, - * "date" : string, - * "posAction" : string, - * "negAction" : string, - * "name" : string, - * } - * ``` - * - * @param {any} id - The app ID to get information for - * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete - * @url http://www.espruino.com/Reference#l_NRF_ancsGetAppInfo - */ - static ancsGetAppInfo(id: any): Promise; - - /** - * Check if Apple Media Service (AMS) is currently active on the BLE connection - * - * @returns {boolean} True if Apple Media Service (AMS) has been initialised and is active - * @url http://www.espruino.com/Reference#l_NRF_amsIsActive - */ - static amsIsActive(): boolean; - - /** - * Get Apple Media Service (AMS) info for the current media player. "playbackinfo" - * returns a concatenation of three comma-separated values: - * - PlaybackState: a string that represents the integer value of the playback - * state: - * - PlaybackStatePaused = 0 - * - PlaybackStatePlaying = 1 - * - PlaybackStateRewinding = 2 - * - PlaybackStateFastForwarding = 3 - * - PlaybackRate: a string that represents the floating point value of the - * playback rate. - * - ElapsedTime: a string that represents the floating point value of the elapsed - * time of the current track, in seconds - * - * @param {any} id - Either 'name', 'playbackinfo' or 'volume' - * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete - * @url http://www.espruino.com/Reference#l_NRF_amsGetPlayerInfo - */ - static amsGetPlayerInfo(id: any): Promise; - - /** - * Get Apple Media Service (AMS) info for the currently-playing track - * - * @param {any} id - Either 'artist', 'album', 'title' or 'duration' - * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete - * @url http://www.espruino.com/Reference#l_NRF_amsGetTrackInfo - */ - static amsGetTrackInfo(id: any): Promise; - - /** - * Send an AMS command to an Apple Media Service device to control music playback - * Command is one of play, pause, playpause, next, prev, volup, voldown, repeat, - * shuffle, skipforward, skipback, like, dislike, bookmark - * - * @param {any} id - For example, 'play', 'pause', 'volup' or 'voldown' - * @url http://www.espruino.com/Reference#l_NRF_amsCommand - */ - static amsCommand(id: any): void; - - /** - * Search for available devices matching the given filters. Since we have no UI - * here, Espruino will pick the FIRST device it finds, or it'll call `catch`. - * `options` can have the following fields: - * * `filters` - a list of filters that a device must match before it is returned - * (see below) - * * `timeout` - the maximum time to scan for in milliseconds (scanning stops when - * a match is found. eg. `NRF.requestDevice({ timeout:2000, filters: [ ... ] })` - * * `active` - whether to perform active scanning (requesting 'scan response' - * packets from any devices that are found). eg. `NRF.requestDevice({ active:true, - * filters: [ ... ] })` - * * `phy` - (NRF52840 only) use the long-range coded phy (`"1mbps"` default, can - * be `"1mbps/2mbps/both/coded"`) - * * `extended` - (NRF52840 only) support receiving extended-length advertising - * packets (default=true if phy isn't `"1mbps"`) - * **NOTE:** `timeout` and `active` are not part of the Web Bluetooth standard. - * The following filter types are implemented: - * * `services` - list of services as strings (all of which must match). 128 bit - * services must be in the form '01230123-0123-0123-0123-012301230123' - * * `name` - exact device name - * * `namePrefix` - starting characters of device name - * * `id` - exact device address (`id:"e9:53:86:09:89:99 random"`) (this is - * Espruino-specific, and is not part of the Web Bluetooth spec) - * * `serviceData` - an object containing service characteristics which must all - * match (`serviceData:{"1809":{}}`). Matching of actual service data is not - * supported yet. - * * `manufacturerData` - an object containing manufacturer UUIDs which must all - * match (`manufacturerData:{0x0590:{}}`). Matching of actual manufacturer data - * is not supported yet. - * ``` - * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) { ... }); - * // or - * NRF.requestDevice({ filters: [{ services: ['1823'] }] }).then(function(device) { ... }); - * // or - * NRF.requestDevice({ filters: [{ manufacturerData:{0x0590:{}} }] }).then(function(device) { ... }); - * ``` - * As a full example, to send data to another Puck.js to turn an LED on: - * ``` - * var gatt; - * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) { - * return device.gatt.connect(); - * }).then(function(g) { - * gatt = g; - * return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); - * }).then(function(service) { - * return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); - * }).then(function(characteristic) { - * return characteristic.writeValue("LED1.set()\n"); - * }).then(function() { - * gatt.disconnect(); - * console.log("Done!"); - * }); - * ``` - * Or slightly more concisely, using ES6 arrow functions: - * ``` - * var gatt; - * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }]}).then( - * device => device.gatt.connect()).then( - * g => (gatt=g).getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e")).then( - * service => service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e")).then( - * characteristic => characteristic.writeValue("LED1.reset()\n")).then( - * () => { gatt.disconnect(); console.log("Done!"); } ); - * ``` - * Note that you have to keep track of the `gatt` variable so that you can - * disconnect the Bluetooth connection when you're done. - * **Note:** Using a filter in `NRF.requestDevice` filters each advertising packet - * individually. As soon as a matching advertisement is received, - * `NRF.requestDevice` resolves the promise and stops scanning. This means that if - * you filter based on a service UUID and a device advertises with multiple packets - * (or a scan response when `active:true`) only the packet matching the filter is - * returned - you may not get the device's name is that was in a separate packet. - * To aggregate multiple packets you can use `NRF.findDevices`. - * - * @param {any} options - Options used to filter the device to use - * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete - * @url http://www.espruino.com/Reference#l_NRF_requestDevice - */ - static requestDevice(options?: { filters?: NRFFilters, timeout?: number, active?: boolean, phy?: string, extended?: boolean }): Promise; - - /** - * Connect to a BLE device by MAC address. Returns a promise, the argument of which - * is the `BluetoothRemoteGATTServer` connection. - * ``` - * NRF.connect("aa:bb:cc:dd:ee").then(function(server) { - * // ... - * }); - * ``` - * This has the same effect as calling `BluetoothDevice.gatt.connect` on a - * `BluetoothDevice` requested using `NRF.requestDevice`. It just allows you to - * specify the address directly (without having to scan). - * You can use it as follows - this would connect to another Puck device and turn - * its LED on: - * ``` - * var gatt; - * NRF.connect("aa:bb:cc:dd:ee random").then(function(g) { - * gatt = g; - * return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); - * }).then(function(service) { - * return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); - * }).then(function(characteristic) { - * return characteristic.writeValue("LED1.set()\n"); - * }).then(function() { - * gatt.disconnect(); - * console.log("Done!"); - * }); - * ``` - * **Note:** Espruino Bluetooth devices use a type of BLE address known as 'random - * static', which is different to a 'public' address. To connect to an Espruino - * device you'll need to use an address string of the form `"aa:bb:cc:dd:ee - * random"` rather than just `"aa:bb:cc:dd:ee"`. If you scan for devices with - * `NRF.findDevices`/`NRF.setScan` then addresses are already reported in the - * correct format. - * - * @param {any} mac - The MAC address to connect to - * @param {any} options - (Espruino-specific) An object of connection options (see `BluetoothRemoteGATTServer.connect` for full details) - * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete - * @url http://www.espruino.com/Reference#l_NRF_connect - */ - static connect(mac: any, options: any): Promise; - - /** - * If set to true, whenever a device bonds it will be added to the whitelist. - * When set to false, the whitelist is cleared and newly bonded devices will not be - * added to the whitelist. - * **Note:** This is remembered between `reset()`s but isn't remembered after - * power-on (you'll have to add it to `onInit()`. - * - * @param {boolean} whitelisting - Are we using a whitelist? (default false) - * @url http://www.espruino.com/Reference#l_NRF_setWhitelist - */ - static setWhitelist(whitelisting: boolean): void; - - /** - * When connected, Bluetooth LE devices communicate at a set interval. Lowering the - * interval (eg. more packets/second) means a lower delay when sending data, higher - * bandwidth, but also more power consumption. - * By default, when connected as a peripheral Espruino automatically adjusts the - * connection interval. When connected it's as fast as possible (7.5ms) but when - * idle for over a minute it drops to 200ms. On continued activity (>1 BLE - * operation) the interval is raised to 7.5ms again. - * The options for `interval` are: - * * `undefined` / `"auto"` : (default) automatically adjust connection interval - * * `100` : set min and max connection interval to the same number (between 7.5ms - * and 4000ms) - * * `{minInterval:20, maxInterval:100}` : set min and max connection interval as a - * range - * This configuration is not remembered during a `save()` - you will have to re-set - * it via `onInit`. - * **Note:** If connecting to another device (as Central), you can use an extra - * argument to `NRF.connect` or `BluetoothRemoteGATTServer.connect` to specify a - * connection interval. - * **Note:** This overwrites any changes imposed by the deprecated - * `NRF.setLowPowerConnection` - * - * @param {any} interval - The connection interval to use (see below) - * @url http://www.espruino.com/Reference#l_NRF_setConnectionInterval - */ - static setConnectionInterval(interval: any): void; - - /** - * Sets the security options used when connecting/pairing. This applies to both - * central *and* peripheral mode. - * ``` - * NRF.setSecurity({ - * display : bool // default false, can this device display a passkey - * // - sent via the `BluetoothDevice.passkey` event - * keyboard : bool // default false, can this device enter a passkey - * // - request sent via the `BluetoothDevice.passkeyRequest` event - * bond : bool // default true, Perform bonding - * mitm : bool // default false, Man In The Middle protection - * lesc : bool // default false, LE Secure Connections - * passkey : // default "", or a 6 digit passkey to use - * oob : [0..15] // if specified, Out Of Band pairing is enabled and - * // the 16 byte pairing code supplied here is used - * encryptUart : bool // default false (unless oob or passkey specified) - * // This sets the BLE UART service such that it - * // is encrypted and can only be used from a bonded connection - * }); - * ``` - * **NOTE:** Some combinations of arguments will cause an error. For example - * supplying a passkey without `display:1` is not allowed. If `display:1` is set - * you do not require a physical display, the user just needs to know the passkey - * you supplied. - * For instance, to require pairing and to specify a passkey, use: - * ``` - * NRF.setSecurity({passkey:"123456", mitm:1, display:1}); - * ``` - * However, while most devices will request a passkey for pairing at this point it - * is still possible for a device to connect without requiring one (eg. using the - * 'NRF Connect' app). - * To force a passkey you need to protect each characteristic you define with - * `NRF.setSecurity`. For instance the following code will *require* that the - * passkey `123456` is entered before the characteristic - * `9d020002-bf5f-1d1a-b52a-fe52091d5b12` can be read. - * ``` - * NRF.setSecurity({passkey:"123456", mitm:1, display:1}); - * NRF.setServices({ - * "9d020001-bf5f-1d1a-b52a-fe52091d5b12" : { - * "9d020002-bf5f-1d1a-b52a-fe52091d5b12" : { - * // readable always - * value : "Not Secret" - * }, - * "9d020003-bf5f-1d1a-b52a-fe52091d5b12" : { - * // readable only once bonded - * value : "Secret", - * readable : true, - * security: { - * read: { - * mitm: true, - * encrypted: true - * } - * } - * }, - * "9d020004-bf5f-1d1a-b52a-fe52091d5b12" : { - * // readable always - * // writable only once bonded - * value : "Readable", - * readable : true, - * writable : true, - * onWrite : function(evt) { - * console.log("Wrote ", evt.data); - * }, - * security: { - * write: { - * mitm: true, - * encrypted: true - * } - * } - * } - * } - * }); - * ``` - * **Note:** If `passkey` or `oob` is specified, the Nordic UART service (if - * enabled) will automatically be set to require encryption, but otherwise it is - * open. - * - * @param {any} options - An object containing security-related options (see below) - * @url http://www.espruino.com/Reference#l_NRF_setSecurity - */ - static setSecurity(options: any): void; - - /** - * Return an object with information about the security state of the current - * peripheral connection: - * ``` - * { - * connected // The connection is active (not disconnected). - * encrypted // Communication on this link is encrypted. - * mitm_protected // The encrypted communication is also protected against man-in-the-middle attacks. - * bonded // The peer is bonded with us - * connected_addr // If connected=true, the MAC address of the currently connected device - * } - * ``` - * If there is no active connection, `{connected:false}` will be returned. - * See `NRF.setSecurity` for information about negotiating a secure connection. - * @returns {any} An object - * @url http://www.espruino.com/Reference#l_NRF_getSecurityStatus - */ - static getSecurityStatus(): any; - - /** - * - * @param {boolean} forceRepair - True if we should force repairing even if there is already valid pairing info - * @returns {any} A promise - * @url http://www.espruino.com/Reference#l_NRF_startBonding - */ - static startBonding(forceRepair: boolean): any; - - -} - -/** - * @url http://www.espruino.com/Reference#Bluetooth - */ -declare class Bluetooth { - /** - * @url http://www.espruino.com/Reference#l_Bluetooth_setConsole - */ - static setConsole(): void; - - -} - -/** - * A Web Bluetooth-style device - you can request one using - * `NRF.requestDevice(address)` - * For example: - * ``` - * var gatt; - * NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) { - * console.log("found device"); - * return device.gatt.connect(); - * }).then(function(g) { - * gatt = g; - * console.log("connected"); - * return gatt.startBonding(); - * }).then(function() { - * console.log("bonded", gatt.getSecurityStatus()); - * gatt.disconnect(); - * }).catch(function(e) { - * console.log("ERROR",e); - * }); - * ``` - * @url http://www.espruino.com/Reference#BluetoothDevice - */ -declare class BluetoothDevice { - /** - * Called when the device gets disconnected. - * To connect and then print `Disconnected` when the device is disconnected, just - * do the following: - * ``` - * var gatt; - * NRF.connect("aa:bb:cc:dd:ee:ff").then(function(gatt) { - * gatt.device.on('gattserverdisconnected', function(reason) { - * console.log("Disconnected ",reason); - * }); - * }); - * ``` - * Or: - * ``` - * var gatt; - * NRF.requestDevice(...).then(function(device) { - * device.on('gattserverdisconnected', function(reason) { - * console.log("Disconnected ",reason); - * }); - * }); - * ``` - * @param {string} event - The event to listen to. - * @param {(reason: number) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `reason` The reason code reported back by the BLE stack - see Nordic's `ble_hci.h` file for more information - * @url http://www.espruino.com/Reference#l_BluetoothDevice_gattserverdisconnected - */ - static on(event: "gattserverdisconnected", callback: (reason: number) => void): void; - - /** - * Called when the device pairs and sends a passkey that Espruino should display. - * For this to be used, you'll have to specify that there's a display using - * `NRF.setSecurity` - * **This is not part of the Web Bluetooth Specification.** It has been added - * specifically for Espruino. - * @param {string} event - The event to listen to. - * @param {(passkey: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `passkey` A 6 character numeric String to be displayed - * @url http://www.espruino.com/Reference#l_BluetoothDevice_passkey - */ - static on(event: "passkey", callback: (passkey: any) => void): void; - - /** - * Called when the device pairs, displays a passkey, and wants Espruino to tell it - * what the passkey was. - * Respond with `BluetoothDevice.sendPasskey()` with a 6 character string - * containing only `0..9`. - * For this to be used, you'll have to specify that there's a keyboard using - * `NRF.setSecurity` - * **This is not part of the Web Bluetooth Specification.** It has been added - * specifically for Espruino. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_BluetoothDevice_passkeyRequest - */ - static on(event: "passkeyRequest", callback: () => void): void; - - /** - * @returns {any} A `BluetoothRemoteGATTServer` for this device - * @url http://www.espruino.com/Reference#l_BluetoothDevice_gatt - */ - gatt: any; - - /** - * @returns {boolean} The last received RSSI (signal strength) for this device - * @url http://www.espruino.com/Reference#l_BluetoothDevice_rssi - */ - rssi: boolean; - - /** - * To be used as a response when the event `BluetoothDevice.sendPasskey` has been - * received. - * **This is not part of the Web Bluetooth Specification.** It has been added - * specifically for Espruino. - * - * @param {any} passkey - A 6 character numeric String to be returned to the device - * @url http://www.espruino.com/Reference#l_BluetoothDevice_sendPasskey - */ - sendPasskey(passkey: any): void; -} - -/** - * Web Bluetooth-style GATT server - get this using `NRF.connect(address)` or - * `NRF.requestDevice(options)` and `response.gatt.connect` - * https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver - * @url http://www.espruino.com/Reference#BluetoothRemoteGATTServer - */ -declare class BluetoothRemoteGATTServer { - - - /** - * Connect to a BLE device - returns a promise, the argument of which is the - * `BluetoothRemoteGATTServer` connection. - * See [`NRF.requestDevice`](/Reference#l_NRF_requestDevice) for usage examples. - * `options` is an optional object containing: - * ``` - * { - * minInterval // min connection interval in milliseconds, 7.5 ms to 4 s - * maxInterval // max connection interval in milliseconds, 7.5 ms to 4 s - * } - * ``` - * By default the interval is 20-200ms (or 500-1000ms if - * `NRF.setLowPowerConnection(true)` was called. During connection Espruino - * negotiates with the other device to find a common interval that can be used. - * For instance calling: - * ``` - * NRF.requestDevice({ filters: [{ namePrefix: 'Pixl.js' }] }).then(function(device) { - * return device.gatt.connect({minInterval:7.5, maxInterval:7.5}); - * }).then(function(g) { - * ``` - * will force the connection to use the fastest connection interval possible (as - * long as the device at the other end supports it). - * **Note:** The Web Bluetooth spec states that if a device hasn't advertised its - * name, when connected to a device the central (in this case Espruino) should - * automatically retrieve the name from the corresponding characteristic (`0x2a00` - * on service `0x1800`). Espruino does not automatically do this. - * - * @param {any} options - (Espruino-specific) An object of connection options (see below) - * @returns {any} A `Promise` that is resolved (or rejected) when the connection is complete - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_connect - */ - connect(options: any): Promise; - - /** - * @returns {boolean} Whether the device is connected or not - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_connected - */ - connected: boolean; - - /** - * @returns {number} The handle to this device (if it is currently connected) - the handle is an internal value used by the Bluetooth Stack - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_handle - */ - handle: number; - - /** - * Disconnect from a previously connected BLE device connected with - * `BluetoothRemoteGATTServer.connect` - this does not disconnect from something - * that has connected to the Espruino. - * **Note:** While `.disconnect` is standard Web Bluetooth, in the spec it returns - * undefined not a `Promise` for implementation reasons. In Espruino we return a - * `Promise` to make it easier to detect when Espruino is free to connect to - * something else. - * @returns {any} A `Promise` that is resolved (or rejected) when the disconnection is complete (non-standard) - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_disconnect - */ - disconnect(): Promise; - - /** - * Start negotiating bonding (secure communications) with the connected device, and - * return a Promise that is completed on success or failure. - * ``` - * var gatt; - * NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) { - * console.log("found device"); - * return device.gatt.connect(); - * }).then(function(g) { - * gatt = g; - * console.log("connected"); - * return gatt.startBonding(); - * }).then(function() { - * console.log("bonded", gatt.getSecurityStatus()); - * gatt.disconnect(); - * }).catch(function(e) { - * console.log("ERROR",e); - * }); - * ``` - * **This is not part of the Web Bluetooth Specification.** It has been added - * specifically for Espruino. - * - * @param {boolean} forceRePair - If the device is already bonded, re-pair it - * @returns {any} A `Promise` that is resolved (or rejected) when the bonding is complete - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_startBonding - */ - startBonding(forceRePair: boolean): Promise; - - /** - * Return an object with information about the security state of the current - * connection: - * ``` - * { - * connected // The connection is active (not disconnected). - * encrypted // Communication on this link is encrypted. - * mitm_protected // The encrypted communication is also protected against man-in-the-middle attacks. - * bonded // The peer is bonded with us - * } - * ``` - * See `BluetoothRemoteGATTServer.startBonding` for information about negotiating a - * secure connection. - * **This is not part of the Web Bluetooth Specification.** It has been added - * specifically for Puck.js. - * @returns {any} An object - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_getSecurityStatus - */ - getSecurityStatus(): any; - - /** - * See `NRF.connect` for usage examples. - * - * @param {any} service - The service UUID - * @returns {any} A `Promise` that is resolved (or rejected) when the primary service is found (the argument contains a `BluetoothRemoteGATTService`) - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_getPrimaryService - */ - getPrimaryService(service: any): Promise; - - /** - * @returns {any} A `Promise` that is resolved (or rejected) when the primary services are found (the argument contains an array of `BluetoothRemoteGATTService`) - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_getPrimaryServices - */ - getPrimaryServices(): Promise; - - /** - * Start/stop listening for RSSI values on the active GATT connection - * ``` - * // Start listening for RSSI value updates - * gattServer.setRSSIHandler(function(rssi) { - * console.log(rssi); // prints -85 (or similar) - * }); - * // Stop listening - * gattServer.setRSSIHandler(); - * ``` - * RSSI is the 'Received Signal Strength Indication' in dBm - * - * @param {any} callback - The callback to call with the RSSI value, or undefined to stop - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_setRSSIHandler - */ - setRSSIHandler(callback: any): void; -} - -/** - * Web Bluetooth-style GATT service - get this using - * `BluetoothRemoteGATTServer.getPrimaryService(s)` - * https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice - * @url http://www.espruino.com/Reference#BluetoothRemoteGATTService - */ -declare class BluetoothRemoteGATTService { - - - /** - * @returns {any} The `BluetoothDevice` this Service came from - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTService_device - */ - device: any; - - /** - * See `NRF.connect` for usage examples. - * - * @param {any} characteristic - The characteristic UUID - * @returns {any} A `Promise` that is resolved (or rejected) when the characteristic is found (the argument contains a `BluetoothRemoteGATTCharacteristic`) - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTService_getCharacteristic - */ - getCharacteristic(characteristic: any): Promise; - - /** - * @returns {any} A `Promise` that is resolved (or rejected) when the characteristic is found (the argument contains an array of `BluetoothRemoteGATTCharacteristic`) - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTService_getCharacteristics - */ - getCharacteristics(): Promise; -} - -/** - * Web Bluetooth-style GATT characteristic - get this using - * `BluetoothRemoteGATTService.getCharacteristic(s)` - * https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattcharacteristic - * @url http://www.espruino.com/Reference#BluetoothRemoteGATTCharacteristic - */ -declare class BluetoothRemoteGATTCharacteristic { - /** - * Called when a characteristic's value changes, *after* - * `BluetoothRemoteGATTCharacteristic.startNotifications` has been called. - * ``` - * ... - * return service.getCharacteristic("characteristic_uuid"); - * }).then(function(c) { - * c.on('characteristicvaluechanged', function(event) { - * console.log("-> "+event.target.value); - * }); - * return c.startNotifications(); - * }).then(... - * ``` - * The first argument is of the form `{target : - * BluetoothRemoteGATTCharacteristic}`, and - * `BluetoothRemoteGATTCharacteristic.value` will then contain the new value (as a - * DataView). - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_characteristicvaluechanged - */ - static on(event: "characteristicvaluechanged", callback: () => void): void; - - /** - * @returns {any} The `BluetoothRemoteGATTService` this Service came from - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_service - */ - service: any; - - /** - * Write a characteristic's value - * ``` - * var device; - * NRF.connect(device_address).then(function(d) { - * device = d; - * return d.getPrimaryService("service_uuid"); - * }).then(function(s) { - * console.log("Service ",s); - * return s.getCharacteristic("characteristic_uuid"); - * }).then(function(c) { - * return c.writeValue("Hello"); - * }).then(function(d) { - * device.disconnect(); - * }).catch(function() { - * console.log("Something's broken."); - * }); - * ``` - * - * @param {any} data - The data to write - * @returns {any} A `Promise` that is resolved (or rejected) when the characteristic is written - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_writeValue - */ - writeValue(data: any): Promise; - - /** - * Read a characteristic's value, return a promise containing a `DataView` - * ``` - * var device; - * NRF.connect(device_address).then(function(d) { - * device = d; - * return d.getPrimaryService("service_uuid"); - * }).then(function(s) { - * console.log("Service ",s); - * return s.getCharacteristic("characteristic_uuid"); - * }).then(function(c) { - * return c.readValue(); - * }).then(function(d) { - * console.log("Got:", JSON.stringify(d.buffer)); - * device.disconnect(); - * }).catch(function() { - * console.log("Something's broken."); - * }); - * ``` - * @returns {any} A `Promise` that is resolved (or rejected) with a `DataView` when the characteristic is read - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_readValue - */ - readValue(): Promise; - - /** - * Starts notifications - whenever this characteristic's value changes, a - * `characteristicvaluechanged` event is fired and `characteristic.value` will then - * contain the new value as a `DataView`. - * ``` - * var device; - * NRF.connect(device_address).then(function(d) { - * device = d; - * return d.getPrimaryService("service_uuid"); - * }).then(function(s) { - * console.log("Service ",s); - * return s.getCharacteristic("characteristic_uuid"); - * }).then(function(c) { - * c.on('characteristicvaluechanged', function(event) { - * console.log("-> ",event.target.value); // this is a DataView - * }); - * return c.startNotifications(); - * }).then(function(d) { - * console.log("Waiting for notifications"); - * }).catch(function() { - * console.log("Something's broken."); - * }); - * ``` - * For example, to listen to the output of another Puck.js's Nordic Serial port - * service, you can use: - * ``` - * var gatt; - * NRF.connect("pu:ck:js:ad:dr:es random").then(function(g) { - * gatt = g; - * return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); - * }).then(function(service) { - * return service.getCharacteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); - * }).then(function(characteristic) { - * characteristic.on('characteristicvaluechanged', function(event) { - * console.log("RX: "+JSON.stringify(event.target.value.buffer)); - * }); - * return characteristic.startNotifications(); - * }).then(function() { - * console.log("Done!"); - * }); - * ``` - * @returns {any} A `Promise` that is resolved (or rejected) with data when notifications have been added - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_startNotifications - */ - startNotifications(): Promise; - - /** - * Stop notifications (that were requested with - * `BluetoothRemoteGATTCharacteristic.startNotifications`) - * @returns {any} A `Promise` that is resolved (or rejected) with data when notifications have been removed - * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_stopNotifications - */ - stopNotifications(): Promise; -} - -/** - * Class containing utility functions for the [Bangle.js Smart - * Watch](http://www.espruino.com/Bangle.js) - * @url http://www.espruino.com/Reference#Bangle - */ -declare class Bangle { - /** - * Accelerometer data available with `{x,y,z,diff,mag}` object as a parameter. - * * `x` is X axis (left-right) in `g` - * * `y` is Y axis (up-down) in `g` - * * `z` is Z axis (in-out) in `g` - * * `diff` is difference between this and the last reading in `g` - * * `mag` is the magnitude of the acceleration in `g` - * You can also retrieve the most recent reading with `Bangle.getAccel()`. - * @param {string} event - The event to listen to. - * @param {(xyz: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `xyz` - * @url http://www.espruino.com/Reference#l_Bangle_accel - */ - static on(event: "accel", callback: (xyz: AccelData) => void): void; - - /** - * Called whenever a step is detected by Bangle.js's pedometer. - * @param {string} event - The event to listen to. - * @param {(up: number) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `up` The number of steps since Bangle.js was last reset - * @url http://www.espruino.com/Reference#l_Bangle_step - */ - static on(event: "step", callback: (up: number) => void): void; - - /** - * See `Bangle.getHealthStatus()` for more information. This is used for health - * tracking to allow Bangle.js to record historical exercise data. - * @param {string} event - The event to listen to. - * @param {(info: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `info` An object containing the last 10 minutes health data - * @url http://www.espruino.com/Reference#l_Bangle_health - */ - static on(event: "health", callback: (info: HealthStatus) => void): void; - - /** - * Has the watch been moved so that it is face-up, or not face up? - * @param {string} event - The event to listen to. - * @param {(up: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `up` `true` if face-up - * @url http://www.espruino.com/Reference#l_Bangle_faceUp - */ - static on(event: "faceUp", callback: (up: boolean) => void): void; - - /** - * This event happens when the watch has been twisted around it's axis - for - * instance as if it was rotated so someone could look at the time. - * To tweak when this happens, see the `twist*` options in `Bangle.setOptions()` - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_Bangle_twist - */ - static on(event: "twist", callback: () => void): void; - - /** - * Is the battery charging or not? - * @param {string} event - The event to listen to. - * @param {(charging: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `charging` `true` if charging - * @url http://www.espruino.com/Reference#l_Bangle_charging - */ - static on(event: "charging", callback: (charging: boolean) => void): void; - - /** - * Magnetometer/Compass data available with `{x,y,z,dx,dy,dz,heading}` object as a - * parameter - * * `x/y/z` raw x,y,z magnetometer readings - * * `dx/dy/dz` readings based on calibration since magnetometer turned on - * * `heading` in degrees based on calibrated readings (will be NaN if magnetometer - * hasn't been rotated around 360 degrees) - * To get this event you must turn the compass on with `Bangle.setCompassPower(1)`. - * You can also retrieve the most recent reading with `Bangle.getCompass()`. - * @param {string} event - The event to listen to. - * @param {(xyz: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `xyz` - * @url http://www.espruino.com/Reference#l_Bangle_mag - */ - static on(event: "mag", callback: (xyz: CompassData) => void): void; - - /** - * Raw NMEA GPS / u-blox data messages received as a string - * To get this event you must turn the GPS on with `Bangle.setGPSPower(1)`. - * @param {string} event - The event to listen to. - * @param {(nmea: any, dataLoss: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `nmea` A string containing the raw NMEA data from the GPS - * * `dataLoss` This is set to true if some lines of GPS data have previously been lost (eg because system was too busy to queue up a GPS-raw event) - * @url http://www.espruino.com/Reference#l_Bangle_GPS-raw - */ - static on(event: "GPS-raw", callback: (nmea: string, dataLoss: boolean) => void): void; - - /** - * GPS data, as an object. Contains: - * ``` - * { "lat": number, // Latitude in degrees - * "lon": number, // Longitude in degrees - * "alt": number, // altitude in M - * "speed": number, // Speed in kph - * "course": number, // Course in degrees - * "time": Date, // Current Time (or undefined if not known) - * "satellites": 7, // Number of satellites - * "fix": 1 // NMEA Fix state - 0 is no fix - * "hdop": number, // Horizontal Dilution of Precision - * } - * ``` - * If a value such as `lat` is not known because there is no fix, it'll be `NaN`. - * `hdop` is a value from the GPS receiver that gives a rough idea of accuracy of - * lat/lon based on the geometry of the satellites in range. Multiply by 5 to get a - * value in meters. This is just a ballpark estimation and should not be considered - * remotely accurate. - * To get this event you must turn the GPS on with `Bangle.setGPSPower(1)`. - * @param {string} event - The event to listen to. - * @param {(fix: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `fix` An object with fix info (see below) - * @url http://www.espruino.com/Reference#l_Bangle_GPS - */ - static on(event: "GPS", callback: (fix: GPSFix) => void): void; - - /** - * Heat rate data, as an object. Contains: - * ``` - * { "bpm": number, // Beats per minute - * "confidence": number, // 0-100 percentage confidence in the heart rate - * "raw": Uint8Array, // raw samples from heart rate monitor - * } - * ``` - * To get this event you must turn the heart rate monitor on with - * `Bangle.setHRMPower(1)`. - * @param {string} event - The event to listen to. - * @param {(hrm: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `hrm` An object with heart rate info (see below) - * @url http://www.espruino.com/Reference#l_Bangle_HRM - */ - static on(event: "HRM", callback: (hrm: { bpm: number, confidence: number, raw: Uint8Array }) => void): void; - - /** - * Called when heart rate sensor data is available - see `Bangle.setHRMPower(1)`. - * `hrm` is of the form: - * ``` - * { "raw": -1, // raw value from sensor - * "filt": -1, // bandpass-filtered raw value from sensor - * "bpm": 88.9, // last BPM value measured - * "confidence": 0 // confidence in the BPM value - * } - * ``` - * @param {string} event - The event to listen to. - * @param {(hrm: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `hrm` A object containing instant readings from the heart rate sensor - * @url http://www.espruino.com/Reference#l_Bangle_HRM-raw - */ - static on(event: "HRM-raw", callback: (hrm: { raw: number, filt: number, bpm: number, confidence: number }) => void): void; - - /** - * When `Bangle.setBarometerPower(true)` is called, this event is fired containing - * barometer readings. - * Same format as `Bangle.getPressure()` - * @param {string} event - The event to listen to. - * @param {(e: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `e` An object containing `{temperature,pressure,altitude}` - * @url http://www.espruino.com/Reference#l_Bangle_pressure - */ - static on(event: "pressure", callback: (e: PressureData) => void): void; - - /** - * Has the screen been turned on or off? Can be used to stop tasks that are no - * longer useful if nothing is displayed. Also see `Bangle.isLCDOn()` - * @param {string} event - The event to listen to. - * @param {(on: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `on` `true` if screen is on - * @url http://www.espruino.com/Reference#l_Bangle_lcdPower - */ - static on(event: "lcdPower", callback: (on: boolean) => void): void; - - /** - * Has the screen been locked? Also see `Bangle.isLocked()` - * @param {string} event - The event to listen to. - * @param {(on: boolean) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `on` `true` if screen is locked, `false` if it is unlocked and touchscreen/buttons will work - * @url http://www.espruino.com/Reference#l_Bangle_lock - */ - static on(event: "lock", callback: (on: boolean) => void): void; - - /** - * If the watch is tapped, this event contains information on the way it was - * tapped. - * `dir` reports the side of the watch that was tapped (not the direction it was - * tapped in). - * ``` - * { - * dir : "left/right/top/bottom/front/back", - * double : true/false // was this a double-tap? - * x : -2 .. 2, // the axis of the tap - * y : -2 .. 2, // the axis of the tap - * z : -2 .. 2 // the axis of the tap - * ``` - * @param {string} event - The event to listen to. - * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `data` `{dir, double, x, y, z}` - * @url http://www.espruino.com/Reference#l_Bangle_tap - */ - static on(event: "tap", callback: (data: { dir: "left" | "right" | "top" | "bottom" | "front" | "back", double: boolean, x: TapAxis, y: TapAxis, z: TapAxis }) => void): void; - - /** - * Emitted when a 'gesture' (fast movement) is detected - * @param {string} event - The event to listen to. - * @param {(xyz: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `xyz` An Int8Array of XYZXYZXYZ data - * @url http://www.espruino.com/Reference#l_Bangle_gesture - */ - static on(event: "gesture", callback: (xyz: Int8Array) => void): void; - - /** - * Emitted when a 'gesture' (fast movement) is detected, and a Tensorflow model is - * in storage in the `".tfmodel"` file. - * If a `".tfnames"` file is specified as a comma-separated list of names, it will - * be used to decode `gesture` from a number into a string. - * @param {string} event - The event to listen to. - * @param {(gesture: any, weights: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `gesture` The name of the gesture (if '.tfnames' exists, or the index. 'undefined' if not matching - * * `weights` An array of floating point values output by the model - * @url http://www.espruino.com/Reference#l_Bangle_aiGesture - */ - static on(event: "aiGesture", callback: (gesture: string | undefined, weights: number[]) => void): void; - - /** - * Emitted when a swipe on the touchscreen is detected (a movement from - * left->right, right->left, down->up or up->down) - * Bangle.js 1 is only capable of detecting left/right swipes as it only contains a - * 2 zone touchscreen. - * @param {string} event - The event to listen to. - * @param {(directionLR: number, directionUD: number) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `directionLR` `-1` for left, `1` for right, `0` for up/down - * * `directionUD` `-1` for up, `1` for down, `0` for left/right (Bangle.js 2 only) - * @url http://www.espruino.com/Reference#l_Bangle_swipe - */ - static on(event: "swipe", callback: SwipeCallback): void; - - /** - * Emitted when the touchscreen is pressed - * @param {string} event - The event to listen to. - * @param {(button: number, xy: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `button` `1` for left, `2` for right - * * `xy` Object of form `{x,y}` containing touch coordinates (if the device supports full touch). Clipped to 0..175 (LCD pixel coordinates) on firmware 2v13 and later. - * @url http://www.espruino.com/Reference#l_Bangle_touch - */ - static on(event: "touch", callback: TouchCallback): void; - - /** - * Emitted when the touchscreen is dragged or released - * The touchscreen extends past the edge of the screen and while `x` and `y` - * coordinates are arranged such that they align with the LCD's pixels, if your - * finger goes towards the edge of the screen, `x` and `y` could end up larger than - * 175 (the screen's maximum pixel coordinates) or smaller than 0. Coordinates from - * the `touch` event are clipped. - * @param {string} event - The event to listen to. - * @param {(event: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `event` Object of form `{x,y,dx,dy,b}` containing touch coordinates, difference in touch coordinates, and an integer `b` containing number of touch points (currently 1 or 0) - * @url http://www.espruino.com/Reference#l_Bangle_drag - */ - static on(event: "drag", callback: DragCallback): void; - - /** - * Emitted when the touchscreen is dragged for a large enough distance to count as - * a gesture. - * If Bangle.strokes is defined and populated with data from `Unistroke.new`, the - * `event` argument will also contain a `stroke` field containing the most closely - * matching stroke name. - * For example: - * ``` - * Bangle.strokes = { - * up : Unistroke.new(new Uint8Array([57, 151, ... 158, 137])), - * alpha : Unistroke.new(new Uint8Array([161, 55, ... 159, 161])), - * }; - * Bangle.on('stroke',o=>{ - * print(o.stroke); - * g.clear(1).drawPoly(o.xy); - * }); - * // Might print something like - * { - * "xy": new Uint8Array([149, 50, ... 107, 136]), - * "stroke": "alpha" - * } - * ``` - * @param {string} event - The event to listen to. - * @param {(event: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `event` Object of form `{xy:Uint8Array([x1,y1,x2,y2...])}` containing touch coordinates - * @url http://www.espruino.com/Reference#l_Bangle_stroke - */ - static on(event: "stroke", callback: (event: { xy: Uint8Array, stroke?: string }) => void): void; - - /** - * Emitted at midnight (at the point the `day` health info is reset to 0). - * Can be used for housekeeping tasks that don't want to be run during the day. - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_Bangle_midnight - */ - static on(event: "midnight", callback: () => void): void; - - /** - * This function can be used to turn Bangle.js's LCD off or on. - * This function resets the Bangle's 'activity timer' (like pressing a button or - * the screen would) so after a time period of inactivity set by - * `Bangle.setLCDTimeout` the screen will turn off. - * If you want to keep the screen on permanently (until apps are changed) you can - * do: - * ``` - * Bangle.setLCDTimeout(0); // turn off the timeout - * Bangle.setLCDPower(1); // keep screen on - * ``` - * **When on full, the LCD draws roughly 40mA.** You can adjust When brightness - * using `Bangle.setLCDBrightness`. - * - * @param {boolean} isOn - True if the LCD should be on, false if not - * @url http://www.espruino.com/Reference#l_Bangle_setLCDPower - */ - static setLCDPower(isOn: boolean): void; - - /** - * This function can be used to adjust the brightness of Bangle.js's display, and - * hence prolong its battery life. - * Due to hardware design constraints, software PWM has to be used which means that - * the display may flicker slightly when Bluetooth is active and the display is not - * at full power. - * **Power consumption** - * * 0 = 7mA - * * 0.1 = 12mA - * * 0.2 = 18mA - * * 0.5 = 28mA - * * 0.9 = 40mA (switching overhead) - * * 1 = 40mA - * - * @param {number} brightness - The brightness of Bangle.js's display - from 0(off) to 1(on full) - * @url http://www.espruino.com/Reference#l_Bangle_setLCDBrightness - */ - static setLCDBrightness(brightness: number): void; - - /** - * This function can be used to change the way graphics is handled on Bangle.js. - * Available options for `Bangle.setLCDMode` are: - * * `Bangle.setLCDMode()` or `Bangle.setLCDMode("direct")` (the default) - The - * drawable area is 240x240 16 bit. Unbuffered, so draw calls take effect - * immediately. Terminal and vertical scrolling work (horizontal scrolling - * doesn't). - * * `Bangle.setLCDMode("doublebuffered")` - The drawable area is 240x160 16 bit, - * terminal and scrolling will not work. `g.flip()` must be called for draw - * operations to take effect. - * * `Bangle.setLCDMode("120x120")` - The drawable area is 120x120 8 bit, - * `g.getPixel`, terminal, and full scrolling work. Uses an offscreen buffer - * stored on Bangle.js, `g.flip()` must be called for draw operations to take - * effect. - * * `Bangle.setLCDMode("80x80")` - The drawable area is 80x80 8 bit, `g.getPixel`, - * terminal, and full scrolling work. Uses an offscreen buffer stored on - * Bangle.js, `g.flip()` must be called for draw operations to take effect. - * You can also call `Bangle.setLCDMode()` to return to normal, unbuffered - * `"direct"` mode. - * - * @param {any} mode - The LCD mode (See below) - * @url http://www.espruino.com/Reference#l_Bangle_setLCDMode - */ - static setLCDMode(mode?: LCDMode): void; - - /** - * The current LCD mode. - * See `Bangle.setLCDMode` for examples. - * @returns {any} The LCD mode as a String - * @url http://www.espruino.com/Reference#l_Bangle_getLCDMode - */ - static getLCDMode(): LCDMode; - - /** - * This can be used to move the displayed memory area up or down temporarily. It's - * used for displaying notifications while keeping the main display contents - * intact. - * - * @param {number} y - The amount of pixels to shift the LCD up or down - * @url http://www.espruino.com/Reference#l_Bangle_setLCDOffset - */ - static setLCDOffset(y: number): void; - - /** - * This function can be used to turn Bangle.js's LCD power saving on or off. - * With power saving off, the display will remain in the state you set it with - * `Bangle.setLCDPower`. - * With power saving on, the display will turn on if a button is pressed, the watch - * is turned face up, or the screen is updated (see `Bangle.setOptions` for - * configuration). It'll turn off automatically after the given timeout. - * **Note:** This function also sets the Backlight and Lock timeout (the time at - * which the touchscreen/buttons start being ignored). To set both separately, use - * `Bangle.setOptions` - * - * @param {number} isOn - The timeout of the display in seconds, or `0`/`undefined` to turn power saving off. Default is 10 seconds. - * @url http://www.espruino.com/Reference#l_Bangle_setLCDTimeout - */ - static setLCDTimeout(isOn: number): void; - - /** - * Set how often the watch should poll for new acceleration/gyro data and kick the - * Watchdog timer. It isn't recommended that you make this interval much larger - * than 1000ms, but values up to 4000ms are allowed. - * Calling this will set `Bangle.setOptions({powerSave: false})` - disabling the - * dynamic adjustment of poll interval to save battery power when Bangle.js is - * stationary. - * - * @param {number} interval - Polling interval in milliseconds (Default is 80ms - 12.5Hz to match accelerometer) - * @url http://www.espruino.com/Reference#l_Bangle_setPollInterval - */ - static setPollInterval(interval: number): void; - - /** - * Set internal options used for gestures, etc... - * * `wakeOnBTN1` should the LCD turn on when BTN1 is pressed? default = `true` - * * `wakeOnBTN2` (Bangle.js 1) should the LCD turn on when BTN2 is pressed? - * default = `true` - * * `wakeOnBTN3` (Bangle.js 1) should the LCD turn on when BTN3 is pressed? - * default = `true` - * * `wakeOnFaceUp` should the LCD turn on when the watch is turned face up? - * default = `false` - * * `wakeOnTouch` should the LCD turn on when the touchscreen is pressed? default - * = `false` - * * `wakeOnTwist` should the LCD turn on when the watch is twisted? default = - * `true` - * * `twistThreshold` How much acceleration to register a twist of the watch strap? - * Can be negative for opposite direction. default = `800` - * * `twistMaxY` Maximum acceleration in Y to trigger a twist (low Y means watch is - * facing the right way up). default = `-800` - * * `twistTimeout` How little time (in ms) must a twist take from low->high - * acceleration? default = `1000` - * * `gestureStartThresh` how big a difference before we consider a gesture - * started? default = `sqr(800)` - * * `gestureEndThresh` how small a difference before we consider a gesture ended? - * default = `sqr(2000)` - * * `gestureInactiveCount` how many samples do we keep after a gesture has ended? - * default = `4` - * * `gestureMinLength` how many samples must a gesture have before we notify about - * it? default = `10` - * * `powerSave` after a minute of not being moved, Bangle.js will change the - * accelerometer poll interval down to 800ms (10x accelerometer samples). On - * movement it'll be raised to the default 80ms. If `Bangle.setPollInterval` is - * used this is disabled, and for it to work the poll interval must be either - * 80ms or 800ms. default = `true`. Setting `powerSave:false` will disable this - * automatic power saving, but will **not** change the poll interval from its - * current value. If you desire a specific interval (e.g. the default 80ms) you - * must set it manually with `Bangle.setPollInterval(80)` after setting - * `powerSave:false`. - * * `lockTimeout` how many milliseconds before the screen locks - * * `lcdPowerTimeout` how many milliseconds before the screen turns off - * * `backlightTimeout` how many milliseconds before the screen's backlight turns - * off - * * `hrmPollInterval` set the requested poll interval (in milliseconds) for the - * heart rate monitor. On Bangle.js 2 only 10,20,40,80,160,200 ms are supported, - * and polling rate may not be exact. The algorithm's filtering is tuned for - * 20-40ms poll intervals, so higher/lower intervals may effect the reliability - * of the BPM reading. - * * `seaLevelPressure` (Bangle.js 2) Normally 1013.25 millibars - this is used for - * calculating altitude with the pressure sensor - * Where accelerations are used they are in internal units, where `8192 = 1g` - * - * @param {any} options - * @url http://www.espruino.com/Reference#l_Bangle_setOptions - */ - static setOptions(options: { [key in keyof BangleOptions]?: BangleOptions[key] }): void; - - /** - * Return the current state of options as set by `Bangle.setOptions` - * @returns {any} The current state of all options - * @url http://www.espruino.com/Reference#l_Bangle_getOptions - */ - static getOptions(): BangleOptions; - - /** - * Also see the `Bangle.lcdPower` event - * @returns {boolean} Is the display on or not? - * @url http://www.espruino.com/Reference#l_Bangle_isLCDOn - */ - static isLCDOn(): boolean; - - /** - * This function can be used to lock or unlock Bangle.js (e.g. whether buttons and - * touchscreen work or not) - * - * @param {boolean} isLocked - `true` if the Bangle is locked (no user input allowed) - * @url http://www.espruino.com/Reference#l_Bangle_setLocked - */ - static setLocked(isLocked: boolean): void; - - /** - * Also see the `Bangle.lock` event - * @returns {boolean} Is the screen locked or not? - * @url http://www.espruino.com/Reference#l_Bangle_isLocked - */ - static isLocked(): boolean; - - /** - * @returns {boolean} Is the battery charging or not? - * @url http://www.espruino.com/Reference#l_Bangle_isCharging - */ - static isCharging(): boolean; - - /** - * Writes a command directly to the ST7735 LCD controller - * - * @param {number} cmd - * @param {any} data - * @url http://www.espruino.com/Reference#l_Bangle_lcdWr - */ - static lcdWr(cmd: number, data: any): void; - - /** - * Set the power to the Heart rate monitor - * When on, data is output via the `HRM` event on `Bangle`: - * ``` - * Bangle.setHRMPower(true, "myapp"); - * Bangle.on('HRM',print); - * ``` - * *When on, the Heart rate monitor draws roughly 5mA* - * - * @param {boolean} isOn - True if the heart rate monitor should be on, false if not - * @param {any} appID - A string with the app's name in, used to ensure one app can't turn off something another app is using - * @returns {boolean} Is HRM on? - * @url http://www.espruino.com/Reference#l_Bangle_setHRMPower - */ - static setHRMPower(isOn: boolean, appID: string): boolean; - - /** - * Is the Heart rate monitor powered? - * Set power with `Bangle.setHRMPower(...);` - * @returns {boolean} Is HRM on? - * @url http://www.espruino.com/Reference#l_Bangle_isHRMOn - */ - static isHRMOn(): boolean; - - /** - * Set the power to the GPS. - * When on, data is output via the `GPS` event on `Bangle`: - * ``` - * Bangle.setGPSPower(true, "myapp"); - * Bangle.on('GPS',print); - * ``` - * *When on, the GPS draws roughly 20mA* - * - * @param {boolean} isOn - True if the GPS should be on, false if not - * @param {any} appID - A string with the app's name in, used to ensure one app can't turn off something another app is using - * @returns {boolean} Is the GPS on? - * @url http://www.espruino.com/Reference#l_Bangle_setGPSPower - */ - static setGPSPower(isOn: boolean, appID: string): boolean; - - /** - * Is the GPS powered? - * Set power with `Bangle.setGPSPower(...);` - * @returns {boolean} Is the GPS on? - * @url http://www.espruino.com/Reference#l_Bangle_isGPSOn - */ - static isGPSOn(): boolean; - - /** - * Get the last available GPS fix info (or `undefined` if GPS is off). - * The fix info received is the same as you'd get from the `Bangle.GPS` event. - * @returns {any} A GPS fix object with `{lat,lon,...}` - * @url http://www.espruino.com/Reference#l_Bangle_getGPSFix - */ - static getGPSFix(): GPSFix; - - /** - * Set the power to the Compass - * When on, data is output via the `mag` event on `Bangle`: - * ``` - * Bangle.setCompassPower(true, "myapp"); - * Bangle.on('mag',print); - * ``` - * *When on, the compass draws roughly 2mA* - * - * @param {boolean} isOn - True if the Compass should be on, false if not - * @param {any} appID - A string with the app's name in, used to ensure one app can't turn off something another app is using - * @returns {boolean} Is the Compass on? - * @url http://www.espruino.com/Reference#l_Bangle_setCompassPower - */ - static setCompassPower(isOn: boolean, appID: string): boolean; - - /** - * Is the compass powered? - * Set power with `Bangle.setCompassPower(...);` - * @returns {boolean} Is the Compass on? - * @url http://www.espruino.com/Reference#l_Bangle_isCompassOn - */ - static isCompassOn(): boolean; - - /** - * Resets the compass minimum/maximum values. Can be used if the compass isn't - * providing a reliable heading any more. - * - * @url http://www.espruino.com/Reference#l_Bangle_resetCompass - */ - static resetCompass(): void; - - /** - * Set the power to the barometer IC. Once enabled, `Bangle.pressure` events are - * fired each time a new barometer reading is available. - * When on, the barometer draws roughly 50uA - * - * @param {boolean} isOn - True if the barometer IC should be on, false if not - * @param {any} appID - A string with the app's name in, used to ensure one app can't turn off something another app is using - * @returns {boolean} Is the Barometer on? - * @url http://www.espruino.com/Reference#l_Bangle_setBarometerPower - */ - static setBarometerPower(isOn: boolean, appID: string): boolean; - - /** - * Is the Barometer powered? - * Set power with `Bangle.setBarometerPower(...);` - * @returns {boolean} Is the Barometer on? - * @url http://www.espruino.com/Reference#l_Bangle_isBarometerOn - */ - static isBarometerOn(): boolean; - - /** - * Returns the current amount of steps recorded by the step counter - * @returns {number} The number of steps recorded by the step counter - * @url http://www.espruino.com/Reference#l_Bangle_getStepCount - */ - static getStepCount(): number; - - /** - * Sets the current value of the step counter - * - * @param {number} count - The value with which to reload the step counter - * @url http://www.espruino.com/Reference#l_Bangle_setStepCount - */ - static setStepCount(count: number): void; - - /** - * Get the most recent Magnetometer/Compass reading. Data is in the same format as - * the `Bangle.on('mag',` event. - * Returns an `{x,y,z,dx,dy,dz,heading}` object - * * `x/y/z` raw x,y,z magnetometer readings - * * `dx/dy/dz` readings based on calibration since magnetometer turned on - * * `heading` in degrees based on calibrated readings (will be NaN if magnetometer - * hasn't been rotated around 360 degrees) - * To get this event you must turn the compass on with `Bangle.setCompassPower(1)`. - * @returns {any} An object containing magnetometer readings (as below) - * @url http://www.espruino.com/Reference#l_Bangle_getCompass - */ - static getCompass(): CompassData; - - /** - * Get the most recent accelerometer reading. Data is in the same format as the - * `Bangle.on('accel',` event. - * * `x` is X axis (left-right) in `g` - * * `y` is Y axis (up-down) in `g` - * * `z` is Z axis (in-out) in `g` - * * `diff` is difference between this and the last reading in `g` (calculated by - * comparing vectors, not magnitudes) - * * `td` is the elapsed - * * `mag` is the magnitude of the acceleration in `g` - * @returns {any} An object containing accelerometer readings (as below) - * @url http://www.espruino.com/Reference#l_Bangle_getAccel - */ - static getAccel(): AccelData & { td: number }; - - /** - * `range` is one of: - * * `undefined` or `'current'` - health data so far in the last 10 minutes is - * returned, - * * `'last'` - health data during the last 10 minutes - * * `'day'` - the health data so far for the day - * `getHealthStatus` returns an object containing: - * * `movement` is the 32 bit sum of all `acc.diff` readings since power on (and - * rolls over). It is the difference in accelerometer values as `g*8192` - * * `steps` is the number of steps during this period - * * `bpm` the best BPM reading from HRM sensor during this period - * * `bpmConfidence` best BPM confidence (0-100%) during this period - * - * @param {any} range - What time period to return data for, see below: - * @returns {any} Returns an object containing various health info - * @url http://www.espruino.com/Reference#l_Bangle_getHealthStatus - */ - static getHealthStatus(range?: "current" | "last" | "day"): HealthStatus; + static I2C: any; /** - * Reads debug info * @returns {any} - * @url http://www.espruino.com/Reference#l_Bangle_dbg + * @url http://www.espruino.com/Reference#l_WioLTE_UART */ - static dbg(): any; + static UART: any; /** - * Writes a register on the accelerometer - * - * @param {number} reg - * @param {number} data - * @url http://www.espruino.com/Reference#l_Bangle_accelWr - */ - static accelWr(reg: number, data: number): void; - - /** - * Reads a register from the accelerometer - * **Note:** On Espruino 2v06 and before this function only returns a number (`cnt` - * is ignored). - * - * @param {number} reg - * @param {number} cnt - If specified, returns an array of the given length (max 128). If not (or 0) it returns a number * @returns {any} - * @url http://www.espruino.com/Reference#l_Bangle_accelRd + * @url http://www.espruino.com/Reference#l_WioLTE_A4 */ - static accelRd(reg: number, cnt?: 0): number; - static accelRd(reg: number, cnt: number): number[]; + static A4: any; - /** - * Writes a register on the barometer IC - * - * @param {number} reg - * @param {number} data - * @url http://www.espruino.com/Reference#l_Bangle_barometerWr - */ - static barometerWr(reg: number, data: number): void; - /** - * Reads a register from the barometer IC - * - * @param {number} reg - * @param {number} cnt - If specified, returns an array of the given length (max 128). If not (or 0) it returns a number - * @returns {any} - * @url http://www.espruino.com/Reference#l_Bangle_barometerRd - */ - static barometerRd(reg: number, cnt?: 0): number; - static barometerRd(reg: number, cnt: number): number[]; - - /** - * Writes a register on the Magnetometer/Compass - * - * @param {number} reg - * @param {number} data - * @url http://www.espruino.com/Reference#l_Bangle_compassWr - */ - static compassWr(reg: number, data: number): void; - - /** - * Read a register on the Magnetometer/Compass - * - * @param {number} reg - * @param {number} cnt - If specified, returns an array of the given length (max 128). If not (or 0) it returns a number - * @returns {any} - * @url http://www.espruino.com/Reference#l_Bangle_compassRd - */ - static compassRd(reg: number, cnt?: 0): number; - static compassRd(reg: number, cnt: number): number[]; - - /** - * Writes a register on the Heart rate monitor - * - * @param {number} reg - * @param {number} data - * @url http://www.espruino.com/Reference#l_Bangle_hrmWr - */ - static hrmWr(reg: number, data: number): void; - - /** - * Read a register on the Heart rate monitor - * - * @param {number} reg - * @param {number} cnt - If specified, returns an array of the given length (max 128). If not (or 0) it returns a number - * @returns {any} - * @url http://www.espruino.com/Reference#l_Bangle_hrmRd - */ - static hrmRd(reg: number, cnt?: 0): number; - static hrmRd(reg: number, cnt: number): number[]; - - /** - * Changes a pin state on the IO expander - * - * @param {number} mask - * @param {number} isOn - * @url http://www.espruino.com/Reference#l_Bangle_ioWr - */ - static ioWr(mask: number, isOn: number): void; - - /** - * Read temperature, pressure and altitude data. A promise is returned which will - * be resolved with `{temperature, pressure, altitude}`. - * If the Barometer has been turned on with `Bangle.setBarometerPower` then this - * will return almost immediately with the reading. If the Barometer is off, - * conversions take between 500-750ms. - * Altitude assumes a sea-level pressure of 1013.25 hPa - * ``` - * Bangle.getPressure().then(d=>{ - * console.log(d); - * // {temperature, pressure, altitude} - * }); - * ``` - * @returns {any} A promise that will be resolved with `{temperature, pressure, altitude}` - * @url http://www.espruino.com/Reference#l_Bangle_getPressure - */ - static getPressure(): PressureData; - - /** - * Perform a Spherical [Web Mercator - * projection](https://en.wikipedia.org/wiki/Web_Mercator_projection) of latitude - * and longitude into `x` and `y` coordinates, which are roughly equivalent to - * meters from `{lat:0,lon:0}`. - * This is the formula used for most online mapping and is a good way to compare - * GPS coordinates to work out the distance between them. - * - * @param {any} latlong - `{lat:..., lon:...}` - * @returns {any} {x:..., y:...} - * @url http://www.espruino.com/Reference#l_Bangle_project - */ - static project(latlong: { lat: number, lon: number }): { x: number, y: number }; - - /** - * Use the piezo speaker to Beep for a certain time period and frequency - * - * @param {number} [time] - [optional] Time in ms (default 200) - * @param {number} [freq] - [optional] Frequency in hz (default 4000) - * @returns {any} A promise, completed when beep is finished - * @url http://www.espruino.com/Reference#l_Bangle_beep - */ - static beep(time?: number, freq?: number): Promise; - - /** - * Use the vibration motor to buzz for a certain time period - * - * @param {number} [time] - [optional] Time in ms (default 200) - * @param {number} [strength] - [optional] Power of vibration from 0 to 1 (Default 1) - * @returns {any} A promise, completed when vibration is finished - * @url http://www.espruino.com/Reference#l_Bangle_buzz - */ - static buzz(time?: number, strength?: number): Promise; - - /** - * Turn Bangle.js off. It can only be woken by pressing BTN1. - * @url http://www.espruino.com/Reference#l_Bangle_off - */ - static off(): void; - - /** - * Turn Bangle.js (mostly) off, but keep the CPU in sleep mode until BTN1 is - * pressed to preserve the RTC (current time). - * @url http://www.espruino.com/Reference#l_Bangle_softOff - */ - static softOff(): void; - - /** - * * On platforms with an LCD of >=8bpp this is 222 x 104 x 2 bits - * * Otherwise it's 119 x 56 x 1 bits - * @returns {any} An image to be used with `g.drawImage` (as a String) - * @url http://www.espruino.com/Reference#l_Bangle_getLogo - */ - static getLogo(): string; - - /** - * Load all widgets from flash Storage. Call this once at the beginning of your - * application if you want any on-screen widgets to be loaded. - * They will be loaded into a global `WIDGETS` array, and can be rendered with - * `Bangle.drawWidgets`. - * @url http://www.espruino.com/Reference#l_Bangle_loadWidgets - */ - static loadWidgets(): void; - - /** - * Draw any onscreen widgets that were loaded with `Bangle.loadWidgets()`. - * Widgets should redraw themselves when something changes - you'll only need to - * call drawWidgets if you decide to clear the entire screen with `g.clear()`. - * @url http://www.espruino.com/Reference#l_Bangle_drawWidgets - */ - static drawWidgets(): void; - - /** - * @url http://www.espruino.com/Reference#l_Bangle_drawWidgets - */ - static drawWidgets(): void; - - /** - * Load the Bangle.js app launcher, which will allow the user to select an - * application to launch. - * @url http://www.espruino.com/Reference#l_Bangle_showLauncher - */ - static showLauncher(): void; - - /** - * This puts Bangle.js into the specified UI input mode, and calls the callback - * provided when there is user input. - * Currently supported interface types are: - * * 'updown' - UI input with upwards motion `cb(-1)`, downwards motion `cb(1)`, - * and select `cb()` - * * Bangle.js 1 uses BTN1/3 for up/down and BTN2 for select - * * Bangle.js 2 uses touchscreen swipe up/down and tap - * * 'leftright' - UI input with left motion `cb(-1)`, right motion `cb(1)`, and - * select `cb()` - * * Bangle.js 1 uses BTN1/3 for left/right and BTN2 for select - * * Bangle.js 2 uses touchscreen swipe left/right and tap/BTN1 for select - * * 'clock' - called for clocks. Sets `Bangle.CLOCK=1` and allows a button to - * start the launcher - * * Bangle.js 1 BTN2 starts the launcher - * * Bangle.js 2 BTN1 starts the launcher - * * 'clockupdown' - called for clocks. Sets `Bangle.CLOCK=1`, allows a button to - * start the launcher, but also provides up/down functionality - * * Bangle.js 1 BTN2 starts the launcher, BTN1/BTN3 call `cb(-1)` and `cb(1)` - * * Bangle.js 2 BTN1 starts the launcher, touchscreen tap in top/bottom right - * hand side calls `cb(-1)` and `cb(1)` - * * `{mode:"custom", ...}` allows you to specify custom handlers for different - * interactions. See below. - * * `undefined` removes all user interaction code - * While you could use setWatch/etc manually, the benefit here is that you don't - * end up with multiple `setWatch` instances, and the actual input method (touch, - * or buttons) is implemented dependent on the watch (Bangle.js 1 or 2) - * **Note:** You can override this function in boot code to change the interaction - * mode with the watch. For instance you could make all clocks start the launcher - * with a swipe by using: - * ``` - * (function() { - * var sui = Bangle.setUI; - * Bangle.setUI = function(mode, cb) { - * if (mode!="clock") return sui(mode,cb); - * sui(); // clear - * Bangle.CLOCK=1; - * Bangle.swipeHandler = Bangle.showLauncher; - * Bangle.on("swipe", Bangle.swipeHandler); - * }; - * })(); - * ``` - * The first argument can also be an object, in which case more options can be - * specified: - * ``` - * Bangle.setUI({ - * mode : "custom", - * back : function() {}, // optional - add a 'back' icon in top-left widget area and call this function when it is pressed - * touch : function(n,e) {}, // optional - handler for 'touch' events - * swipe : function(dir) {}, // optional - handler for 'swipe' events - * drag : function(e) {}, // optional - handler for 'drag' events (Bangle.js 2 only) - * btn : function(n) {}, // optional - handler for 'button' events (n==1 on Bangle.js 2, n==1/2/3 depending on button for Bangle.js 1) - * clock : 0 // optional - if set the behavior of 'clock' mode is added (does not override btn if defined) - * }); - * ``` - * - * @param {any} type - The type of UI input: 'updown', 'leftright', 'clock', 'clockupdown' or undefined to cancel. Can also be an object (see below) - * @param {any} callback - A function with one argument which is the direction - * @url http://www.espruino.com/Reference#l_Bangle_setUI - */ - static setUI(type?: "updown" | "leftright" | "clock" | "clockupdown" | { mode: "custom"; back?: () => void; touch?: TouchCallback; swipe?: SwipeCallback; drag?: DragCallback; btn?: (n: number) => void, clock?: boolean }, callback?: (direction?: -1 | 1) => void): void; - - /** - * @url http://www.espruino.com/Reference#l_Bangle_setUI - */ - static setUI(): void; - - /** - * Erase all storage and reload it with the default contents. - * This is only available on Bangle.js 2.0. On Bangle.js 1.0 you need to use - * `Install Default Apps` under the `More...` tab of http://banglejs.com/apps - * @url http://www.espruino.com/Reference#l_Bangle_factoryReset - */ - static factoryReset(): void; - - /** - * Returns the rectangle on the screen that is currently reserved for the app. - * @returns {any} An object of the form `{x,y,w,h,x2,y2}` - * @url http://www.espruino.com/Reference#l_Bangle_appRect - */ - static appRect: { x: number, y: number, w: number, h: number, x2: number, y2: number }; - - static CLOCK: boolean; - static strokes: undefined | { [key: string]: Unistroke }; } -interface DateConstructor { +/** + * This class handles waveforms. In Espruino, a Waveform is a set of data that you + * want to input or output. + * @url http://www.espruino.com/Reference#Waveform + */ +declare class Waveform { /** - * Get the number of milliseconds elapsed since 1970 (or on embedded platforms, - * since startup) - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_now - */ - now(): number; - - /** - * Parse a date string and return milliseconds since 1970. Data can be either - * '2011-10-20T14:48:00', '2011-10-20' or 'Mon, 25 Dec 1995 13:30:00 +0430' - * - * @param {any} str - A String - * @returns {number} The number of milliseconds since 1970 - * @url http://www.espruino.com/Reference#l_Date_parse - */ - parse(str: string): number; - - /** - * Creates a date object + * Create a waveform class. This allows high speed input and output of waveforms. + * It has an internal variable called `buffer` (as well as `buffer2` when + * double-buffered - see `options` below) which contains the data to input/output. + * When double-buffered, a 'buffer' event will be emitted each time a buffer is + * finished with (the argument is that buffer). When the recording stops, a + * 'finish' event will be emitted (with the first argument as the buffer). * @constructor * - * @param {any} args - Either nothing (current time), one numeric argument (milliseconds since 1970), a date string (see `Date.parse`), or [year, month, day, hour, minute, second, millisecond] - * @returns {any} A Date object - * @url http://www.espruino.com/Reference#l_Date_Date + * @param {number} samples - The number of samples + * @param {any} options - Optional options struct `{doubleBuffer:bool, bits : 8/16}` where: `doubleBuffer` is whether to allocate two buffers or not (default false), and bits is the amount of bits to use (default 8). + * @returns {any} An Waveform object + * @url http://www.espruino.com/Reference#l_Waveform_Waveform */ - new(): Date; - new(value: number | string): Date; - new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + static new(samples: number, options: any): any; + + /** + * Will start outputting the waveform on the given pin - the pin must have + * previously been initialised with analogWrite. If not repeating, it'll emit a + * `finish` event when it is done. + * + * @param {Pin} output - The pin to output on + * @param {number} freq - The frequency to output each sample at + * @param {any} options - Optional options struct `{time:float,repeat:bool}` where: `time` is the that the waveform with start output at, e.g. `getTime()+1` (otherwise it is immediate), `repeat` is a boolean specifying whether to repeat the give sample + * @url http://www.espruino.com/Reference#l_Waveform_startOutput + */ + startOutput(output: Pin, freq: number, options: any): void; + + /** + * Will start inputting the waveform on the given pin that supports analog. If not + * repeating, it'll emit a `finish` event when it is done. + * + * @param {Pin} output - The pin to output on + * @param {number} freq - The frequency to output each sample at + * @param {any} options - Optional options struct `{time:float,repeat:bool}` where: `time` is the that the waveform with start output at, e.g. `getTime()+1` (otherwise it is immediate), `repeat` is a boolean specifying whether to repeat the give sample + * @url http://www.espruino.com/Reference#l_Waveform_startInput + */ + startInput(output: Pin, freq: number, options: any): void; + + /** + * Stop a waveform that is currently outputting + * @url http://www.espruino.com/Reference#l_Waveform_stop + */ + stop(): void; } -interface Date { +interface DataViewConstructor { /** - * This returns the time-zone offset from UTC, in minutes. - * @returns {number} The difference, in minutes, between UTC and local time - * @url http://www.espruino.com/Reference#l_Date_getTimezoneOffset - */ - getTimezoneOffset(): number; - - /** - * This returns a boolean indicating whether daylight savings time is in effect. - * @returns {number} true if daylight savings time is in effect - * @url http://www.espruino.com/Reference#l_Date_getIsDST - */ - getIsDST(): boolean - - /** - * Return the number of milliseconds since 1970 - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_getTime - */ - getTime(): number; - - /** - * Return the number of milliseconds since 1970 - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_valueOf - */ - valueOf(): number; - - /** - * Set the time/date of this Date class + * Create a `DataView` object that can be used to access the data in an + * `ArrayBuffer`. + * ``` + * var b = new ArrayBuffer(8) + * var v = new DataView(b) + * v.setUint16(0,"0x1234") + * v.setUint8(3,"0x56") + * console.log("0x"+v.getUint32(0).toString(16)) + * // prints 0x12340056 + * ``` + * @constructor * - * @param {number} timeValue - the number of milliseconds since 1970 - * @returns {number} the number of milliseconds since 1970 - * @url http://www.espruino.com/Reference#l_Date_setTime + * @param {any} buffer - The `ArrayBuffer` to base this on + * @param {number} [byteOffset] - [optional] The offset of this view in bytes + * @param {number} [byteLength] - [optional] The length in bytes + * @returns {any} A `DataView` object + * @url http://www.espruino.com/Reference#l_DataView_DataView */ - setTime(timeValue: number): number; + new(buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; +} +interface DataView { /** - * 0..23 - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_getHours - */ - getHours(): number; - - /** - * 0..59 - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_getMinutes - */ - getMinutes(): number; - - /** - * 0..59 - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_getSeconds - */ - getSeconds(): number; - - /** - * 0..999 - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_getMilliseconds - */ - getMilliseconds(): number; - - /** - * Day of the week (0=sunday, 1=monday, etc) - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_getDay - */ - getDay(): number; - - /** - * Day of the month 1..31 - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_getDate - */ - getDate(): number; - - /** - * Month of the year 0..11 - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_getMonth - */ - getMonth(): number; - - /** - * The year, eg. 2014 - * @returns {number} - * @url http://www.espruino.com/Reference#l_Date_getFullYear - */ - getFullYear(): number; - - /** - * 0..23 * - * @param {number} hoursValue - number of hours, 0..23 - * @param {any} minutesValue - number of minutes, 0..59 - * @param {any} secondsValue - optional - number of seconds, 0..59 - * @param {any} millisecondsValue - optional - number of milliseconds, 0..999 - * @returns {number} The number of milliseconds since 1970 - * @url http://www.espruino.com/Reference#l_Date_setHours + * @param {number} byteOffset - The offset in bytes to read from + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @returns {any} the index of the value in the array, or -1 + * @url http://www.espruino.com/Reference#l_DataView_getFloat32 */ - setHours(hoursValue: number, minutesValue?: number, secondsValue?: number, millisecondsValue?: number): number; - - /** - * 0..59 - * - * @param {number} minutesValue - number of minutes, 0..59 - * @param {any} secondsValue - optional - number of seconds, 0..59 - * @param {any} millisecondsValue - optional - number of milliseconds, 0..999 - * @returns {number} The number of milliseconds since 1970 - * @url http://www.espruino.com/Reference#l_Date_setMinutes - */ - setMinutes(minutesValue: number, secondsValue?: number, millisecondsValue?: number): number; - - /** - * 0..59 - * - * @param {number} secondsValue - number of seconds, 0..59 - * @param {any} millisecondsValue - optional - number of milliseconds, 0..999 - * @returns {number} The number of milliseconds since 1970 - * @url http://www.espruino.com/Reference#l_Date_setSeconds - */ - setSeconds(secondsValue: number, millisecondsValue?: number): number; + getFloat32(byteOffset: number, littleEndian?: boolean): number; /** * - * @param {number} millisecondsValue - number of milliseconds, 0..999 - * @returns {number} The number of milliseconds since 1970 - * @url http://www.espruino.com/Reference#l_Date_setMilliseconds + * @param {number} byteOffset - The offset in bytes to read from + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @returns {any} the index of the value in the array, or -1 + * @url http://www.espruino.com/Reference#l_DataView_getFloat64 */ - setMilliseconds(millisecondsValue: number): number; - - /** - * Day of the month 1..31 - * - * @param {number} dayValue - the day of the month, between 0 and 31 - * @returns {number} The number of milliseconds since 1970 - * @url http://www.espruino.com/Reference#l_Date_setDate - */ - setDate(dayValue: number): number; - - /** - * Month of the year 0..11 - * - * @param {number} yearValue - The month, between 0 and 11 - * @param {any} dayValue - optional - the day, between 0 and 31 - * @returns {number} The number of milliseconds since 1970 - * @url http://www.espruino.com/Reference#l_Date_setMonth - */ - setMonth(yearValue: number, dayValue?: number): number; + getFloat64(byteOffset: number, littleEndian?: boolean): number; /** * - * @param {number} yearValue - The full year - eg. 1989 - * @param {any} monthValue - optional - the month, between 0 and 11 - * @param {any} dayValue - optional - the day, between 0 and 31 - * @returns {number} The number of milliseconds since 1970 - * @url http://www.espruino.com/Reference#l_Date_setFullYear + * @param {number} byteOffset - The offset in bytes to read from + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @returns {any} the index of the value in the array, or -1 + * @url http://www.espruino.com/Reference#l_DataView_getInt8 */ - setFullYear(yearValue: number, monthValue?: number, dayValue?: number): number; + getInt8(byteOffset: number, littleEndian?: boolean): number; /** - * Converts to a String, eg: `Fri Jun 20 2014 14:52:20 GMT+0000` - * **Note:** This uses whatever timezone was set with `E.setTimeZone()` or - * `E.setDST()` + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @returns {any} the index of the value in the array, or -1 + * @url http://www.espruino.com/Reference#l_DataView_getInt16 + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @returns {any} the index of the value in the array, or -1 + * @url http://www.espruino.com/Reference#l_DataView_getInt32 + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @returns {any} the index of the value in the array, or -1 + * @url http://www.espruino.com/Reference#l_DataView_getUint8 + */ + getUint8(byteOffset: number, littleEndian?: boolean): number; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @returns {any} the index of the value in the array, or -1 + * @url http://www.espruino.com/Reference#l_DataView_getUint16 + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @returns {any} the index of the value in the array, or -1 + * @url http://www.espruino.com/Reference#l_DataView_getUint32 + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {any} value - The value to write + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @url http://www.espruino.com/Reference#l_DataView_setFloat32 + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {any} value - The value to write + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @url http://www.espruino.com/Reference#l_DataView_setFloat64 + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {any} value - The value to write + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @url http://www.espruino.com/Reference#l_DataView_setInt8 + */ + setInt8(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {any} value - The value to write + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @url http://www.espruino.com/Reference#l_DataView_setInt16 + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {any} value - The value to write + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @url http://www.espruino.com/Reference#l_DataView_setInt32 + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {any} value - The value to write + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @url http://www.espruino.com/Reference#l_DataView_setUint8 + */ + setUint8(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {any} value - The value to write + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @url http://www.espruino.com/Reference#l_DataView_setUint16 + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * + * @param {number} byteOffset - The offset in bytes to read from + * @param {any} value - The value to write + * @param {boolean} [littleEndian] - [optional] Whether to read in little endian - if false or undefined data is read as big endian + * @url http://www.espruino.com/Reference#l_DataView_setUint32 + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; +} + +/** + * This class helps + * @url http://www.espruino.com/Reference#DataView + */ +declare const DataView: DataViewConstructor + +interface consoleConstructor { + /** + * Print the supplied string(s) to the console + * **Note:** If you're connected to a computer (not a wall adaptor) via USB but + * **you are not running a terminal app** then when you print data Espruino may + * pause execution and wait until the computer requests the data it is trying to + * print. + * + * @param {any} text - One or more arguments to print + * @url http://www.espruino.com/Reference#l_console_log + */ + log(...text: any[]): void; +} + +interface console { + +} + +/** + * An Object that contains functions for writing to the interactive console + * @url http://www.espruino.com/Reference#console + */ +declare const console: consoleConstructor + +interface ErrorConstructor { + /** + * Creates an Error object + * @constructor + * + * @param {any} [message] - [optional] An message string + * @returns {any} An Error object + * @url http://www.espruino.com/Reference#l_Error_Error + */ + new(message?: string): Error; +} + +interface Error { + /** * @returns {any} A String - * @url http://www.espruino.com/Reference#l_Date_toString + * @url http://www.espruino.com/Reference#l_Error_toString */ toString(): string; - - /** - * Converts to a String, eg: `Fri, 20 Jun 2014 14:52:20 GMT` - * **Note:** This always assumes a timezone of GMT - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_Date_toUTCString - */ - toUTCString(): string; - - /** - * Converts to a ISO 8601 String, eg: `2014-06-20T14:52:20.123Z` - * **Note:** This always assumes a timezone of GMT - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_Date_toISOString - */ - toISOString(): string; - - /** - * Calls `Date.toISOString` to output this date to JSON - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_Date_toJSON - */ - toJSON(): string; - - /** - * Converts to a ISO 8601 String (with timezone information), eg: - * `2014-06-20T14:52:20.123-0500` - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_Date_toLocalISOString - */ - toLocalISOString(): string; } /** - * The built-in class for handling Dates. - * **Note:** By default the time zone is GMT+0, however you can change the timezone - * using the `E.setTimeZone(...)` function. - * For example `E.setTimeZone(1)` will be GMT+0100 - * *However* if you have daylight savings time set with `E.setDST(...)` then the - * timezone set by `E.setTimeZone(...)` will be _ignored_. - * @url http://www.espruino.com/Reference#Date + * The base class for runtime errors + * @url http://www.espruino.com/Reference#Error */ -declare const Date: DateConstructor +declare const Error: ErrorConstructor -/** - * This class provides a software-defined OneWire master. It is designed to be - * similar to Arduino's OneWire library. - * @url http://www.espruino.com/Reference#OneWire - */ -declare class OneWire { +interface SyntaxErrorConstructor { /** - * Create a software OneWire implementation on the given pin + * Creates a SyntaxError object * @constructor * - * @param {Pin} pin - The pin to implement OneWire on - * @returns {any} A OneWire object - * @url http://www.espruino.com/Reference#l_OneWire_OneWire + * @param {any} [message] - [optional] An message string + * @returns {any} A SyntaxError object + * @url http://www.espruino.com/Reference#l_SyntaxError_SyntaxError */ - static new(pin: Pin): any; - - /** - * Perform a reset cycle - * @returns {boolean} True is a device was present (it held the bus low) - * @url http://www.espruino.com/Reference#l_OneWire_reset - */ - reset(): boolean; - - /** - * Select a ROM - always performs a reset first - * - * @param {any} rom - The device to select (get this using `OneWire.search()`) - * @url http://www.espruino.com/Reference#l_OneWire_select - */ - select(rom: any): void; - - /** - * Skip a ROM - * @url http://www.espruino.com/Reference#l_OneWire_skip - */ - skip(): void; - - /** - * Write one or more bytes - * - * @param {any} data - A byte (or array of bytes) to write - * @param {boolean} power - Whether to leave power on after write (default is false) - * @url http://www.espruino.com/Reference#l_OneWire_write - */ - write(data: any, power: boolean): void; - - /** - * Read a byte - * - * @param {any} count - (optional) The amount of bytes to read - * @returns {any} The byte that was read, or a Uint8Array if count was specified and >=0 - * @url http://www.espruino.com/Reference#l_OneWire_read - */ - read(count: any): any; - - /** - * Search for devices - * - * @param {number} command - (Optional) command byte. If not specified (or zero), this defaults to 0xF0. This can could be set to 0xEC to perform a DS18B20 'Alarm Search Command' - * @returns {any} An array of devices that were found - * @url http://www.espruino.com/Reference#l_OneWire_search - */ - search(command: number): any; + new(message?: string): SyntaxError; } -interface NumberConstructor { +interface SyntaxError { /** - * @returns {number} Not a Number - * @url http://www.espruino.com/Reference#l_Number_NaN + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_SyntaxError_toString */ - NaN: number; - - /** - * @returns {number} Maximum representable value - * @url http://www.espruino.com/Reference#l_Number_MAX_VALUE - */ - MAX_VALUE: number; - - /** - * @returns {number} Smallest representable value - * @url http://www.espruino.com/Reference#l_Number_MIN_VALUE - */ - MIN_VALUE: number; - - /** - * @returns {number} Negative Infinity (-1/0) - * @url http://www.espruino.com/Reference#l_Number_NEGATIVE_INFINITY - */ - NEGATIVE_INFINITY: number; - - /** - * @returns {number} Positive Infinity (1/0) - * @url http://www.espruino.com/Reference#l_Number_POSITIVE_INFINITY - */ - POSITIVE_INFINITY: number; - - /** - * Creates a number - * @constructor - * - * @param {any} value - A single value to be converted to a number - * @returns {any} A Number object - * @url http://www.espruino.com/Reference#l_Number_Number - */ - new(...value: any[]): any; -} - -interface Number { - /** - * Format the number as a fixed point number - * - * @param {number} decimalPlaces - A number between 0 and 20 specifying the number of decimal digits after the decimal point - * @returns {any} A string - * @url http://www.espruino.com/Reference#l_Number_toFixed - */ - toFixed(decimalPlaces: number): any; + toString(): string; } /** - * This is the built-in JavaScript class for numbers. - * @url http://www.espruino.com/Reference#Number + * The base class for syntax errors + * @url http://www.espruino.com/Reference#SyntaxError */ -declare const Number: NumberConstructor +declare const SyntaxError: SyntaxErrorConstructor + +interface TypeErrorConstructor { + /** + * Creates a TypeError object + * @constructor + * + * @param {any} [message] - [optional] An message string + * @returns {any} A TypeError object + * @url http://www.espruino.com/Reference#l_TypeError_TypeError + */ + new(message?: string): TypeError; +} + +interface TypeError { + /** + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_TypeError_toString + */ + toString(): string; +} + +/** + * The base class for type errors + * @url http://www.espruino.com/Reference#TypeError + */ +declare const TypeError: TypeErrorConstructor + +/** + * The base class for internal errors + * @url http://www.espruino.com/Reference#InternalError + */ +declare class InternalError { + /** + * Creates an InternalError object + * @constructor + * + * @param {any} [message] - [optional] An message string + * @returns {any} An InternalError object + * @url http://www.espruino.com/Reference#l_InternalError_InternalError + */ + static new(message?: string): InternalError; + + /** + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_InternalError_toString + */ + toString(): string; +} + +interface ReferenceErrorConstructor { + /** + * Creates a ReferenceError object + * @constructor + * + * @param {any} [message] - [optional] An message string + * @returns {any} A ReferenceError object + * @url http://www.espruino.com/Reference#l_ReferenceError_ReferenceError + */ + new(message?: string): ReferenceError; +} + +interface ReferenceError { + /** + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_ReferenceError_toString + */ + toString(): string; +} + +/** + * The base class for reference errors - where a variable which doesn't exist has + * been accessed. + * @url http://www.espruino.com/Reference#ReferenceError + */ +declare const ReferenceError: ReferenceErrorConstructor interface ArrayBufferConstructor { /** @@ -6135,7 +6293,7 @@ declare class ArrayBufferView { * Copy the contents of `array` into this one, mapping `this[x+offset]=array[x];` * * @param {any} arr - Floating point index to access - * @param {number} offset - The offset in this array at which to write the values (optional) + * @param {number} [offset] - [optional] The offset in this array at which to write the values * @url http://www.espruino.com/Reference#l_ArrayBufferView_set */ set(arr: ArrayLike, offset: number): void @@ -6147,7 +6305,7 @@ declare class ArrayBufferView { * get an `Array`, use `Array.map`, e.g. `[].map.call(myArray, x=>x+1)` * * @param {any} function - Function used to map one item to another - * @param {any} thisArg - if specified, the function is called with 'this' set to thisArg (optional) + * @param {any} [thisArg] - [optional] If specified, the function is called with 'this' set to thisArg * @returns {any} An array containing the results * @url http://www.espruino.com/Reference#l_ArrayBufferView_map */ @@ -6168,7 +6326,7 @@ declare class ArrayBufferView { * Return the index of the value in the array, or `-1` * * @param {any} value - The value to check for - * @param {number} startIndex - (optional) the index to search from, or 0 if not specified + * @param {number} [startIndex] - [optional] the index to search from, or 0 if not specified * @returns {any} the index of the value in the array, or -1 * @url http://www.espruino.com/Reference#l_ArrayBufferView_indexOf */ @@ -6178,7 +6336,7 @@ declare class ArrayBufferView { * Return `true` if the array includes the value, `false` otherwise * * @param {any} value - The value to check for - * @param {number} startIndex - (optional) the index to search from, or 0 if not specified + * @param {number} [startIndex] - [optional] the index to search from, or 0 if not specified * @returns {boolean} `true` if the array includes the value, `false` otherwise * @url http://www.espruino.com/Reference#l_ArrayBufferView_includes */ @@ -6207,7 +6365,7 @@ declare class ArrayBufferView { * Executes a provided function once per array element. * * @param {any} function - Function to be executed - * @param {any} thisArg - if specified, the function is called with 'this' set to thisArg (optional) + * @param {any} [thisArg] - [optional] If specified, the function is called with 'this' set to thisArg * @url http://www.espruino.com/Reference#l_ArrayBufferView_forEach */ forEach(callbackfn: (value: number, index: number, array: T) => void, thisArg?: any): void; @@ -6240,7 +6398,7 @@ declare class ArrayBufferView { * function returns 'true' * * @param {any} function - Function to be executed - * @param {any} thisArg - if specified, the function is called with 'this' set to thisArg (optional) + * @param {any} [thisArg] - [optional] If specified, the function is called with 'this' set to thisArg * @returns {any} An array containing the results * @url http://www.espruino.com/Reference#l_ArrayBufferView_filter */ @@ -6278,7 +6436,7 @@ declare class ArrayBufferView { * **Note:** This currently returns a normal `Array`, not an `ArrayBuffer` * * @param {number} start - Start index - * @param {any} end - End index (optional) + * @param {any} [end] - [optional] End index * @returns {any} A new array * @url http://www.espruino.com/Reference#l_ArrayBufferView_slice */ @@ -6526,1009 +6684,491 @@ type Float64Array = ArrayBufferView; declare const Float64Array: Float64ArrayConstructor -interface PromiseConstructor { +interface DateConstructor { /** - * Return a new promise that is resolved when all promises in the supplied array - * are resolved. - * - * @param {any} promises - An array of promises - * @returns {any} A new Promise - * @url http://www.espruino.com/Reference#l_Promise_all + * Get the number of milliseconds elapsed since 1970 (or on embedded platforms, + * since startup) + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_now */ - all(promises: Promise[]): Promise; + now(): number; /** - * Return a new promise that is already resolved (at idle it'll call `.then`) + * Parse a date string and return milliseconds since 1970. Data can be either + * '2011-10-20T14:48:00', '2011-10-20' or 'Mon, 25 Dec 1995 13:30:00 +0430' * - * @param {any} promises - Data to pass to the `.then` handler - * @returns {any} A new Promise - * @url http://www.espruino.com/Reference#l_Promise_resolve + * @param {any} str - A String + * @returns {number} The number of milliseconds since 1970 + * @url http://www.espruino.com/Reference#l_Date_parse */ - resolve(promises: T): Promise; + parse(str: string): number; /** - * Return a new promise that is already rejected (at idle it'll call `.catch`) - * - * @param {any} promises - Data to pass to the `.catch` handler - * @returns {any} A new Promise - * @url http://www.espruino.com/Reference#l_Promise_reject - */ - reject(promises: any): any; - - /** - * Create a new Promise. The executor function is executed immediately (before the - * constructor even returns) and + * Creates a date object * @constructor * - * @param {any} executor - A function of the form `function (resolve, reject)` - * @returns {any} A Promise - * @url http://www.espruino.com/Reference#l_Promise_Promise + * @param {any} args - Either nothing (current time), one numeric argument (milliseconds since 1970), a date string (see `Date.parse`), or [year, month, day, hour, minute, second, millisecond] + * @returns {any} A Date object + * @url http://www.espruino.com/Reference#l_Date_Date */ - new(executor: (resolve: (value: T) => void, reject: (reason?: any) => void) => void): Promise; + new(): Date; + new(value: number | string): Date; + new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; } -interface Promise { +interface Date { /** - * - * @param {any} onFulfilled - A callback that is called when this promise is resolved - * @param {any} [onRejected] - [optional] A callback that is called when this promise is rejected (or nothing) - * @returns {any} The original Promise - * @url http://www.espruino.com/Reference#l_Promise_then + * This returns the time-zone offset from UTC, in minutes. + * @returns {number} The difference, in minutes, between UTC and local time + * @url http://www.espruino.com/Reference#l_Date_getTimezoneOffset */ - then(onfulfilled?: ((value: T) => TResult1 | Promise) | undefined | null, onrejected?: ((reason: any) => TResult2 | Promise) | undefined | null): Promise; + getTimezoneOffset(): number; + + /** + * This returns a boolean indicating whether daylight savings time is in effect. + * @returns {number} true if daylight savings time is in effect + * @url http://www.espruino.com/Reference#l_Date_getIsDST + */ + getIsDST(): boolean + + /** + * Return the number of milliseconds since 1970 + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_getTime + */ + getTime(): number; + + /** + * Return the number of milliseconds since 1970 + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_valueOf + */ + valueOf(): number; + + /** + * Set the time/date of this Date class + * + * @param {number} timeValue - the number of milliseconds since 1970 + * @returns {number} the number of milliseconds since 1970 + * @url http://www.espruino.com/Reference#l_Date_setTime + */ + setTime(timeValue: number): number; + + /** + * 0..23 + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_getHours + */ + getHours(): number; + + /** + * 0..59 + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_getMinutes + */ + getMinutes(): number; + + /** + * 0..59 + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_getSeconds + */ + getSeconds(): number; + + /** + * 0..999 + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_getMilliseconds + */ + getMilliseconds(): number; + + /** + * Day of the week (0=sunday, 1=monday, etc) + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_getDay + */ + getDay(): number; + + /** + * Day of the month 1..31 + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_getDate + */ + getDate(): number; + + /** + * Month of the year 0..11 + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_getMonth + */ + getMonth(): number; + + /** + * The year, e.g. 2014 + * @returns {number} + * @url http://www.espruino.com/Reference#l_Date_getFullYear + */ + getFullYear(): number; + + /** + * 0..23 + * + * @param {number} hoursValue - number of hours, 0..23 + * @param {any} minutesValue - number of minutes, 0..59 + * @param {any} [secondsValue] - [optional] number of seconds, 0..59 + * @param {any} [millisecondsValue] - [optional] number of milliseconds, 0..999 + * @returns {number} The number of milliseconds since 1970 + * @url http://www.espruino.com/Reference#l_Date_setHours + */ + setHours(hoursValue: number, minutesValue?: number, secondsValue?: number, millisecondsValue?: number): number; + + /** + * 0..59 + * + * @param {number} minutesValue - number of minutes, 0..59 + * @param {any} [secondsValue] - [optional] number of seconds, 0..59 + * @param {any} [millisecondsValue] - [optional] number of milliseconds, 0..999 + * @returns {number} The number of milliseconds since 1970 + * @url http://www.espruino.com/Reference#l_Date_setMinutes + */ + setMinutes(minutesValue: number, secondsValue?: number, millisecondsValue?: number): number; + + /** + * 0..59 + * + * @param {number} secondsValue - number of seconds, 0..59 + * @param {any} [millisecondsValue] - [optional] number of milliseconds, 0..999 + * @returns {number} The number of milliseconds since 1970 + * @url http://www.espruino.com/Reference#l_Date_setSeconds + */ + setSeconds(secondsValue: number, millisecondsValue?: number): number; /** * - * @param {any} onRejected - A callback that is called when this promise is rejected - * @returns {any} The original Promise - * @url http://www.espruino.com/Reference#l_Promise_catch + * @param {number} millisecondsValue - number of milliseconds, 0..999 + * @returns {number} The number of milliseconds since 1970 + * @url http://www.espruino.com/Reference#l_Date_setMilliseconds */ - catch(onRejected: any): any; + setMilliseconds(millisecondsValue: number): number; + + /** + * Day of the month 1..31 + * + * @param {number} dayValue - the day of the month, between 0 and 31 + * @returns {number} The number of milliseconds since 1970 + * @url http://www.espruino.com/Reference#l_Date_setDate + */ + setDate(dayValue: number): number; + + /** + * Month of the year 0..11 + * + * @param {number} yearValue - The month, between 0 and 11 + * @param {any} [dayValue] - [optional] the day, between 0 and 31 + * @returns {number} The number of milliseconds since 1970 + * @url http://www.espruino.com/Reference#l_Date_setMonth + */ + setMonth(yearValue: number, dayValue?: number): number; + + /** + * + * @param {number} yearValue - The full year - eg. 1989 + * @param {any} [monthValue] - [optional] the month, between 0 and 11 + * @param {any} [dayValue] - [optional] the day, between 0 and 31 + * @returns {number} The number of milliseconds since 1970 + * @url http://www.espruino.com/Reference#l_Date_setFullYear + */ + setFullYear(yearValue: number, monthValue?: number, dayValue?: number): number; + + /** + * Converts to a String, e.g: `Fri Jun 20 2014 14:52:20 GMT+0000` + * **Note:** This uses whatever timezone was set with `E.setTimeZone()` or + * `E.setDST()` + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_Date_toString + */ + toString(): string; + + /** + * Converts to a String, e.g: `Fri, 20 Jun 2014 14:52:20 GMT` + * **Note:** This always assumes a timezone of GMT + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_Date_toUTCString + */ + toUTCString(): string; + + /** + * Converts to a ISO 8601 String, e.g: `2014-06-20T14:52:20.123Z` + * **Note:** This always assumes a timezone of GMT + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_Date_toISOString + */ + toISOString(): string; + + /** + * Calls `Date.toISOString` to output this date to JSON + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_Date_toJSON + */ + toJSON(): string; + + /** + * Converts to a ISO 8601 String (with timezone information), e.g: + * `2014-06-20T14:52:20.123-0500` + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_Date_toLocalISOString + */ + toLocalISOString(): string; } /** - * This is the built-in class for ES6 Promises - * @url http://www.espruino.com/Reference#Promise + * The built-in class for handling Dates. + * **Note:** By default the time zone is GMT+0, however you can change the timezone + * using the `E.setTimeZone(...)` function. + * For example `E.setTimeZone(1)` will be GMT+0100 + * *However* if you have daylight savings time set with `E.setDST(...)` then the + * timezone set by `E.setTimeZone(...)` will be _ignored_. + * @url http://www.espruino.com/Reference#Date */ -declare const Promise: PromiseConstructor +declare const Date: DateConstructor + +interface MathConstructor { + /** + * @returns {number} The value of E - 2.718281828459045 + * @url http://www.espruino.com/Reference#l_Math_E + */ + E: number; + + /** + * @returns {number} The value of PI - 3.141592653589793 + * @url http://www.espruino.com/Reference#l_Math_PI + */ + PI: number; + + /** + * @returns {number} The natural logarithm of 2 - 0.6931471805599453 + * @url http://www.espruino.com/Reference#l_Math_LN2 + */ + LN2: number; + + /** + * @returns {number} The natural logarithm of 10 - 2.302585092994046 + * @url http://www.espruino.com/Reference#l_Math_LN10 + */ + LN10: number; + + /** + * @returns {number} The base 2 logarithm of e - 1.4426950408889634 + * @url http://www.espruino.com/Reference#l_Math_LOG2E + */ + LOG2E: number; + + /** + * @returns {number} The base 10 logarithm of e - 0.4342944819032518 + * @url http://www.espruino.com/Reference#l_Math_LOG10E + */ + LOG10E: number; + + /** + * @returns {number} The square root of 2 - 1.4142135623730951 + * @url http://www.espruino.com/Reference#l_Math_SQRT2 + */ + SQRT2: number; + + /** + * @returns {number} The square root of 1/2 - 0.7071067811865476 + * @url http://www.espruino.com/Reference#l_Math_SQRT1_2 + */ + SQRT1_2: number; -/** - * This class allows use of the built-in SPI ports. Currently it is SPI master - * only. - * @url http://www.espruino.com/Reference#SPI - */ -declare class SPI { /** - * Try and find an SPI hardware device that will work on this pin (eg. `SPI1`) - * May return undefined if no device can be found. * - * @param {Pin} pin - A pin to search with - * @returns {any} An object of type `SPI`, or `undefined` if one couldn't be found. - * @url http://www.espruino.com/Reference#l_SPI_find + * @param {number} x - A floating point value + * @returns {number} The absolute value of x (eg, ```Math.abs(2)==2```, but also ```Math.abs(-2)==2```) + * @url http://www.espruino.com/Reference#l_Math_abs */ - static find(pin: Pin): any; + abs(x: number): number; /** - * Create a software SPI port. This has limited functionality (no baud rate), but - * it can work on any pins. - * Use `SPI.setup` to configure this port. - * @constructor - * @returns {any} A SPI object - * @url http://www.espruino.com/Reference#l_SPI_SPI - */ - static new(): any; - - /** - * Set up this SPI port as an SPI Master. - * Options can contain the following (defaults are shown where relevant): - * ``` - * { - * sck:pin, - * miso:pin, - * mosi:pin, - * baud:integer=100000, // ignored on software SPI - * mode:integer=0, // between 0 and 3 - * order:string='msb' // can be 'msb' or 'lsb' - * bits:8 // only available for software SPI - * } - * ``` - * If `sck`,`miso` and `mosi` are left out, they will automatically be chosen. - * However if one or more is specified then the unspecified pins will not be set - * up. - * You can find out which pins to use by looking at [your board's reference - * page](#boards) and searching for pins with the `SPI` marker. Some boards such as - * those based on `nRF52` chips can have SPI on any pins, so don't have specific - * markings. - * The SPI `mode` is between 0 and 3 - see - * http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase - * On STM32F1-based parts, you cannot mix AF and non-AF pins (SPI pins are usually - * grouped on the chip - and you can't mix pins from two groups). Espruino will not - * warn you about this. * - * @param {any} options - An Object containing extra information on initialising the SPI port - * @url http://www.espruino.com/Reference#l_SPI_setup + * @param {number} x - The value to get the arc cosine of + * @returns {number} The arc cosine of x, between 0 and PI + * @url http://www.espruino.com/Reference#l_Math_acos */ - setup(options: any): void; + acos(x: number): number; /** - * Send data down SPI, and return the result. Sending an integer will return an - * integer, a String will return a String, and anything else will return a - * Uint8Array. - * Sending multiple bytes in one call to send is preferable as they can then be - * transmitted end to end. Using multiple calls to send() will result in - * significantly slower transmission speeds. - * For maximum speeds, please pass either Strings or Typed Arrays as arguments. - * Note that you can even pass arrays of arrays, like `[1,[2,3,4],5]` * - * @param {any} data - The data to send - either an Integer, Array, String, or Object of the form `{data: ..., count:#}` - * @param {Pin} nss_pin - An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised. - * @returns {any} The data that was returned - * @url http://www.espruino.com/Reference#l_SPI_send + * @param {number} x - The value to get the arc sine of + * @returns {number} The arc sine of x, between -PI/2 and PI/2 + * @url http://www.espruino.com/Reference#l_Math_asin */ - send(data: any, nss_pin: Pin): any; + asin(x: number): number; /** - * Write a character or array of characters to SPI - without reading the result - * back. - * For maximum speeds, please pass either Strings or Typed Arrays as arguments. * - * @param {any} data - * One or more items to write. May be ints, strings, arrays, or special objects (see `E.toUint8Array` for more info). - * If the last argument is a pin, it is taken to be the NSS pin - * @url http://www.espruino.com/Reference#l_SPI_write + * @param {number} x - The value to get the arc tangent of + * @returns {number} The arc tangent of x, between -PI/2 and PI/2 + * @url http://www.espruino.com/Reference#l_Math_atan */ - write(...data: any[]): void; + atan(x: number): number; /** - * Send data down SPI, using 4 bits for each 'real' bit (MSB first). This can be - * useful for faking one-wire style protocols - * Sending multiple bytes in one call to send is preferable as they can then be - * transmitted end to end. Using multiple calls to send() will result in - * significantly slower transmission speeds. * - * @param {any} data - The data to send - either an integer, array, or string - * @param {number} bit0 - The 4 bits to send for a 0 (MSB first) - * @param {number} bit1 - The 4 bits to send for a 1 (MSB first) - * @param {Pin} nss_pin - An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised. - * @url http://www.espruino.com/Reference#l_SPI_send4bit + * @param {number} y - The Y-part of the angle to get the arc tangent of + * @param {number} x - The X-part of the angle to get the arc tangent of + * @returns {number} The arctangent of Y/X, between -PI and PI + * @url http://www.espruino.com/Reference#l_Math_atan2 */ - send4bit(data: any, bit0: number, bit1: number, nss_pin: Pin): void; + atan2(y: number, x: number): number; /** - * Send data down SPI, using 8 bits for each 'real' bit (MSB first). This can be - * useful for faking one-wire style protocols - * Sending multiple bytes in one call to send is preferable as they can then be - * transmitted end to end. Using multiple calls to send() will result in - * significantly slower transmission speeds. * - * @param {any} data - The data to send - either an integer, array, or string - * @param {number} bit0 - The 8 bits to send for a 0 (MSB first) - * @param {number} bit1 - The 8 bits to send for a 1 (MSB first) - * @param {Pin} nss_pin - An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised - * @url http://www.espruino.com/Reference#l_SPI_send8bit + * @param {number} theta - The angle to get the cosine of + * @returns {number} The cosine of theta + * @url http://www.espruino.com/Reference#l_Math_cos */ - send8bit(data: any, bit0: number, bit1: number, nss_pin: Pin): void; + cos(theta: number): number; + + /** + * + * @param {number} x - The value to raise to the power + * @param {number} y - The power x should be raised to + * @returns {number} x raised to the power y (x^y) + * @url http://www.espruino.com/Reference#l_Math_pow + */ + pow(x: number, y: number): number; + + /** + * @returns {number} A random number between 0 and 1 + * @url http://www.espruino.com/Reference#l_Math_random + */ + random(): number; + + /** + * + * @param {number} x - The value to round + * @returns {any} x, rounded to the nearest integer + * @url http://www.espruino.com/Reference#l_Math_round + */ + round(x: number): any; + + /** + * + * @param {number} theta - The angle to get the sine of + * @returns {number} The sine of theta + * @url http://www.espruino.com/Reference#l_Math_sin + */ + sin(theta: number): number; + + /** + * + * @param {number} theta - The angle to get the tangent of + * @returns {number} The tangent of theta + * @url http://www.espruino.com/Reference#l_Math_tan + */ + tan(theta: number): number; + + /** + * + * @param {number} x - The value to take the square root of + * @returns {number} The square root of x + * @url http://www.espruino.com/Reference#l_Math_sqrt + */ + sqrt(x: number): number; + + /** + * + * @param {number} x - The value to round up + * @returns {number} x, rounded upwards to the nearest integer + * @url http://www.espruino.com/Reference#l_Math_ceil + */ + ceil(x: number): number; + + /** + * + * @param {number} x - The value to round down + * @returns {number} x, rounded downwards to the nearest integer + * @url http://www.espruino.com/Reference#l_Math_floor + */ + floor(x: number): number; + + /** + * + * @param {number} x - The value raise E to the power of + * @returns {number} E^x + * @url http://www.espruino.com/Reference#l_Math_exp + */ + exp(x: number): number; + + /** + * + * @param {number} x - The value to take the logarithm (base E) root of + * @returns {number} The log (base E) of x + * @url http://www.espruino.com/Reference#l_Math_log + */ + log(x: number): number; + + /** + * DEPRECATED - Please use `E.clip()` instead. Clip a number to be between min and + * max (inclusive) + * + * @param {number} x - A floating point value to clip + * @param {number} min - The smallest the value should be + * @param {number} max - The largest the value should be + * @returns {number} The value of x, clipped so as not to be below min or above max. + * @url http://www.espruino.com/Reference#l_Math_clip + */ + clip(x: number, min: number, max: number): number; + + /** + * DEPRECATED - This is not part of standard JavaScript libraries + * Wrap a number around if it is less than 0 or greater than or equal to max. For + * instance you might do: ```Math.wrap(angleInDegrees, 360)``` + * + * @param {number} x - A floating point value to wrap + * @param {number} max - The largest the value should be + * @returns {number} The value of x, wrapped so as not to be below min or above max. + * @url http://www.espruino.com/Reference#l_Math_wrap + */ + wrap(x: number, max: number): number; + + /** + * Find the minimum of a series of numbers + * + * @param {any} args - Floating point values to clip + * @returns {number} The minimum of the supplied values + * @url http://www.espruino.com/Reference#l_Math_min + */ + min(...args: any[]): number; + + /** + * Find the maximum of a series of numbers + * + * @param {any} args - Floating point values to clip + * @returns {number} The maximum of the supplied values + * @url http://www.espruino.com/Reference#l_Math_max + */ + max(...args: any[]): number; + + /** + * + * @param {number} x - The value to get the sign from + * @returns {number} sign on x - -1, 1, or 0 + * @url http://www.espruino.com/Reference#l_Math_sign + */ + sign(x: number): number; } -/** - * This class allows use of the built-in I2C ports. Currently it allows I2C Master - * mode only. - * All addresses are in 7 bit format. If you have an 8 bit address then you need to - * shift it one bit to the right. - * @url http://www.espruino.com/Reference#I2C - */ -declare class I2C { - /** - * Try and find an I2C hardware device that will work on this pin (eg. `I2C1`) - * May return undefined if no device can be found. - * - * @param {Pin} pin - A pin to search with - * @returns {any} An object of type `I2C`, or `undefined` if one couldn't be found. - * @url http://www.espruino.com/Reference#l_I2C_find - */ - static find(pin: Pin): any; - - /** - * Create a software I2C port. This has limited functionality (no baud rate), but - * it can work on any pins. - * Use `I2C.setup` to configure this port. - * @constructor - * @returns {any} An I2C object - * @url http://www.espruino.com/Reference#l_I2C_I2C - */ - static new(): any; - - /** - * Set up this I2C port - * If not specified in options, the default pins are used (usually the lowest - * numbered pins on the lowest port that supports this peripheral) - * - * @param {any} options - * An optional structure containing extra information on initialising the I2C port - * ```{scl:pin, sda:pin, bitrate:100000}``` - * You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `I2C` marker. Note that 400kHz is the maximum bitrate for most parts. - * @url http://www.espruino.com/Reference#l_I2C_setup - */ - setup(options: any): void; - - /** - * Transmit to the slave device with the given address. This is like Arduino's - * beginTransmission, write, and endTransmission rolled up into one. - * - * @param {any} address - The 7 bit address of the device to transmit to, or an object of the form `{address:12, stop:false}` to send this data without a STOP signal. - * @param {any} data - One or more items to write. May be ints, strings, arrays, or special objects (see `E.toUint8Array` for more info). - * @url http://www.espruino.com/Reference#l_I2C_writeTo - */ - writeTo(address: any, ...data: any[]): void; - - /** - * Request bytes from the given slave device, and return them as a Uint8Array - * (packed array of bytes). This is like using Arduino Wire's requestFrom, - * available and read functions. Sends a STOP - * - * @param {any} address - The 7 bit address of the device to request bytes from, or an object of the form `{address:12, stop:false}` to send this data without a STOP signal. - * @param {number} quantity - The number of bytes to request - * @returns {any} The data that was returned - as a Uint8Array - * @url http://www.espruino.com/Reference#l_I2C_readFrom - */ - readFrom(address: any, quantity: number): Uint8Array; -} - -/** - * This class handles waveforms. In Espruino, a Waveform is a set of data that you - * want to input or output. - * @url http://www.espruino.com/Reference#Waveform - */ -declare class Waveform { - /** - * Create a waveform class. This allows high speed input and output of waveforms. - * It has an internal variable called `buffer` (as well as `buffer2` when - * double-buffered - see `options` below) which contains the data to input/output. - * When double-buffered, a 'buffer' event will be emitted each time a buffer is - * finished with (the argument is that buffer). When the recording stops, a - * 'finish' event will be emitted (with the first argument as the buffer). - * @constructor - * - * @param {number} samples - The number of samples - * @param {any} options - Optional options struct `{doubleBuffer:bool, bits : 8/16}` where: `doubleBuffer` is whether to allocate two buffers or not (default false), and bits is the amount of bits to use (default 8). - * @returns {any} An Waveform object - * @url http://www.espruino.com/Reference#l_Waveform_Waveform - */ - static new(samples: number, options: any): any; - - /** - * Will start outputting the waveform on the given pin - the pin must have - * previously been initialised with analogWrite. If not repeating, it'll emit a - * `finish` event when it is done. - * - * @param {Pin} output - The pin to output on - * @param {number} freq - The frequency to output each sample at - * @param {any} options - Optional options struct `{time:float,repeat:bool}` where: `time` is the that the waveform with start output at, e.g. `getTime()+1` (otherwise it is immediate), `repeat` is a boolean specifying whether to repeat the give sample - * @url http://www.espruino.com/Reference#l_Waveform_startOutput - */ - startOutput(output: Pin, freq: number, options: any): void; - - /** - * Will start inputting the waveform on the given pin that supports analog. If not - * repeating, it'll emit a `finish` event when it is done. - * - * @param {Pin} output - The pin to output on - * @param {number} freq - The frequency to output each sample at - * @param {any} options - Optional options struct `{time:float,repeat:bool}` where: `time` is the that the waveform with start output at, e.g. `getTime()+1` (otherwise it is immediate), `repeat` is a boolean specifying whether to repeat the give sample - * @url http://www.espruino.com/Reference#l_Waveform_startInput - */ - startInput(output: Pin, freq: number, options: any): void; - - /** - * Stop a waveform that is currently outputting - * @url http://www.espruino.com/Reference#l_Waveform_stop - */ - stop(): void; -} - -/** - * This is the built-in class for Pins, such as D0,D1,LED1, or BTN - * You can call the methods on Pin, or you can use Wiring-style functions such as - * digitalWrite - * @url http://www.espruino.com/Reference#Pin - */ -declare class Pin { - /** - * Creates a pin from the given argument (or returns undefined if no argument) - * @constructor - * - * @param {any} value - A value to be converted to a pin. Can be a number, pin, or String. - * @returns {any} A Pin object - * @url http://www.espruino.com/Reference#l_Pin_Pin - */ - static new(value: any): any; - - /** - * Returns the input state of the pin as a boolean. - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset the pin's state to `"input"` - * @returns {boolean} Whether pin is a logical 1 or 0 - * @url http://www.espruino.com/Reference#l_Pin_read - */ - read(): boolean; - - /** - * Sets the output state of the pin to a 1 - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset the pin's state to `"output"` - * @url http://www.espruino.com/Reference#l_Pin_set - */ - set(): void; - - /** - * Sets the output state of the pin to a 0 - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset the pin's state to `"output"` - * @url http://www.espruino.com/Reference#l_Pin_reset - */ - reset(): void; - - /** - * Sets the output state of the pin to the parameter given - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset the pin's state to `"output"` - * - * @param {boolean} value - Whether to set output high (true/1) or low (false/0) - * @url http://www.espruino.com/Reference#l_Pin_write - */ - write(value: boolean): void; - - /** - * Sets the output state of the pin to the parameter given at the specified time. - * **Note:** this **doesn't** change the mode of the pin to an output. To do that, - * you need to use `pin.write(0)` or `pinMode(pin, 'output')` first. - * - * @param {boolean} value - Whether to set output high (true/1) or low (false/0) - * @param {number} time - Time at which to write - * @url http://www.espruino.com/Reference#l_Pin_writeAtTime - */ - writeAtTime(value: boolean, time: number): void; - - /** - * Return the current mode of the given pin. See `pinMode` for more information. - * @returns {any} The pin mode, as a string - * @url http://www.espruino.com/Reference#l_Pin_getMode - */ - getMode(): any; - - /** - * Set the mode of the given pin. See [`pinMode`](#l__global_pinMode) for more - * information on pin modes. - * - * @param {any} mode - The mode - a string that is either 'analog', 'input', 'input_pullup', 'input_pulldown', 'output', 'opendrain', 'af_output' or 'af_opendrain'. Do not include this argument if you want to revert to automatic pin mode setting. - * @url http://www.espruino.com/Reference#l_Pin_mode - */ - mode(mode: any): void; - - /** - * Toggles the state of the pin from off to on, or from on to off. - * **Note:** This method doesn't currently work on the ESP8266 port of Espruino. - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset the pin's state to `"output"` - * @returns {boolean} True if the pin is high after calling the function - * @url http://www.espruino.com/Reference#l_Pin_toggle - */ - toggle(): boolean; - - /** - * Get information about this pin and its capabilities. Of the form: - * ``` - * { - * "port" : "A", // the Pin's port on the chip - * "num" : 12, // the Pin's number - * "in_addr" : 0x..., // (if available) the address of the pin's input address in bit-banded memory (can be used with peek) - * "out_addr" : 0x..., // (if available) the address of the pin's output address in bit-banded memory (can be used with poke) - * "analog" : { ADCs : [1], channel : 12 }, // If analog input is available - * "functions" : { - * "TIM1":{type:"CH1, af:0}, - * "I2C3":{type:"SCL", af:1} - * } - * } - * ``` - * Will return undefined if pin is not valid. - * @returns {any} An object containing information about this pins - * @url http://www.espruino.com/Reference#l_Pin_getInfo - */ - getInfo(): any; -} - -interface DataViewConstructor { - /** - * Create a `DataView` object that can be used to access the data in an - * `ArrayBuffer`. - * ``` - * var b = new ArrayBuffer(8) - * var v = new DataView(b) - * v.setUint16(0,"0x1234") - * v.setUint8(3,"0x56") - * console.log("0x"+v.getUint32(0).toString(16)) - * // prints 0x12340056 - * ``` - * @constructor - * - * @param {any} buffer - The `ArrayBuffer` to base this on - * @param {number} byteOffset - (optional) The offset of this view in bytes - * @param {number} byteLength - (optional) The length in bytes - * @returns {any} A `DataView` object - * @url http://www.espruino.com/Reference#l_DataView_DataView - */ - new(buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; -} - -interface DataView { - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @returns {any} the index of the value in the array, or -1 - * @url http://www.espruino.com/Reference#l_DataView_getFloat32 - */ - getFloat32(byteOffset: number, littleEndian?: boolean): number; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @returns {any} the index of the value in the array, or -1 - * @url http://www.espruino.com/Reference#l_DataView_getFloat64 - */ - getFloat64(byteOffset: number, littleEndian?: boolean): number; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @returns {any} the index of the value in the array, or -1 - * @url http://www.espruino.com/Reference#l_DataView_getInt8 - */ - getInt8(byteOffset: number, littleEndian?: boolean): number; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @returns {any} the index of the value in the array, or -1 - * @url http://www.espruino.com/Reference#l_DataView_getInt16 - */ - getInt16(byteOffset: number, littleEndian?: boolean): number; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @returns {any} the index of the value in the array, or -1 - * @url http://www.espruino.com/Reference#l_DataView_getInt32 - */ - getInt32(byteOffset: number, littleEndian?: boolean): number; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @returns {any} the index of the value in the array, or -1 - * @url http://www.espruino.com/Reference#l_DataView_getUint8 - */ - getUint8(byteOffset: number, littleEndian?: boolean): number; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @returns {any} the index of the value in the array, or -1 - * @url http://www.espruino.com/Reference#l_DataView_getUint16 - */ - getUint16(byteOffset: number, littleEndian?: boolean): number; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @returns {any} the index of the value in the array, or -1 - * @url http://www.espruino.com/Reference#l_DataView_getUint32 - */ - getUint32(byteOffset: number, littleEndian?: boolean): number; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {any} value - The value to write - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @url http://www.espruino.com/Reference#l_DataView_setFloat32 - */ - setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {any} value - The value to write - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @url http://www.espruino.com/Reference#l_DataView_setFloat64 - */ - setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {any} value - The value to write - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @url http://www.espruino.com/Reference#l_DataView_setInt8 - */ - setInt8(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {any} value - The value to write - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @url http://www.espruino.com/Reference#l_DataView_setInt16 - */ - setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {any} value - The value to write - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @url http://www.espruino.com/Reference#l_DataView_setInt32 - */ - setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {any} value - The value to write - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @url http://www.espruino.com/Reference#l_DataView_setUint8 - */ - setUint8(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {any} value - The value to write - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @url http://www.espruino.com/Reference#l_DataView_setUint16 - */ - setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; - - /** - * - * @param {number} byteOffset - The offset in bytes to read from - * @param {any} value - The value to write - * @param {boolean} littleEndian - (optional) Whether to read in little endian - if false or undefined data is read as big endian - * @url http://www.espruino.com/Reference#l_DataView_setUint32 - */ - setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; -} - -/** - * This class helps - * @url http://www.espruino.com/Reference#DataView - */ -declare const DataView: DataViewConstructor - -/** - * This class allows use of the built-in USARTs - * Methods may be called on the `USB`, `Serial1`, `Serial2`, `Serial3`, `Serial4`, - * `Serial5` and `Serial6` objects. While different processors provide different - * numbers of USARTs, on official Espruino boards you can always rely on at least - * `Serial1` being available - * @url http://www.espruino.com/Reference#Serial - */ -declare class Serial { - /** - * The `data` event is called when data is received. If a handler is defined with - * `X.on('data', function(data) { ... })` then it will be called, otherwise data - * will be stored in an internal buffer, where it can be retrieved with `X.read()` - * @param {string} event - The event to listen to. - * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `data` A string containing one or more characters of received data - * @url http://www.espruino.com/Reference#l_Serial_data - */ - static on(event: "data", callback: (data: any) => void): void; - - /** - * The `framing` event is called when there was activity on the input to the UART - * but the `STOP` bit wasn't in the correct place. This is either because there was - * noise on the line, or the line has been pulled to 0 for a long period of time. - * To enable this, you must initialise Serial with `SerialX.setup(..., { ..., - * errors:true });` - * **Note:** Even though there was an error, the byte will still be received and - * passed to the `data` handler. - * **Note:** This only works on STM32 and NRF52 based devices (eg. all official - * Espruino boards) - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_Serial_framing - */ - static on(event: "framing", callback: () => void): void; - - /** - * The `parity` event is called when the UART was configured with a parity bit, and - * this doesn't match the bits that have actually been received. - * To enable this, you must initialise Serial with `SerialX.setup(..., { ..., - * errors:true });` - * **Note:** Even though there was an error, the byte will still be received and - * passed to the `data` handler. - * **Note:** This only works on STM32 and NRF52 based devices (eg. all official - * Espruino boards) - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_Serial_parity - */ - static on(event: "parity", callback: () => void): void; - - /** - * Try and find a USART (Serial) hardware device that will work on this pin (eg. - * `Serial1`) - * May return undefined if no device can be found. - * - * @param {Pin} pin - A pin to search with - * @returns {any} An object of type `Serial`, or `undefined` if one couldn't be found. - * @url http://www.espruino.com/Reference#l_Serial_find - */ - static find(pin: Pin): any; - - /** - * Create a software Serial port. This has limited functionality (only low baud - * rates), but it can work on any pins. - * Use `Serial.setup` to configure this port. - * @constructor - * @returns {any} A Serial object - * @url http://www.espruino.com/Reference#l_Serial_Serial - */ - static new(): any; - - /** - * Set this Serial port as the port for the JavaScript console (REPL). - * Unless `force` is set to true, changes in the connection state of the board (for - * instance plugging in USB) will cause the console to change. - * See `E.setConsole` for a more flexible version of this function. - * - * @param {boolean} force - Whether to force the console to this port - * @url http://www.espruino.com/Reference#l_Serial_setConsole - */ - setConsole(force: boolean): void; - - /** - * Setup this Serial port with the given baud rate and options. - * eg. - * ``` - * Serial1.setup(9600,{rx:a_pin, tx:a_pin}); - * ``` - * The second argument can contain: - * ``` - * { - * rx:pin, // Receive pin (data in to Espruino) - * tx:pin, // Transmit pin (data out of Espruino) - * ck:pin, // (default none) Clock Pin - * cts:pin, // (default none) Clear to Send Pin - * bytesize:8, // (default 8)How many data bits - 7 or 8 - * parity:null/'none'/'o'/'odd'/'e'/'even', - * // (default none) Parity bit - * stopbits:1, // (default 1) Number of stop bits to use - * flow:null/undefined/'none'/'xon', // (default none) software flow control - * path:null/undefined/string // Linux Only - the path to the Serial device to use - * errors:false // (default false) whether to forward framing/parity errors - * } - * ``` - * You can find out which pins to use by looking at [your board's reference - * page](#boards) and searching for pins with the `UART`/`USART` markers. - * If not specified in options, the default pins are used for rx and tx (usually - * the lowest numbered pins on the lowest port that supports this peripheral). `ck` - * and `cts` are not used unless specified. - * Note that even after changing the RX and TX pins, if you have called setup - * before then the previous RX and TX pins will still be connected to the Serial - * port as well - until you set them to something else using `digitalWrite` or - * `pinMode`. - * Flow control can be xOn/xOff (`flow:'xon'`) or hardware flow control (receive - * only) if `cts` is specified. If `cts` is set to a pin, the pin's value will be 0 - * when Espruino is ready for data and 1 when it isn't. - * By default, framing or parity errors don't create `framing` or `parity` events - * on the `Serial` object because storing these errors uses up additional storage - * in the queue. If you're intending to receive a lot of malformed data then the - * queue might overflow `E.getErrorFlags()` would return `FIFO_FULL`. However if - * you need to respond to `framing` or `parity` errors then you'll need to use - * `errors:true` when initialising serial. - * On Linux builds there is no default Serial device, so you must specify a path to - * a device - for instance: `Serial1.setup(9600,{path:"/dev/ttyACM0"})` - * You can also set up 'software serial' using code like: - * ``` - * var s = new Serial(); - * s.setup(9600,{rx:a_pin, tx:a_pin}); - * ``` - * However software serial doesn't use `ck`, `cts`, `parity`, `flow` or `errors` - * parts of the initialisation object. - * - * @param {any} baudrate - The baud rate - the default is 9600 - * @param {any} options - An optional structure containing extra information on initialising the serial port - see below. - * @url http://www.espruino.com/Reference#l_Serial_setup - */ - setup(baudrate: any, options: any): void; - - /** - * If the serial (or software serial) device was set up, uninitialise it. - * @url http://www.espruino.com/Reference#l_Serial_unsetup - */ - unsetup(): void; - - /** - * Print a string to the serial port - without a line feed - * **Note:** This function replaces any occurances of `\n` in the string with - * `\r\n`. To avoid this, use `Serial.write`. - * - * @param {any} string - A String to print - * @url http://www.espruino.com/Reference#l_Serial_print - */ - print(string: any): void; - - /** - * Print a line to the serial port with a newline (`\r\n`) at the end of it. - * **Note:** This function converts data to a string first, eg - * `Serial.print([1,2,3])` is equivalent to `Serial.print("1,2,3"). If you'd like - * to write raw bytes, use `Serial.write`. - * - * @param {any} string - A String to print - * @url http://www.espruino.com/Reference#l_Serial_println - */ - println(string: any): void; - - /** - * Write a character or array of data to the serial port - * This method writes unmodified data, eg `Serial.write([1,2,3])` is equivalent to - * `Serial.write("\1\2\3")`. If you'd like data converted to a string first, use - * `Serial.print`. - * - * @param {any} data - One or more items to write. May be ints, strings, arrays, or special objects (see `E.toUint8Array` for more info). - * @url http://www.espruino.com/Reference#l_Serial_write - */ - write(...data: any[]): void; - - /** - * Add data to this device as if it came directly from the input - it will be - * returned via `serial.on('data', ...)`; - * ``` - * Serial1.on('data', function(d) { print("Got",d); }); - * Serial1.inject('Hello World'); - * // prints "Got Hel","Got lo World" (characters can be split over multiple callbacks) - * ``` - * This is most useful if you wish to send characters to Espruino's REPL (console) - * while it is on another device. - * - * @param {any} data - One or more items to write. May be ints, strings, arrays, or special objects (see `E.toUint8Array` for more info). - * @url http://www.espruino.com/Reference#l_Serial_inject - */ - inject(...data: any[]): void; - - /** - * Return how many bytes are available to read. If there is already a listener for - * data, this will always return 0. - * @returns {number} How many bytes are available - * @url http://www.espruino.com/Reference#l_Serial_available - */ - available(): number; - - /** - * Return a string containing characters that have been received - * - * @param {number} chars - The number of characters to read, or undefined/0 for all available - * @returns {any} A string containing the required bytes. - * @url http://www.espruino.com/Reference#l_Serial_read - */ - read(chars: number): any; - - /** - * Pipe this USART to a stream (an object with a 'write' method) - * - * @param {any} destination - The destination file/stream that will receive content from the source. - * @param {any} options - * An optional object `{ chunkSize : int=32, end : bool=true, complete : function }` - * chunkSize : The amount of data to pipe from source to destination at a time - * complete : a function to call when the pipe activity is complete - * end : call the 'end' function on the destination when the source is finished - * @url http://www.espruino.com/Reference#l_Serial_pipe - */ - pipe(destination: any, options: any): void; -} - -/** - * These objects are created from `require("Storage").open` and allow Storage items - * to be read/written. - * The `Storage` library writes into Flash memory (which can only be erased in - * chunks), and unlike a normal filesystem it allocates files in one long - * contiguous area to allow them to be accessed easily from Espruino. - * This presents a challenge for `StorageFile` which allows you to append to a - * file, so instead `StorageFile` stores files in chunks. It uses the last - * character of the filename to denote the chunk number (eg `"foobar\1"`, - * `"foobar\2"`, etc). - * This means that while `StorageFile` files exist in the same area as those from - * `Storage`, they should be read using `Storage.open` (and not `Storage.read`). - * ``` - * f = s.open("foobar","w"); - * f.write("Hell"); - * f.write("o World\n"); - * f.write("Hello\n"); - * f.write("World 2\n"); - * // there's no need to call 'close' - * // then - * f = s.open("foobar","r"); - * f.read(13) // "Hello World\nH" - * f.read(13) // "ello\nWorld 2\n" - * f.read(13) // "Hello World 3" - * f.read(13) // "\n" - * f.read(13) // undefined - * // or - * f = s.open("foobar","r"); - * f.readLine() // "Hello World\n" - * f.readLine() // "Hello\n" - * f.readLine() // "World 2\n" - * f.readLine() // "Hello World 3\n" - * f.readLine() // undefined - * // now get rid of file - * f.erase(); - * ``` - * **Note:** `StorageFile` uses the fact that all bits of erased flash memory are 1 - * to detect the end of a file. As such you should not write character code 255 - * (`"\xFF"`) to these files. - * @url http://www.espruino.com/Reference#StorageFile - */ -declare class StorageFile { - - - /** - * Read 'len' bytes of data from the file, and return a String containing those - * bytes. - * If the end of the file is reached, the String may be smaller than the amount of - * bytes requested, or if the file is already at the end, `undefined` is returned. - * - * @param {number} len - How many bytes to read - * @returns {any} A String, or undefined - * @url http://www.espruino.com/Reference#l_StorageFile_read - */ - read(len: number): string; - - /** - * Read a line of data from the file (up to and including `"\n"`) - * @returns {any} A line of data - * @url http://www.espruino.com/Reference#l_StorageFile_readLine - */ - readLine(): string; - - /** - * Return the length of the current file. - * This requires Espruino to read the file from scratch, which is not a fast - * operation. - * @returns {number} The current length in bytes of the file - * @url http://www.espruino.com/Reference#l_StorageFile_getLength - */ - getLength(): number; - - /** - * Append the given data to a file. You should not attempt to append `"\xFF"` - * (character code 255). - * - * @param {any} data - The data to write. This should not include `'\xFF'` (character code 255) - * @url http://www.espruino.com/Reference#l_StorageFile_write - */ - write(data: string): void; - - /** - * Erase this file - * @url http://www.espruino.com/Reference#l_StorageFile_erase - */ - erase(): void; -} - -interface processConstructor { - /** - * This event is called when an exception gets thrown and isn't caught (eg. it gets - * all the way back to the event loop). - * You can use this for logging potential problems that might occur during - * execution when you might not be able to see what is written to the console, for - * example: - * ``` - * var lastError; - * process.on('uncaughtException', function(e) { - * lastError=e; - * print(e,e.stack?"\n"+e.stack:"") - * }); - * function checkError() { - * if (!lastError) return print("No Error"); - * print(lastError,lastError.stack?"\n"+lastError.stack:"") - * } - * ``` - * **Note:** When this is used, exceptions will cease to be reported on the - * console - which may make debugging difficult! - * @param {string} event - The event to listen to. - * @param {(exception: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `exception` The uncaught exception - * @url http://www.espruino.com/Reference#l_process_uncaughtException - */ - on(event: "uncaughtException", callback: (exception: any) => void): void; - - /** - * Returns the version of Espruino as a String - * @returns {any} The version of Espruino - * @url http://www.espruino.com/Reference#l_process_version - */ - version: any; - - /** - * Returns an Object containing various pre-defined variables. - * * `VERSION` - is the Espruino version - * * `GIT_COMMIT` - is Git commit hash this firmware was built from - * * `BOARD` - the board's ID (eg. `PUCKJS`) - * * `RAM` - total amount of on-chip RAM in bytes - * * `FLASH` - total amount of on-chip flash memory in bytes - * * `SPIFLASH` - (on Bangle.js) total amount of off-chip flash memory in bytes - * * `HWVERSION` - For Puck.js this is the board revision (1, 2, 2.1), or for - * Bangle.js it's 1 or 2 - * * `STORAGE` - memory in bytes dedicated to the `Storage` module - * * `SERIAL` - the serial number of this chip - * * `CONSOLE` - the name of the current console device being used (`Serial1`, - * `USB`, `Bluetooth`, etc) - * * `MODULES` - a list of built-in modules separated by commas - * * `EXPTR` - The address of the `exportPtrs` structure in flash (this includes - * links to built-in functions that compiled JS code needs) - * * `APP_RAM_BASE` - On nRF5x boards, this is the RAM required by the Softdevice - * *if it doesn't exactly match what was allocated*. You can use this to update - * `LD_APP_RAM_BASE` in the `BOARD.py` file - * For example, to get a list of built-in modules, you can use - * `process.env.MODULES.split(',')` - * @returns {any} An object - * @url http://www.espruino.com/Reference#l_process_env - */ - env: any; - - /** - * Run a Garbage Collection pass, and return an object containing information on - * memory usage. - * * `free` : Memory that is available to be used (in blocks) - * * `usage` : Memory that has been used (in blocks) - * * `total` : Total memory (in blocks) - * * `history` : Memory used for command history - that is freed if memory is low. - * Note that this is INCLUDED in the figure for 'free' - * * `gc` : Memory freed during the GC pass - * * `gctime` : Time taken for GC pass (in milliseconds) - * * `blocksize` : Size of a block (variable) in bytes - * * `stackEndAddress` : (on ARM) the address (that can be used with peek/poke/etc) - * of the END of the stack. The stack grows down, so unless you do a lot of - * recursion the bytes above this can be used. - * * `flash_start` : (on ARM) the address of the start of flash memory (usually - * `0x8000000`) - * * `flash_binary_end` : (on ARM) the address in flash memory of the end of - * Espruino's firmware. - * * `flash_code_start` : (on ARM) the address in flash memory of pages that store - * any code that you save with `save()`. - * * `flash_length` : (on ARM) the amount of flash memory this firmware was built - * for (in bytes). **Note:** Some STM32 chips actually have more memory than is - * advertised. - * Memory units are specified in 'blocks', which are around 16 bytes each - * (depending on your device). The actual size is available in `blocksize`. See - * http://www.espruino.com/Performance for more information. - * **Note:** To find free areas of flash memory, see `require('Flash').getFree()` - * - * @param {any} gc - An optional boolean. If `undefined` or `true` Garbage collection is performed, if `false` it is not - * @returns {any} Information about memory usage - * @url http://www.espruino.com/Reference#l_process_memory - */ - memory(gc: any): any; -} - -interface process { +interface Math { } /** - * This class contains information about Espruino itself - * @url http://www.espruino.com/Reference#process + * This is a standard JavaScript class that contains useful Maths routines + * @url http://www.espruino.com/Reference#Math */ -declare const process: processConstructor +declare const Math: MathConstructor /** * Built-in class that caches the modules used by the `require` command @@ -7568,870 +7208,126 @@ declare class Modules { } -interface StringConstructor { - /** - * Return the character(s) represented by the given character code(s). - * - * @param {any} code - One or more character codes to create a string from (range 0-255). - * @returns {any} The character - * @url http://www.espruino.com/Reference#l_String_fromCharCode - */ - fromCharCode(...code: any[]): any; - - /** - * Create a new String - * @constructor - * - * @param {any} str - A value to turn into a string. If undefined or not supplied, an empty String is created. - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_String_String - */ - new(...str: any[]): any; -} - -interface String { - /** - * Find the length of the string - * @returns {any} The value of the string - * @url http://www.espruino.com/Reference#l_String_length - */ - length: any; - - /** - * Return a single character at the given position in the String. - * - * @param {number} pos - The character number in the string. Negative values return characters from end of string (-1 = last char) - * @returns {any} The character in the string - * @url http://www.espruino.com/Reference#l_String_charAt - */ - charAt(pos: number): any; - - /** - * Return the integer value of a single character at the given position in the - * String. - * Note that this returns 0 not 'NaN' for out of bounds characters - * - * @param {number} pos - The character number in the string. Negative values return characters from end of string (-1 = last char) - * @returns {number} The integer value of a character in the string - * @url http://www.espruino.com/Reference#l_String_charCodeAt - */ - charCodeAt(pos: number): number; - - /** - * Return the index of substring in this string, or -1 if not found - * - * @param {any} substring - The string to search for - * @param {any} fromIndex - Index to search from - * @returns {number} The index of the string, or -1 if not found - * @url http://www.espruino.com/Reference#l_String_indexOf - */ - indexOf(substring: any, fromIndex: any): number; - - /** - * Return the last index of substring in this string, or -1 if not found - * - * @param {any} substring - The string to search for - * @param {any} fromIndex - Index to search from - * @returns {number} The index of the string, or -1 if not found - * @url http://www.espruino.com/Reference#l_String_lastIndexOf - */ - lastIndexOf(substring: any, fromIndex: any): number; - - /** - * Matches an occurrence `subStr` in the string. - * Returns `null` if no match, or: - * ``` - * "abcdef".match("b") == [ - * "b", // array index 0 - the matched string - * index: 1, // the start index of the match - * input: "b" // the input string - * ] - * "abcdefabcdef".match(/bcd/) == [ - * "bcd", index: 1, - * input: "abcdefabcdef" - * ] - * ``` - * 'Global' RegEx matches just return an array of matches (with no indices): - * ``` - * "abcdefabcdef".match(/bcd/g) = [ - * "bcd", - * "bcd" - * ] - * ``` - * - * @param {any} substr - Substring or RegExp to match - * @returns {any} A match array or `null` (see below): - * @url http://www.espruino.com/Reference#l_String_match - */ - match(substr: any): any; - - /** - * Search and replace ONE occurrance of `subStr` with `newSubStr` and return the - * result. This doesn't alter the original string. Regular expressions not - * supported. - * - * @param {any} subStr - The string to search for - * @param {any} newSubStr - The string to replace it with - * @returns {any} This string with `subStr` replaced - * @url http://www.espruino.com/Reference#l_String_replace - */ - replace(subStr: any, newSubStr: any): any; - - /** - * - * @param {number} start - The start character index (inclusive) - * @param {any} end - The end character index (exclusive) - * @returns {any} The part of this string between start and end - * @url http://www.espruino.com/Reference#l_String_substring - */ - substring(start: number, end: any): any; - - /** - * - * @param {number} start - The start character index - * @param {any} len - The number of characters - * @returns {any} Part of this string from start for len characters - * @url http://www.espruino.com/Reference#l_String_substr - */ - substr(start: number, len: any): any; - - /** - * - * @param {number} start - The start character index, if negative it is from the end of the string - * @param {any} end - The end character index, if negative it is from the end of the string, and if omitted it is the end of the string - * @returns {any} Part of this string from start for len characters - * @url http://www.espruino.com/Reference#l_String_slice - */ - slice(start: number, end: any): any; - - /** - * Return an array made by splitting this string up by the separator. eg. - * ```'1,2,3'.split(',')==['1', '2', '3']``` - * Regular Expressions can also be used to split strings, eg. `'1a2b3 - * 4'.split(/[^0-9]/)==['1', '2', '3', '4']`. - * - * @param {any} separator - The separator `String` or `RegExp` to use - * @returns {any} Part of this string from start for len characters - * @url http://www.espruino.com/Reference#l_String_split - */ - split(separator: any): any; - - /** - * - * @returns {any} The lowercase version of this string - * @url http://www.espruino.com/Reference#l_String_toLowerCase - */ - toLowerCase(): any; - - /** - * - * @returns {any} The uppercase version of this string - * @url http://www.espruino.com/Reference#l_String_toUpperCase - */ - toUpperCase(): any; - - /** - * Return a new string with any whitespace (tabs, space, form feed, newline, - * carriage return, etc) removed from the beginning and end. - * @returns {any} A String with Whitespace removed from the beginning and end - * @url http://www.espruino.com/Reference#l_String_trim - */ - trim(): string; - - /** - * Append all arguments to this `String` and return the result. Does not modify the - * original `String`. - * - * @param {any} args - Strings to append - * @returns {any} The result of appending all arguments to this string - * @url http://www.espruino.com/Reference#l_String_concat - */ - concat(...args: any[]): any; - - /** - * - * @param {any} searchString - The string to search for - * @param {number} position - The start character index (or 0 if not defined) - * @returns {boolean} `true` if the given characters are found at the beginning of the string, otherwise, `false`. - * @url http://www.espruino.com/Reference#l_String_startsWith - */ - startsWith(searchString: any, position: number): boolean; - - /** - * - * @param {any} searchString - The string to search for - * @param {any} length - The 'end' of the string - if left off the actual length of the string is used - * @returns {boolean} `true` if the given characters are found at the end of the string, otherwise, `false`. - * @url http://www.espruino.com/Reference#l_String_endsWith - */ - endsWith(searchString: any, length: any): boolean; - - /** - * - * @param {any} substring - The string to search for - * @param {any} fromIndex - The start character index (or 0 if not defined) - * @returns {boolean} `true` if the given characters are in the string, otherwise, `false`. - * @url http://www.espruino.com/Reference#l_String_includes - */ - includes(substring: any, fromIndex: any): boolean; - - /** - * Repeat this string the given number of times. - * - * @param {number} count - An integer with the amount of times to repeat this String - * @returns {any} A string containing repetitions of this string - * @url http://www.espruino.com/Reference#l_String_repeat - */ - repeat(count: number): string; - - /** - * Pad this string at the beginnind to the required number of characters - * ``` - * "Hello".padStart(10) == " Hello" - * "123".padStart(10,".-") == ".-.-.-.123" - * ``` - * - * @param {number} targetLength - The length to pad this string to - * @param {any} [padString] - [optional] The string to pad with, default is `' '` - * @returns {any} A string containing this string padded to the correct length - * @url http://www.espruino.com/Reference#l_String_padStart - */ - padStart(targetLength: number, padString?: any): string; - - /** - * Pad this string at the end to the required number of characters - * ``` - * "Hello".padEnd(10) == "Hello " - * "123".padEnd(10,".-") == "123.-.-.-." - * ``` - * - * @param {number} targetLength - The length to pad this string to - * @param {any} [padString] - [optional] The string to pad with, default is `' '` - * @returns {any} A string containing this string padded to the correct length - * @url http://www.espruino.com/Reference#l_String_padEnd - */ - padEnd(targetLength: number, padString?: any): string; -} - -/** - * This is the built-in class for Text Strings. - * Text Strings in Espruino are not zero-terminated, so you can store zeros in - * them. - * @url http://www.espruino.com/Reference#String - */ -declare const String: StringConstructor - -interface ArrayConstructor { - /** - * Returns true if the provided object is an array - * - * @param {any} var - The variable to be tested - * @returns {boolean} True if var is an array, false if not. - * @url http://www.espruino.com/Reference#l_Array_isArray - */ - isArray(arg: any): arg is any[]; - - /** - * Create an Array. Either give it one integer argument (>=0) which is the length - * of the array, or any number of arguments - * @constructor - * - * @param {any} args - The length of the array OR any number of items to add to the array - * @returns {any} An Array - * @url http://www.espruino.com/Reference#l_Array_Array - */ - new(arrayLength?: number): any[]; - new(arrayLength: number): T[]; - new(...items: T[]): T[]; - (arrayLength?: number): any[]; - (arrayLength: number): T[]; - (...items: T[]): T[]; -} - -interface Array { - /** - * Convert the Array to a string - * - * @param {any} radix - unused - * @returns {any} A String representing the array - * @url http://www.espruino.com/Reference#l_Array_toString - */ - toString(): string; - - /** - * Find the length of the array - * @returns {any} The length of the array - * @url http://www.espruino.com/Reference#l_Array_length - */ - length: number; - - /** - * Return the index of the value in the array, or -1 - * - * @param {any} value - The value to check for - * @param {number} startIndex - (optional) the index to search from, or 0 if not specified - * @returns {any} the index of the value in the array, or -1 - * @url http://www.espruino.com/Reference#l_Array_indexOf - */ - indexOf(value: T, startIndex?: number): number; - - /** - * Return `true` if the array includes the value, `false` otherwise - * - * @param {any} value - The value to check for - * @param {number} startIndex - (optional) the index to search from, or 0 if not specified - * @returns {boolean} `true` if the array includes the value, `false` otherwise - * @url http://www.espruino.com/Reference#l_Array_includes - */ - includes(value: T, startIndex?: number): boolean; - - /** - * Join all elements of this array together into one string, using 'separator' - * between them. e.g. ```[1,2,3].join(' ')=='1 2 3'``` - * - * @param {any} separator - The separator - * @returns {any} A String representing the Joined array - * @url http://www.espruino.com/Reference#l_Array_join - */ - join(separator?: string): string; - - /** - * Push a new value onto the end of this array' - * This is the opposite of `[1,2,3].unshift(0)`, which adds one or more elements to - * the beginning of the array. - * - * @param {any} arguments - One or more arguments to add - * @returns {number} The new size of the array - * @url http://www.espruino.com/Reference#l_Array_push - */ - push(...arguments: T[]): number; - - /** - * Remove and return the value on the end of this array. - * This is the opposite of `[1,2,3].shift()`, which removes an element from the - * beginning of the array. - * @returns {any} The value that is popped off - * @url http://www.espruino.com/Reference#l_Array_pop - */ - pop(): T | undefined; - - /** - * Return an array which is made from the following: ```A.map(function) = - * [function(A[0]), function(A[1]), ...]``` - * - * @param {any} function - Function used to map one item to another - * @param {any} thisArg - if specified, the function is called with 'this' set to thisArg (optional) - * @returns {any} An array containing the results - * @url http://www.espruino.com/Reference#l_Array_map - */ - map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - - /** - * Executes a provided function once per array element. - * - * @param {any} function - Function to be executed - * @param {any} [thisArg] - [optional] If specified, the function is called with 'this' set to thisArg (optional) - * @url http://www.espruino.com/Reference#l_Array_forEach - */ - forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - - /** - * Return an array which contains only those elements for which the callback - * function returns 'true' - * - * @param {any} function - Function to be executed - * @param {any} thisArg - if specified, the function is called with 'this' set to thisArg (optional) - * @returns {any} An array containing the results - * @url http://www.espruino.com/Reference#l_Array_filter - */ - filter(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; - filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[]; - - /** - * Return the array element where `function` returns `true`, or `undefined` if it - * doesn't returns `true` for any element. - * ``` - * ["Hello","There","World"].find(a=>a[0]=="T") - * // returns "There" - * ``` - * - * @param {any} function - Function to be executed - * @returns {any} The array element where `function` returns `true`, or `undefined` - * @url http://www.espruino.com/Reference#l_Array_find - */ - find(predicate: (this: void, value: T, index: number, obj: T[]) => value is S): S | undefined; - find(predicate: (value: T, index: number, obj: T[]) => unknown): T | undefined; - - /** - * Return the array element's index where `function` returns `true`, or `-1` if it - * doesn't returns `true` for any element. - * ``` - * ["Hello","There","World"].findIndex(a=>a[0]=="T") - * // returns 1 - * ``` - * - * @param {any} function - Function to be executed - * @returns {any} The array element's index where `function` returns `true`, or `-1` - * @url http://www.espruino.com/Reference#l_Array_findIndex - */ - findIndex(predicate: (value: T, index: number, obj: T[]) => unknown): number; - - /** - * Return 'true' if the callback returns 'true' for any of the elements in the - * array - * - * @param {any} function - Function to be executed - * @param {any} thisArg - if specified, the function is called with 'this' set to thisArg (optional) - * @returns {any} A boolean containing the result - * @url http://www.espruino.com/Reference#l_Array_some - */ - some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean; - - /** - * Return 'true' if the callback returns 'true' for every element in the array - * - * @param {any} function - Function to be executed - * @param {any} thisArg - if specified, the function is called with 'this' set to thisArg (optional) - * @returns {any} A boolean containing the result - * @url http://www.espruino.com/Reference#l_Array_every - */ - every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean; - - /** - * Execute `previousValue=initialValue` and then `previousValue = - * callback(previousValue, currentValue, index, array)` for each element in the - * array, and finally return previousValue. - * - * @param {any} callback - Function used to reduce the array - * @param {any} initialValue - if specified, the initial value to pass to the function - * @returns {any} The value returned by the last function called - * @url http://www.espruino.com/Reference#l_Array_reduce - */ - reduce(callback: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - - /** - * Both remove and add items to an array - * - * @param {number} index - Index at which to start changing the array. If negative, will begin that many elements from the end - * @param {any} howMany - An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. - * @param {any} elements - One or more items to add to the array - * @returns {any} An array containing the removed elements. If only one element is removed, an array of one element is returned. - * @url http://www.espruino.com/Reference#l_Array_splice - */ - splice(index: number, howMany?: number, ...elements: T[]): T[]; - - /** - * Remove and return the first element of the array. - * This is the opposite of `[1,2,3].pop()`, which takes an element off the end. - * - * @returns {any} The element that was removed - * @url http://www.espruino.com/Reference#l_Array_shift - */ - shift(): T | undefined; - - /** - * Add one or more items to the start of the array, and return its new length. - * This is the opposite of `[1,2,3].push(4)`, which puts one or more elements on - * the end. - * - * @param {any} elements - One or more items to add to the beginning of the array - * @returns {number} The new array length - * @url http://www.espruino.com/Reference#l_Array_unshift - */ - unshift(...elements: T[]): number; - - /** - * Return a copy of a portion of this array (in a new array) - * - * @param {number} start - Start index - * @param {any} end - End index (optional) - * @returns {any} A new array - * @url http://www.espruino.com/Reference#l_Array_slice - */ - slice(start?: number, end?: number): T[]; - - /** - * Do an in-place quicksort of the array - * - * @param {any} var - A function to use to compare array elements (or undefined) - * @returns {any} This array object - * @url http://www.espruino.com/Reference#l_Array_sort - */ - sort(compareFn?: (a: T, b: T) => number): T[]; - - /** - * Create a new array, containing the elements from this one and any arguments, if - * any argument is an array then those elements will be added. - * - * @param {any} args - Any items to add to the array - * @returns {any} An Array - * @url http://www.espruino.com/Reference#l_Array_concat - */ - concat(...args: (T | T[])[]): T[]; - - /** - * Fill this array with the given value, for every index `>= start` and `< end` - * - * @param {any} value - The value to fill the array with - * @param {number} start - Optional. The index to start from (or 0). If start is negative, it is treated as length+start where length is the length of the array - * @param {any} end - Optional. The index to end at (or the array length). If end is negative, it is treated as length+end. - * @returns {any} This array - * @url http://www.espruino.com/Reference#l_Array_fill - */ - fill(value: T, start: number, end?: number): T[]; - - /** - * Reverse all elements in this array (in place) - * @returns {any} The array, but reversed. - * @url http://www.espruino.com/Reference#l_Array_reverse - */ - reverse(): T[]; - - [index: number]: T -} - -/** - * This is the built-in JavaScript class for arrays. - * Arrays can be defined with ```[]```, ```new Array()```, or ```new - * Array(length)``` - * @url http://www.espruino.com/Reference#Array - */ -declare const Array: ArrayConstructor - -interface ObjectConstructor { - /** - * Return all enumerable keys of the given object - * - * @param {any} object - The object to return keys for - * @returns {any} An array of strings - one for each key on the given object - * @url http://www.espruino.com/Reference#l_Object_keys - */ - keys(object: any): any; - - /** - * Returns an array of all properties (enumerable or not) found directly on a given - * object. - * - * @param {any} object - The Object to return a list of property names for - * @returns {any} An array of the Object's own properties - * @url http://www.espruino.com/Reference#l_Object_getOwnPropertyNames - */ - getOwnPropertyNames(object: any): any; - - /** - * Return all enumerable values of the given object - * - * @param {any} object - The object to return values for - * @returns {any} An array of values - one for each key on the given object - * @url http://www.espruino.com/Reference#l_Object_values - */ - values(object: any): any; - - /** - * Return all enumerable keys and values of the given object - * - * @param {any} object - The object to return values for - * @returns {any} An array of `[key,value]` pairs - one for each key on the given object - * @url http://www.espruino.com/Reference#l_Object_entries - */ - entries(object: any): any; - - /** - * Creates a new object with the specified prototype object and properties. - * properties are currently unsupported. - * - * @param {any} proto - A prototype object - * @param {any} propertiesObject - An object containing properties. NOT IMPLEMENTED - * @returns {any} A new object - * @url http://www.espruino.com/Reference#l_Object_create - */ - create(proto: any, propertiesObject: any): any; - - /** - * Get information on the given property in the object, or undefined - * - * @param {any} obj - The object - * @param {any} name - The name of the property - * @returns {any} An object with a description of the property. The values of writable/enumerable/configurable may not be entirely correct due to Espruino's implementation. - * @url http://www.espruino.com/Reference#l_Object_getOwnPropertyDescriptor - */ - getOwnPropertyDescriptor(obj: any, name: any): any; - - /** - * Add a new property to the Object. 'Desc' is an object with the following fields: - * * `configurable` (bool = false) - can this property be changed/deleted (not - * implemented) - * * `enumerable` (bool = false) - can this property be enumerated (not - * implemented) - * * `value` (anything) - the value of this property - * * `writable` (bool = false) - can the value be changed with the assignment - * operator? - * * `get` (function) - the getter function, or undefined if no getter (only - * supported on some platforms) - * * `set` (function) - the setter function, or undefined if no setter (only - * supported on some platforms) - * **Note:** `configurable`, `enumerable` and `writable` are not implemented and - * will be ignored. - * - * @param {any} obj - An object - * @param {any} name - The name of the property - * @param {any} desc - The property descriptor - * @returns {any} The object, obj. - * @url http://www.espruino.com/Reference#l_Object_defineProperty - */ - defineProperty(obj: any, name: any, desc: any): any; - - /** - * Adds new properties to the Object. See `Object.defineProperty` for more - * information - * - * @param {any} obj - An object - * @param {any} props - An object whose fields represent property names, and whose values are property descriptors. - * @returns {any} The object, obj. - * @url http://www.espruino.com/Reference#l_Object_defineProperties - */ - defineProperties(obj: any, props: any): any; - - /** - * Get the prototype of the given object - this is like writing `object.__proto__` - * but is the 'proper' ES6 way of doing it - * - * @param {any} object - An object - * @returns {any} The prototype - * @url http://www.espruino.com/Reference#l_Object_getPrototypeOf - */ - getPrototypeOf(object: any): any; - - /** - * Set the prototype of the given object - this is like writing `object.__proto__ = - * prototype` but is the 'proper' ES6 way of doing it - * - * @param {any} object - An object - * @param {any} prototype - The prototype to set on the object - * @returns {any} The object passed in - * @url http://www.espruino.com/Reference#l_Object_setPrototypeOf - */ - setPrototypeOf(object: any, prototype: any): any; - - /** - * Appends all keys and values in any subsequent objects to the first object - * **Note:** Unlike the standard ES6 `Object.assign`, this will throw an exception - * if given raw strings, bools or numbers rather than objects. - * - * @param {any} args - The target object, then any items objects to use as sources of keys - * @returns {any} The target object - * @url http://www.espruino.com/Reference#l_Object_assign - */ - assign(...args: any[]): any; - - /** - * Creates an Object from the supplied argument - * @constructor - * - * @param {any} value - A single value to be converted to an object - * @returns {any} An Object - * @url http://www.espruino.com/Reference#l_Object_Object - */ - new(value: any): any; -} - -interface Object { - /** - * Find the length of the object - * @returns {any} The length of the object - * @url http://www.espruino.com/Reference#l_Object_length - */ - length: any; - - /** - * Returns the primitive value of this object. - * @returns {any} The primitive value of this object - * @url http://www.espruino.com/Reference#l_Object_valueOf - */ - valueOf(): any; - - /** - * Convert the Object to a string - * - * @param {any} radix - If the object is an integer, the radix (between 2 and 36) to use. NOTE: Setting a radix does not work on floating point numbers. - * @returns {any} A String representing the object - * @url http://www.espruino.com/Reference#l_Object_toString - */ - toString(radix: any): any; - - /** - * Copy this object completely - * @returns {any} A copy of this Object - * @url http://www.espruino.com/Reference#l_Object_clone - */ - clone(): any; - - /** - * Return true if the object (not its prototype) has the given property. - * NOTE: This currently returns false-positives for built-in functions in - * prototypes - * - * @param {any} name - The name of the property to search for - * @returns {boolean} True if it exists, false if it doesn't - * @url http://www.espruino.com/Reference#l_Object_hasOwnProperty - */ - hasOwnProperty(name: any): boolean; - - /** - * Register an event listener for this object, for instance `Serial1.on('data', - * function(d) {...})`. - * This is the same as Node.js's [EventEmitter](https://nodejs.org/api/events.html) - * but on Espruino the functionality is built into every object: - * * `Object.on` - * * `Object.emit` - * * `Object.removeListener` - * * `Object.removeAllListeners` - * ``` - * var o = {}; // o can be any object... - * // call an arrow function when the 'answer' event is received - * o.on('answer', x => console.log(x)); - * // call a named function when the 'answer' event is received - * function printAnswer(d) { - * console.log("The answer is", d); - * } - * o.on('answer', printAnswer); - * // emit the 'answer' event - functions added with 'on' will be executed - * o.emit('answer', 42); - * // prints: 42 - * // prints: The answer is 42 - * // If you have a named function, it can be removed by name - * o.removeListener('answer', printAnswer); - * // Now 'printAnswer' is removed - * o.emit('answer', 43); - * // prints: 43 - * // Or you can remove all listeners for 'answer' - * o.removeAllListeners('answer') - * // Now nothing happens - * o.emit('answer', 44); - * // nothing printed - * ``` - * - * @param {any} event - The name of the event, for instance 'data' - * @param {any} listener - The listener to call when this event is received - * @url http://www.espruino.com/Reference#l_Object_on - */ - on(event: any, listener: any): void; - - /** - * Call any event listeners that were added to this object with `Object.on`, for - * instance `obj.emit('data', 'Foo')`. - * For more information see `Object.on` - * - * @param {any} event - The name of the event, for instance 'data' - * @param {any} args - Optional arguments - * @url http://www.espruino.com/Reference#l_Object_emit - */ - emit(event: any, ...args: any[]): void; - - /** - * Removes the specified event listener. - * ``` - * function foo(d) { - * console.log(d); - * } - * Serial1.on("data", foo); - * Serial1.removeListener("data", foo); - * ``` - * For more information see `Object.on` - * - * @param {any} event - The name of the event, for instance 'data' - * @param {any} listener - The listener to remove - * @url http://www.espruino.com/Reference#l_Object_removeListener - */ - removeListener(event: any, listener: any): void; - - /** - * Removes all listeners (if `event===undefined`), or those of the specified event. - * ``` - * Serial1.on("data", function(data) { ... }); - * Serial1.removeAllListeners("data"); - * // or - * Serial1.removeAllListeners(); // removes all listeners for all event types - * ``` - * For more information see `Object.on` - * - * @param {any} event - The name of the event, for instance `'data'`. If not specified *all* listeners are removed. - * @url http://www.espruino.com/Reference#l_Object_removeAllListeners - */ - removeAllListeners(event: any): void; -} - -/** - * This is the built-in class for Objects - * @url http://www.espruino.com/Reference#Object - */ -declare const Object: ObjectConstructor - -interface FunctionConstructor { - /** - * Creates a function - * @constructor - * - * @param {any} args - Zero or more arguments (as strings), followed by a string representing the code to run - * @returns {any} A Number object - * @url http://www.espruino.com/Reference#l_Function_Function - */ - new(...args: any[]): any; -} - -interface Function { - /** - * This replaces the function with the one in the argument - while keeping the old - * function's scope. This allows inner functions to be edited, and is used when - * edit() is called on an inner function. - * - * @param {any} newFunc - The new function to replace this function with - * @url http://www.espruino.com/Reference#l_Function_replaceWith - */ - replaceWith(newFunc: any): void; - - /** - * This executes the function with the supplied 'this' argument and parameters - * - * @param {any} this - The value to use as the 'this' argument when executing the function - * @param {any} params - Optional Parameters - * @returns {any} The return value of executing this function - * @url http://www.espruino.com/Reference#l_Function_call - */ - call(this: any, ...params: any[]): any; - - /** - * This executes the function with the supplied 'this' argument and parameters - * - * @param {any} this - The value to use as the 'this' argument when executing the function - * @param {any} args - Optional Array of Arguments - * @returns {any} The return value of executing this function - * @url http://www.espruino.com/Reference#l_Function_apply - */ - apply(this: any, args: any): any; - - /** - * This executes the function with the supplied 'this' argument and parameters - * - * @param {any} this - The value to use as the 'this' argument when executing the function - * @param {any} params - Optional Default parameters that are prepended to the call - * @returns {any} The 'bound' function - * @url http://www.espruino.com/Reference#l_Function_bind - */ - bind(this: any, ...params: any[]): any; -} - -/** - * This is the built-in class for Functions - * @url http://www.espruino.com/Reference#Function - */ -declare const Function: FunctionConstructor - /** * This is the built-in JavaScript class for Espruino utility functions. * @url http://www.espruino.com/Reference#E */ declare class E { + /** + * Display a menu on the screen, and set up the buttons to navigate through it. + * Supply an object containing menu items. When an item is selected, the function + * it references will be executed. For example: + * ``` + * var boolean = false; + * var number = 50; + * // First menu + * var mainmenu = { + * "" : { "title" : "-- Main Menu --" }, + * "Backlight On" : function() { LED1.set(); }, + * "Backlight Off" : function() { LED1.reset(); }, + * "Submenu" : function() { E.showMenu(submenu); }, + * "A Boolean" : { + * value : boolean, + * format : v => v?"On":"Off", + * onchange : v => { boolean=v; } + * }, + * "A Number" : { + * value : number, + * min:0,max:100,step:10, + * onchange : v => { number=v; } + * }, + * "Exit" : function() { E.showMenu(); }, // remove the menu + * }; + * // Submenu + * var submenu = { + * "" : { title : "-- SubMenu --", + * back : function() { E.showMenu(mainmenu); } }, + * "One" : undefined, // do nothing + * "Two" : undefined // do nothing + * }; + * // Actually display the menu + * E.showMenu(mainmenu); + * ``` + * The menu will stay onscreen and active until explicitly removed, which you can + * do by calling `E.showMenu()` without arguments. + * See http://www.espruino.com/graphical_menu for more detailed information. + * + * @param {any} menu - An object containing name->function mappings to to be used in a menu + * @returns {any} A menu object with `draw`, `move` and `select` functions + * @url http://www.espruino.com/Reference#l_E_showMenu + */ + static showMenu(menu: Menu): MenuInstance; + static showMenu(): void; + + /** + * A utility function for displaying a full screen message on the screen. + * Draws to the screen and returns immediately. + * ``` + * E.showMessage("These are\nLots of\nLines","My Title") + * ``` + * + * @param {any} message - A message to display. Can include newlines + * @param {any} [title] - [optional] a title for the message + * @url http://www.espruino.com/Reference#l_E_showMessage + */ + static showMessage(message: string, title?: string): void; + + /** + * Displays a full screen prompt on the screen, with the buttons requested (or + * `Yes` and `No` for defaults). + * When the button is pressed the promise is resolved with the requested values + * (for the `Yes` and `No` defaults, `true` and `false` are returned). + * ``` + * E.showPrompt("Do you like fish?").then(function(v) { + * if (v) print("'Yes' chosen"); + * else print("'No' chosen"); + * }); + * // Or + * E.showPrompt("How many fish\ndo you like?",{ + * title:"Fish", + * buttons : {"One":1,"Two":2,"Three":3} + * }).then(function(v) { + * print("You like "+v+" fish"); + * }); + * ``` + * To remove the prompt, call `E.showPrompt()` with no arguments. + * The second `options` argument can contain: + * ``` + * { + * title: "Hello", // optional Title + * buttons : {"Ok":true,"Cancel":false} // list of button text & return value + * } + * ``` + * + * @param {any} message - A message to display. Can include newlines + * @param {any} [options] - [optional] an object of options (see below) + * @returns {any} A promise that is resolved when 'Ok' is pressed + * @url http://www.espruino.com/Reference#l_E_showPrompt + */ + static showPrompt(message: string, options?: { title?: string, buttons?: { [key: string]: T } }): Promise; + static showPrompt(): void; + + /** + * Displays a full screen prompt on the screen, with a single 'Ok' button. + * When the button is pressed the promise is resolved. + * ``` + * E.showAlert("Hello").then(function() { + * print("Ok pressed"); + * }); + * // or + * E.showAlert("These are\nLots of\nLines","My Title").then(function() { + * print("Ok pressed"); + * }); + * ``` + * To remove the window, call `E.showAlert()` with no arguments. + * + * @param {any} message - A message to display. Can include newlines + * @param {any} [options] - [optional] a title for the message + * @returns {any} A promise that is resolved when 'Ok' is pressed + * @url http://www.espruino.com/Reference#l_E_showAlert + */ + static showAlert(message?: string, options?: string): Promise; + /** * Setup the filesystem so that subsequent calls to `E.openFile` and * `require('fs').*` will use an SD card on the supplied SPI device and pin. @@ -8497,174 +7393,15 @@ declare class E { * format once, as each will erase the content. * `E.flashFatFS({ addr:0x300000,sectors:100,format:true });` * - * @param {any} options - * An optional object `{ addr : int=0x300000, sectors : int=256, format : bool=false }` + * @param {any} [options] + * [optional] An object `{ addr : int=0x300000, sectors : int=256, format : bool=false }` * addr : start address in flash * sectors: number of sectors to use * format: Format the media * @returns {boolean} True on success, or false on failure * @url http://www.espruino.com/Reference#l_E_flashFatFS */ - static flashFatFS(options: any): boolean; - - /** - * Display a menu on the screen, and set up the buttons to navigate through it. - * Supply an object containing menu items. When an item is selected, the function - * it references will be executed. For example: - * ``` - * var boolean = false; - * var number = 50; - * // First menu - * var mainmenu = { - * "" : { "title" : "-- Main Menu --" }, - * "Backlight On" : function() { LED1.set(); }, - * "Backlight Off" : function() { LED1.reset(); }, - * "Submenu" : function() { E.showMenu(submenu); }, - * "A Boolean" : { - * value : boolean, - * format : v => v?"On":"Off", - * onchange : v => { boolean=v; } - * }, - * "A Number" : { - * value : number, - * min:0,max:100,step:10, - * onchange : v => { number=v; } - * }, - * "Exit" : function() { E.showMenu(); }, // remove the menu - * }; - * // Submenu - * var submenu = { - * "" : { title : "-- SubMenu --", - * back : function() { E.showMenu(mainmenu); } }, - * "One" : undefined, // do nothing - * "Two" : undefined // do nothing - * }; - * // Actually display the menu - * E.showMenu(mainmenu); - * ``` - * The menu will stay onscreen and active until explicitly removed, which you can - * do by calling `E.showMenu()` without arguments. - * See http://www.espruino.com/graphical_menu for more detailed information. - * - * @param {any} menu - An object containing name->function mappings to to be used in a menu - * @returns {any} A menu object with `draw`, `move` and `select` functions - * @url http://www.espruino.com/Reference#l_E_showMenu - */ - static showMenu(menu: Menu): MenuInstance; - static showMenu(): void; - - /** - * A utility function for displaying a full screen message on the screen. - * Draws to the screen and returns immediately. - * ``` - * E.showMessage("These are\nLots of\nLines","My Title") - * ``` - * - * @param {any} message - A message to display. Can include newlines - * @param {any} title - (optional) a title for the message - * @url http://www.espruino.com/Reference#l_E_showMessage - */ - static showMessage(message: string, title?: string): void; - - /** - * Displays a full screen prompt on the screen, with the buttons requested (or - * `Yes` and `No` for defaults). - * When the button is pressed the promise is resolved with the requested values - * (for the `Yes` and `No` defaults, `true` and `false` are returned). - * ``` - * E.showPrompt("Do you like fish?").then(function(v) { - * if (v) print("'Yes' chosen"); - * else print("'No' chosen"); - * }); - * // Or - * E.showPrompt("How many fish\ndo you like?",{ - * title:"Fish", - * buttons : {"One":1,"Two":2,"Three":3} - * }).then(function(v) { - * print("You like "+v+" fish"); - * }); - * ``` - * To remove the prompt, call `E.showPrompt()` with no arguments. - * The second `options` argument can contain: - * ``` - * { - * title: "Hello", // optional Title - * buttons : {"Ok":true,"Cancel":false} // list of button text & return value - * } - * ``` - * - * @param {any} message - A message to display. Can include newlines - * @param {any} options - (optional) an object of options (see below) - * @returns {any} A promise that is resolved when 'Ok' is pressed - * @url http://www.espruino.com/Reference#l_E_showPrompt - */ - static showPrompt(message: string, options?: { title?: string, buttons?: { [key: string]: T } }): Promise; - static showPrompt(): void; - - /** - * Displays a full screen prompt on the screen, with a single 'Ok' button. - * When the button is pressed the promise is resolved. - * ``` - * E.showAlert("Hello").then(function() { - * print("Ok pressed"); - * }); - * // or - * E.showAlert("These are\nLots of\nLines","My Title").then(function() { - * print("Ok pressed"); - * }); - * ``` - * To remove the window, call `E.showAlert()` with no arguments. - * - * @param {any} message - A message to display. Can include newlines - * @param {any} options - (optional) a title for the message - * @returns {any} A promise that is resolved when 'Ok' is pressed - * @url http://www.espruino.com/Reference#l_E_showAlert - */ - static showAlert(message?: string, options?: string): Promise; - - /** - * Called when a notification arrives on an Apple iOS device Bangle.js is connected - * to - * ``` - * { - * event:"add", - * uid:42, - * category:4, - * categoryCnt:42, - * silent:true, - * important:false, - * preExisting:true, - * positive:false, - * negative:true - * } - * ``` - * You can then get more information with something like: - * ``` - * NRF.ancsGetNotificationInfo( event.uid ).then(a=>print("Notify",E.toJS(a))); - * ``` - * @param {string} event - The event to listen to. - * @param {(info: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `info` An object (see below) - * @url http://www.espruino.com/Reference#l_E_ANCS - */ - static on(event: "ANCS", callback: (info: any) => void): void; - - /** - * Called when a media event arrives on an Apple iOS device Bangle.js is connected - * to - * ``` - * { - * id : "artist"/"album"/"title"/"duration", - * value : "Some text", - * truncated : bool // the 'value' was too big to be sent completely - * } - * ``` - * @param {string} event - The event to listen to. - * @param {(info: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `info` An object (see below) - * @url http://www.espruino.com/Reference#l_E_AMS - */ - static on(event: "AMS", callback: (info: any) => void): void; + static flashFatFS(options?: any): boolean; /** * Display a menu on the screen, and set up the buttons to navigate through it. @@ -8708,6 +7445,8 @@ declare class E { * * The options object can contain: * * `back : function() { }` - add a 'back' button, with the function called when * it is pressed + * * `remove : function() { }` - add a handler function to be called when the + * menu is removed * * (Bangle.js 2) `scroll : int` - an integer specifying how much the initial * menu should be scrolled by * * The object returned by `E.showMenu` contains: @@ -8752,7 +7491,7 @@ declare class E { * ``` * * @param {any} message - A message to display. Can include newlines - * @param {any} options - (optional) a title for the message, or an object of options `{title:string, img:image_string}` + * @param {any} [options] - [optional] a title for the message, or an object of options `{title:string, img:image_string}` * @url http://www.espruino.com/Reference#l_E_showMessage */ static showMessage(message: string, title?: string | { title?: string, img?: string }): void; @@ -8789,15 +7528,16 @@ declare class E { * title: "Hello", // optional Title * buttons : {"Ok":true,"Cancel":false}, // optional list of button text & return value * img: "image_string" // optional image string to draw + * remove: function() { } // Bangle.js: optional function to be called when the prompt is removed * } * ``` * * @param {any} message - A message to display. Can include newlines - * @param {any} options - (optional) an object of options (see below) + * @param {any} [options] - [optional] an object of options (see below) * @returns {any} A promise that is resolved when 'Ok' is pressed * @url http://www.espruino.com/Reference#l_E_showPrompt */ - static showPrompt(message: string, options?: { title?: string, buttons?: { [key: string]: T } }): Promise; + static showPrompt(message: string, options?: { title?: string, buttons?: { [key: string]: T }, image?: string, remove?: () => void }): Promise; static showPrompt(): void; /** @@ -8810,10 +7550,13 @@ declare class E { * c : 10, // number of menu items * // a function to draw a menu item * draw : function(idx, rect) { ... } - * // a function to call when the item is selected - * select : function(idx) { ... } + * // a function to call when the item is selected, touch parameter is only relevant + * // for Bangle.js 2 and contains the coordinates touched inside the selected item + * select : function(idx, touch) { ... } * // optional function to be called when 'back' is tapped * back : function() { ...} + * // Bangle.js: optional function to be called when the scroller should be removed + * remove : function() {} * } * ``` * For example to display a list of numbers: @@ -8829,11 +7572,11 @@ declare class E { * ``` * To remove the scroller, just call `E.showScroller()` * - * @param {any} options - An object containing `{ h, c, draw, select }` (see below) + * @param {any} options - An object containing `{ h, c, draw, select, back, remove }` (see below) * @returns {any} A menu object with `draw()` and `drawItem(itemNo)` functions * @url http://www.espruino.com/Reference#l_E_showScroller */ - static showScroller(options?: { h: number, c: number, draw: (idx: number, rect: { x: number, y: number, w: number, h: number }) => void, select: (idx: number) => void, back?: () => void }): { draw: () => void, drawItem: (itemNo: number) => void }; + static showScroller(options?: { h: number, c: number, draw: (idx: number, rect: { x: number, y: number, w: number, h: number }) => void, select: (idx: number, touch?: {x: number, y: number}) => void, back?: () => void, remove?: () => void }): { draw: () => void, drawItem: (itemNo: number) => void }; static showScroller(): void; /** @@ -8871,11 +7614,58 @@ declare class E { * To remove the window, call `E.showAlert()` with no arguments. * * @param {any} message - A message to display. Can include newlines - * @param {any} options - (optional) a title for the message + * @param {any} [options] - [optional] a title for the message or an object containing options * @returns {any} A promise that is resolved when 'Ok' is pressed * @url http://www.espruino.com/Reference#l_E_showAlert */ static showAlert(message?: string, options?: string): Promise; + static showAlert(message?: string, options?: { title?: string, remove?: () => void }): Promise; + + /** + * Called when a notification arrives on an Apple iOS device Bangle.js is connected + * to + * ``` + * { + * event:"add", + * uid:42, + * category:4, + * categoryCnt:42, + * silent:true, + * important:false, + * preExisting:true, + * positive:false, + * negative:true + * } + * ``` + * You can then get more information with `NRF.ancsGetNotificationInfo`, for instance: + * ``` + * E.on('ANCS', event => { + * NRF.ancsGetNotificationInfo( event.uid ).then(a=>print("Notify",E.toJS(a))); + * }); + * ``` + * @param {string} event - The event to listen to. + * @param {(info: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `info` An object (see below) + * @url http://www.espruino.com/Reference#l_E_ANCS + */ + static on(event: "ANCS", callback: (info: any) => void): void; + + /** + * Called when a media event arrives on an Apple iOS device Bangle.js is connected + * to + * ``` + * { + * id : "artist"/"album"/"title"/"duration", + * value : "Some text", + * truncated : bool // the 'value' was too big to be sent completely + * } + * ``` + * @param {string} event - The event to listen to. + * @param {(info: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `info` An object (see below) + * @url http://www.espruino.com/Reference#l_E_AMS + */ + static on(event: "AMS", callback: (info: any) => void): void; /** * This event is called right after the board starts up, and has a similar effect @@ -9081,12 +7871,13 @@ declare class E { * // Espruino will now reset if everything_ok is false, * // or if the interval fails to be called * ``` - * **NOTE:** This is only implemented on STM32 and nRF5x devices (all official + * **NOTE:** This is only implemented on STM32, nRF5x and ESP32 devices (all official * Espruino boards). * **NOTE:** On STM32 (Pico, WiFi, Original) with `setDeepSleep(1)` you need to * explicitly wake Espruino up with an interval of less than the watchdog timeout * or the watchdog will fire and the board will reboot. You can do this with * `setInterval("", time_in_milliseconds)`. + * **NOTE:** On ESP32, the timeout will be rounded to the nearest second. * * @param {number} timeout - The timeout in seconds before a watchdog reset * @param {any} isAuto - If undefined or true, the watchdog is kicked automatically. If not, you must call `E.kickWatchdog()` yourself @@ -9153,8 +7944,8 @@ declare class E { * * @param {any} source - The source file/stream that will send content. * @param {any} destination - The destination file/stream that will receive content from the source. - * @param {any} options - * An optional object `{ chunkSize : int=64, end : bool=true, complete : function }` + * @param {any} [options] + * [optional] An object `{ chunkSize : int=64, end : bool=true, complete : function }` * chunkSize : The amount of data to pipe from source to destination at a time * complete : a function to call when the pipe activity is complete * end : call the 'end' function on the destination when the source is finished @@ -9326,7 +8117,7 @@ declare class E { * ``` * * @param {any} device - * @param {any} options - (optional) object of options, see below + * @param {any} [options] - [optional] object of options, see below * @url http://www.espruino.com/Reference#l_E_setConsole */ static setConsole(device: "Serial1" | "USB" | "Bluetooth" | "Telnet" | "Terminal" | Serial | null, options?: { force?: boolean }): void; @@ -9534,20 +8325,23 @@ declare class E { * Convert hue, saturation and brightness to red, green and blue (packed into an * integer if `asArray==false` or an array if `asArray==true`). * This replaces `Graphics.setColorHSB` and `Graphics.setBgColorHSB`. On devices - * with 24 bit colour it can be used as: `Graphics.setColor(E.HSBtoRGB(h, s, b))` + * with 24 bit colour it can be used as: `Graphics.setColor(E.HSBtoRGB(h, s, b))`, + * or on devices with 26 bit colour use `Graphics.setColor(E.HSBtoRGB(h, s, b, 16))` * You can quickly set RGB items in an Array or Typed Array using - * `array.set(E.HSBtoRGB(h, s, b,true), offset)`, which can be useful with arrays + * `array.set(E.HSBtoRGB(h, s, b, true), offset)`, which can be useful with arrays * used with `require("neopixel").write`. * * @param {number} hue - The hue, as a value between 0 and 1 * @param {number} sat - The saturation, as a value between 0 and 1 * @param {number} bri - The brightness, as a value between 0 and 1 - * @param {boolean} asArray - If true, return an array of [R,G,B] values betwen 0 and 255 + * @param {number} format - If `true` or `1`, return an array of [R,G,B] values betwen 0 and 255. If `16`, return a 16 bit number. `undefined`/`24` is the same as normal (returning a 24 bit number) * @returns {any} A 24 bit number containing bytes representing red, green, and blue `0xBBGGRR`. Or if `asArray` is true, an array `[R,G,B]` * @url http://www.espruino.com/Reference#l_E_HSBtoRGB */ - static HSBtoRGB(hue: number, sat: number, bri: number, asArray?: false): number; - static HSBtoRGB(hue: number, sat: number, bri: number, asArray: true): [number, number, number]; + static HSBtoRGB(hue: number, sat: number, bri: number, format?: false): number; + static HSBtoRGB(hue: number, sat: number, bri: number, format: 16): number; + static HSBtoRGB(hue: number, sat: number, bri: number, format: 24): number; + static HSBtoRGB(hue: number, sat: number, bri: number, format: true): [number, number, number]; /** * Set a password on the console (REPL). When powered on, Espruino will then demand @@ -9789,158 +8583,678 @@ declare class E { static decodeUTF8(str: string, lookup: string[], replaceFn: string | ((charCode: number) => string)): string; -} - -interface consoleConstructor { - /** - * Print the supplied string(s) to the console - * **Note:** If you're connected to a computer (not a wall adaptor) via USB but - * **you are not running a terminal app** then when you print data Espruino may - * pause execution and wait until the computer requests the data it is trying to - * print. - * - * @param {any} text - One or more arguments to print - * @url http://www.espruino.com/Reference#l_console_log - */ - log(...text: any[]): void; -} - -interface console { - } /** - * An Object that contains functions for writing to the interactive console - * @url http://www.espruino.com/Reference#console + * This class provides a software-defined OneWire master. It is designed to be + * similar to Arduino's OneWire library. + * @url http://www.espruino.com/Reference#OneWire */ -declare const console: consoleConstructor - -interface ErrorConstructor { +declare class OneWire { /** - * Creates an Error object + * Create a software OneWire implementation on the given pin * @constructor * - * @param {any} message - An optional message string - * @returns {any} An Error object - * @url http://www.espruino.com/Reference#l_Error_Error + * @param {Pin} pin - The pin to implement OneWire on + * @returns {any} A OneWire object + * @url http://www.espruino.com/Reference#l_OneWire_OneWire */ - new(message?: string): Error; + static new(pin: Pin): any; + + /** + * Perform a reset cycle + * @returns {boolean} True is a device was present (it held the bus low) + * @url http://www.espruino.com/Reference#l_OneWire_reset + */ + reset(): boolean; + + /** + * Select a ROM - always performs a reset first + * + * @param {any} rom - The device to select (get this using `OneWire.search()`) + * @url http://www.espruino.com/Reference#l_OneWire_select + */ + select(rom: any): void; + + /** + * Skip a ROM + * @url http://www.espruino.com/Reference#l_OneWire_skip + */ + skip(): void; + + /** + * Write one or more bytes + * + * @param {any} data - A byte (or array of bytes) to write + * @param {boolean} power - Whether to leave power on after write (default is false) + * @url http://www.espruino.com/Reference#l_OneWire_write + */ + write(data: any, power: boolean): void; + + /** + * Read a byte + * + * @param {any} [count] - [optional] The amount of bytes to read + * @returns {any} The byte that was read, or a Uint8Array if count was specified and >=0 + * @url http://www.espruino.com/Reference#l_OneWire_read + */ + read(count?: any): any; + + /** + * Search for devices + * + * @param {number} command - (Optional) command byte. If not specified (or zero), this defaults to 0xF0. This can could be set to 0xEC to perform a DS18B20 'Alarm Search Command' + * @returns {any} An array of devices that were found + * @url http://www.espruino.com/Reference#l_OneWire_search + */ + search(command: number): any; } -interface Error { +interface ObjectConstructor { /** - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_Error_toString + * Return all enumerable keys of the given object + * + * @param {any} object - The object to return keys for + * @returns {any} An array of strings - one for each key on the given object + * @url http://www.espruino.com/Reference#l_Object_keys */ - toString(): string; -} + keys(object: any): Array; -/** - * The base class for runtime errors - * @url http://www.espruino.com/Reference#Error - */ -declare const Error: ErrorConstructor - -interface SyntaxErrorConstructor { /** - * Creates a SyntaxError object + * Returns an array of all properties (enumerable or not) found directly on a given + * object. + * + * @param {any} object - The Object to return a list of property names for + * @returns {any} An array of the Object's own properties + * @url http://www.espruino.com/Reference#l_Object_getOwnPropertyNames + */ + getOwnPropertyNames(object: any): Array; + + /** + * Return all enumerable values of the given object + * + * @param {any} object - The object to return values for + * @returns {any} An array of values - one for each key on the given object + * @url http://www.espruino.com/Reference#l_Object_values + */ + values(object: any): Array; + + /** + * Return all enumerable keys and values of the given object + * + * @param {any} object - The object to return values for + * @returns {any} An array of `[key,value]` pairs - one for each key on the given object + * @url http://www.espruino.com/Reference#l_Object_entries + */ + entries(object: any): Array<[string, any]>; + + /** + * Creates a new object with the specified prototype object and properties. + * properties are currently unsupported. + * + * @param {any} proto - A prototype object + * @param {any} propertiesObject - An object containing properties. NOT IMPLEMENTED + * @returns {any} A new object + * @url http://www.espruino.com/Reference#l_Object_create + */ + create(proto: any, propertiesObject: any): any; + + /** + * Get information on the given property in the object, or undefined + * + * @param {any} obj - The object + * @param {any} name - The name of the property + * @returns {any} An object with a description of the property. The values of writable/enumerable/configurable may not be entirely correct due to Espruino's implementation. + * @url http://www.espruino.com/Reference#l_Object_getOwnPropertyDescriptor + */ + getOwnPropertyDescriptor(obj: any, name: any): any; + + /** + * Add a new property to the Object. 'Desc' is an object with the following fields: + * * `configurable` (bool = false) - can this property be changed/deleted (not + * implemented) + * * `enumerable` (bool = false) - can this property be enumerated (not + * implemented) + * * `value` (anything) - the value of this property + * * `writable` (bool = false) - can the value be changed with the assignment + * operator? + * * `get` (function) - the getter function, or undefined if no getter (only + * supported on some platforms) + * * `set` (function) - the setter function, or undefined if no setter (only + * supported on some platforms) + * **Note:** `configurable`, `enumerable` and `writable` are not implemented and + * will be ignored. + * + * @param {any} obj - An object + * @param {any} name - The name of the property + * @param {any} desc - The property descriptor + * @returns {any} The object, obj. + * @url http://www.espruino.com/Reference#l_Object_defineProperty + */ + defineProperty(obj: any, name: any, desc: any): any; + + /** + * Adds new properties to the Object. See `Object.defineProperty` for more + * information + * + * @param {any} obj - An object + * @param {any} props - An object whose fields represent property names, and whose values are property descriptors. + * @returns {any} The object, obj. + * @url http://www.espruino.com/Reference#l_Object_defineProperties + */ + defineProperties(obj: any, props: any): any; + + /** + * Get the prototype of the given object - this is like writing `object.__proto__` + * but is the 'proper' ES6 way of doing it + * + * @param {any} object - An object + * @returns {any} The prototype + * @url http://www.espruino.com/Reference#l_Object_getPrototypeOf + */ + getPrototypeOf(object: any): any; + + /** + * Set the prototype of the given object - this is like writing `object.__proto__ = + * prototype` but is the 'proper' ES6 way of doing it + * + * @param {any} object - An object + * @param {any} prototype - The prototype to set on the object + * @returns {any} The object passed in + * @url http://www.espruino.com/Reference#l_Object_setPrototypeOf + */ + setPrototypeOf(object: any, prototype: any): any; + + /** + * Appends all keys and values in any subsequent objects to the first object + * **Note:** Unlike the standard ES6 `Object.assign`, this will throw an exception + * if given raw strings, bools or numbers rather than objects. + * + * @param {any} args - The target object, then any items objects to use as sources of keys + * @returns {any} The target object + * @url http://www.espruino.com/Reference#l_Object_assign + */ + assign(...args: any[]): any; + + /** + * Creates an Object from the supplied argument * @constructor * - * @param {any} message - An optional message string - * @returns {any} A SyntaxError object - * @url http://www.espruino.com/Reference#l_SyntaxError_SyntaxError + * @param {any} value - A single value to be converted to an object + * @returns {any} An Object + * @url http://www.espruino.com/Reference#l_Object_Object */ - new(message?: string): SyntaxError; + new(value: any): any; } -interface SyntaxError { +interface Object { /** - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_SyntaxError_toString + * Find the length of the object + * @returns {any} The length of the object + * @url http://www.espruino.com/Reference#l_Object_length */ - toString(): string; + length: any; + + /** + * Returns the primitive value of this object. + * @returns {any} The primitive value of this object + * @url http://www.espruino.com/Reference#l_Object_valueOf + */ + valueOf(): any; + + /** + * Convert the Object to a string + * + * @param {any} [radix] - [optional] If the object is an integer, the radix (between 2 and 36) to use. NOTE: Setting a radix does not work on floating point numbers. + * @returns {any} A String representing the object + * @url http://www.espruino.com/Reference#l_Object_toString + */ + toString(radix?: any): string; + + /** + * Copy this object completely + * @returns {any} A copy of this Object + * @url http://www.espruino.com/Reference#l_Object_clone + */ + clone(): any; + + /** + * Return true if the object (not its prototype) has the given property. + * NOTE: This currently returns false-positives for built-in functions in + * prototypes + * + * @param {any} name - The name of the property to search for + * @returns {boolean} True if it exists, false if it doesn't + * @url http://www.espruino.com/Reference#l_Object_hasOwnProperty + */ + hasOwnProperty(name: any): boolean; + + /** + * Register an event listener for this object, for instance `Serial1.on('data', + * function(d) {...})`. + * This is the same as Node.js's [EventEmitter](https://nodejs.org/api/events.html) + * but on Espruino the functionality is built into every object: + * * `Object.on` + * * `Object.emit` + * * `Object.removeListener` + * * `Object.removeAllListeners` + * ``` + * var o = {}; // o can be any object... + * // call an arrow function when the 'answer' event is received + * o.on('answer', x => console.log(x)); + * // call a named function when the 'answer' event is received + * function printAnswer(d) { + * console.log("The answer is", d); + * } + * o.on('answer', printAnswer); + * // emit the 'answer' event - functions added with 'on' will be executed + * o.emit('answer', 42); + * // prints: 42 + * // prints: The answer is 42 + * // If you have a named function, it can be removed by name + * o.removeListener('answer', printAnswer); + * // Now 'printAnswer' is removed + * o.emit('answer', 43); + * // prints: 43 + * // Or you can remove all listeners for 'answer' + * o.removeAllListeners('answer') + * // Now nothing happens + * o.emit('answer', 44); + * // nothing printed + * ``` + * + * @param {any} event - The name of the event, for instance 'data' + * @param {any} listener - The listener to call when this event is received + * @url http://www.espruino.com/Reference#l_Object_on + */ + on(event: any, listener: any): void; + + /** + * Call any event listeners that were added to this object with `Object.on`, for + * instance `obj.emit('data', 'Foo')`. + * For more information see `Object.on` + * + * @param {any} event - The name of the event, for instance 'data' + * @param {any} args - Optional arguments + * @url http://www.espruino.com/Reference#l_Object_emit + */ + emit(event: any, ...args: any[]): void; + + /** + * Removes the specified event listener. + * ``` + * function foo(d) { + * console.log(d); + * } + * Serial1.on("data", foo); + * Serial1.removeListener("data", foo); + * ``` + * For more information see `Object.on` + * + * @param {any} event - The name of the event, for instance 'data' + * @param {any} listener - The listener to remove + * @url http://www.espruino.com/Reference#l_Object_removeListener + */ + removeListener(event: any, listener: any): void; + + /** + * Removes all listeners (if `event===undefined`), or those of the specified event. + * ``` + * Serial1.on("data", function(data) { ... }); + * Serial1.removeAllListeners("data"); + * // or + * Serial1.removeAllListeners(); // removes all listeners for all event types + * ``` + * For more information see `Object.on` + * + * @param {any} event - The name of the event, for instance `'data'`. If not specified *all* listeners are removed. + * @url http://www.espruino.com/Reference#l_Object_removeAllListeners + */ + removeAllListeners(event: any): void; } /** - * The base class for syntax errors - * @url http://www.espruino.com/Reference#SyntaxError + * This is the built-in class for Objects + * @url http://www.espruino.com/Reference#Object */ -declare const SyntaxError: SyntaxErrorConstructor +declare const Object: ObjectConstructor -interface TypeErrorConstructor { +interface FunctionConstructor { /** - * Creates a TypeError object + * Creates a function * @constructor * - * @param {any} message - An optional message string - * @returns {any} A TypeError object - * @url http://www.espruino.com/Reference#l_TypeError_TypeError + * @param {any} args - Zero or more arguments (as strings), followed by a string representing the code to run + * @returns {any} A Number object + * @url http://www.espruino.com/Reference#l_Function_Function */ - new(message?: string): TypeError; + new(...args: any[]): any; } -interface TypeError { +interface Function { /** - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_TypeError_toString + * This replaces the function with the one in the argument - while keeping the old + * function's scope. This allows inner functions to be edited, and is used when + * edit() is called on an inner function. + * + * @param {any} newFunc - The new function to replace this function with + * @url http://www.espruino.com/Reference#l_Function_replaceWith */ - toString(): string; + replaceWith(newFunc: any): void; + + /** + * This executes the function with the supplied 'this' argument and parameters + * + * @param {any} this - The value to use as the 'this' argument when executing the function + * @param {any} params - Optional Parameters + * @returns {any} The return value of executing this function + * @url http://www.espruino.com/Reference#l_Function_call + */ + call(this: any, ...params: any[]): any; + + /** + * This executes the function with the supplied 'this' argument and parameters + * + * @param {any} this - The value to use as the 'this' argument when executing the function + * @param {any} args - Optional Array of Arguments + * @returns {any} The return value of executing this function + * @url http://www.espruino.com/Reference#l_Function_apply + */ + apply(this: any, args: any): any; + + /** + * This executes the function with the supplied 'this' argument and parameters + * + * @param {any} this - The value to use as the 'this' argument when executing the function + * @param {any} params - Optional Default parameters that are prepended to the call + * @returns {any} The 'bound' function + * @url http://www.espruino.com/Reference#l_Function_bind + */ + bind(this: any, ...params: any[]): any; } /** - * The base class for type errors - * @url http://www.espruino.com/Reference#TypeError + * This is the built-in class for Functions + * @url http://www.espruino.com/Reference#Function */ -declare const TypeError: TypeErrorConstructor +declare const Function: FunctionConstructor -/** - * The base class for internal errors - * @url http://www.espruino.com/Reference#InternalError - */ -declare class InternalError { +interface ArrayConstructor { /** - * Creates an InternalError object + * Returns true if the provided object is an array + * + * @param {any} var - The variable to be tested + * @returns {boolean} True if var is an array, false if not. + * @url http://www.espruino.com/Reference#l_Array_isArray + */ + isArray(arg: any): arg is any[]; + + /** + * Create an Array. Either give it one integer argument (>=0) which is the length + * of the array, or any number of arguments * @constructor * - * @param {any} message - An optional message string - * @returns {any} An InternalError object - * @url http://www.espruino.com/Reference#l_InternalError_InternalError + * @param {any} args - The length of the array OR any number of items to add to the array + * @returns {any} An Array + * @url http://www.espruino.com/Reference#l_Array_Array */ - static new(message?: string): InternalError; - - /** - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_InternalError_toString - */ - toString(): string; + new(arrayLength?: number): any[]; + new(arrayLength: number): T[]; + new(...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; } -interface ReferenceErrorConstructor { +interface Array { /** - * Creates a ReferenceError object - * @constructor + * Convert the Array to a string * - * @param {any} message - An optional message string - * @returns {any} A ReferenceError object - * @url http://www.espruino.com/Reference#l_ReferenceError_ReferenceError - */ - new(message?: string): ReferenceError; -} - -interface ReferenceError { - /** - * @returns {any} A String - * @url http://www.espruino.com/Reference#l_ReferenceError_toString + * @param {any} radix - unused + * @returns {any} A String representing the array + * @url http://www.espruino.com/Reference#l_Array_toString */ toString(): string; + + /** + * Find the length of the array + * @returns {any} The length of the array + * @url http://www.espruino.com/Reference#l_Array_length + */ + length: number; + + /** + * Return the index of the value in the array, or -1 + * + * @param {any} value - The value to check for + * @param {number} [startIndex] - [optional] the index to search from, or 0 if not specified + * @returns {any} the index of the value in the array, or -1 + * @url http://www.espruino.com/Reference#l_Array_indexOf + */ + indexOf(value: T, startIndex?: number): number; + + /** + * Return `true` if the array includes the value, `false` otherwise + * + * @param {any} value - The value to check for + * @param {number} [startIndex] - [optional] the index to search from, or 0 if not specified + * @returns {boolean} `true` if the array includes the value, `false` otherwise + * @url http://www.espruino.com/Reference#l_Array_includes + */ + includes(value: T, startIndex?: number): boolean; + + /** + * Join all elements of this array together into one string, using 'separator' + * between them. e.g. ```[1,2,3].join(' ')=='1 2 3'``` + * + * @param {any} separator - The separator + * @returns {any} A String representing the Joined array + * @url http://www.espruino.com/Reference#l_Array_join + */ + join(separator?: string): string; + + /** + * Push a new value onto the end of this array' + * This is the opposite of `[1,2,3].unshift(0)`, which adds one or more elements to + * the beginning of the array. + * + * @param {any} arguments - One or more arguments to add + * @returns {number} The new size of the array + * @url http://www.espruino.com/Reference#l_Array_push + */ + push(...arguments: T[]): number; + + /** + * Remove and return the value on the end of this array. + * This is the opposite of `[1,2,3].shift()`, which removes an element from the + * beginning of the array. + * @returns {any} The value that is popped off + * @url http://www.espruino.com/Reference#l_Array_pop + */ + pop(): T | undefined; + + /** + * Return an array which is made from the following: ```A.map(function) = + * [function(A[0]), function(A[1]), ...]``` + * + * @param {any} function - Function used to map one item to another + * @param {any} [thisArg] - [optional] If specified, the function is called with 'this' set to thisArg + * @returns {any} An array containing the results + * @url http://www.espruino.com/Reference#l_Array_map + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + + /** + * Executes a provided function once per array element. + * + * @param {any} function - Function to be executed + * @param {any} [thisArg] - [optional] If specified, the function is called with 'this' set to thisArg + * @url http://www.espruino.com/Reference#l_Array_forEach + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Return an array which contains only those elements for which the callback + * function returns 'true' + * + * @param {any} function - Function to be executed + * @param {any} [thisArg] - [optional] If specified, the function is called with 'this' set to thisArg + * @returns {any} An array containing the results + * @url http://www.espruino.com/Reference#l_Array_filter + */ + filter(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; + filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[]; + + /** + * Return the array element where `function` returns `true`, or `undefined` if it + * doesn't returns `true` for any element. + * ``` + * ["Hello","There","World"].find(a=>a[0]=="T") + * // returns "There" + * ``` + * + * @param {any} function - Function to be executed + * @returns {any} The array element where `function` returns `true`, or `undefined` + * @url http://www.espruino.com/Reference#l_Array_find + */ + find(predicate: (this: void, value: T, index: number, obj: T[]) => value is S): S | undefined; + find(predicate: (value: T, index: number, obj: T[]) => unknown): T | undefined; + + /** + * Return the array element's index where `function` returns `true`, or `-1` if it + * doesn't returns `true` for any element. + * ``` + * ["Hello","There","World"].findIndex(a=>a[0]=="T") + * // returns 1 + * ``` + * + * @param {any} function - Function to be executed + * @returns {any} The array element's index where `function` returns `true`, or `-1` + * @url http://www.espruino.com/Reference#l_Array_findIndex + */ + findIndex(predicate: (value: T, index: number, obj: T[]) => unknown): number; + + /** + * Return 'true' if the callback returns 'true' for any of the elements in the + * array + * + * @param {any} function - Function to be executed + * @param {any} [thisArg] - [optional] If specified, the function is called with 'this' set to thisArg + * @returns {any} A boolean containing the result + * @url http://www.espruino.com/Reference#l_Array_some + */ + some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean; + + /** + * Return 'true' if the callback returns 'true' for every element in the array + * + * @param {any} function - Function to be executed + * @param {any} [thisArg] - [optional] If specified, the function is called with 'this' set to thisArg + * @returns {any} A boolean containing the result + * @url http://www.espruino.com/Reference#l_Array_every + */ + every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean; + + /** + * Execute `previousValue=initialValue` and then `previousValue = + * callback(previousValue, currentValue, index, array)` for each element in the + * array, and finally return previousValue. + * + * @param {any} callback - Function used to reduce the array + * @param {any} initialValue - if specified, the initial value to pass to the function + * @returns {any} The value returned by the last function called + * @url http://www.espruino.com/Reference#l_Array_reduce + */ + reduce(callback: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Both remove and add items to an array + * + * @param {number} index - Index at which to start changing the array. If negative, will begin that many elements from the end + * @param {any} howMany - An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. + * @param {any} elements - One or more items to add to the array + * @returns {any} An array containing the removed elements. If only one element is removed, an array of one element is returned. + * @url http://www.espruino.com/Reference#l_Array_splice + */ + splice(index: number, howMany?: number, ...elements: T[]): T[]; + + /** + * Remove and return the first element of the array. + * This is the opposite of `[1,2,3].pop()`, which takes an element off the end. + * + * @returns {any} The element that was removed + * @url http://www.espruino.com/Reference#l_Array_shift + */ + shift(): T | undefined; + + /** + * Add one or more items to the start of the array, and return its new length. + * This is the opposite of `[1,2,3].push(4)`, which puts one or more elements on + * the end. + * + * @param {any} elements - One or more items to add to the beginning of the array + * @returns {number} The new array length + * @url http://www.espruino.com/Reference#l_Array_unshift + */ + unshift(...elements: T[]): number; + + /** + * Return a copy of a portion of this array (in a new array) + * + * @param {number} start - Start index + * @param {any} [end] - [optional] End index + * @returns {any} A new array + * @url http://www.espruino.com/Reference#l_Array_slice + */ + slice(start?: number, end?: number): T[]; + + /** + * Do an in-place quicksort of the array + * + * @param {any} var - A function to use to compare array elements (or undefined) + * @returns {any} This array object + * @url http://www.espruino.com/Reference#l_Array_sort + */ + sort(compareFn?: (a: T, b: T) => number): T[]; + + /** + * Create a new array, containing the elements from this one and any arguments, if + * any argument is an array then those elements will be added. + * + * @param {any} args - Any items to add to the array + * @returns {any} An Array + * @url http://www.espruino.com/Reference#l_Array_concat + */ + concat(...args: (T | T[])[]): T[]; + + /** + * Fill this array with the given value, for every index `>= start` and `< end` + * + * @param {any} value - The value to fill the array with + * @param {number} start - Optional. The index to start from (or 0). If start is negative, it is treated as length+start where length is the length of the array + * @param {any} end - Optional. The index to end at (or the array length). If end is negative, it is treated as length+end. + * @returns {any} This array + * @url http://www.espruino.com/Reference#l_Array_fill + */ + fill(value: T, start: number, end?: number): T[]; + + /** + * Reverse all elements in this array (in place) + * @returns {any} The array, but reversed. + * @url http://www.espruino.com/Reference#l_Array_reverse + */ + reverse(): T[]; + + [index: number]: T } /** - * The base class for reference errors - where a variable which doesn't exist has - * been accessed. - * @url http://www.espruino.com/Reference#ReferenceError + * This is the built-in JavaScript class for arrays. + * Arrays can be defined with ```[]```, ```new Array()```, or ```new + * Array(length)``` + * @url http://www.espruino.com/Reference#Array */ -declare const ReferenceError: ReferenceErrorConstructor +declare const Array: ArrayConstructor interface JSONConstructor { /** @@ -9981,6 +9295,930 @@ interface JSON { */ declare const JSON: JSONConstructor +/** + * This class allows use of the built-in SPI ports. Currently it is SPI master + * only. + * @url http://www.espruino.com/Reference#SPI + */ +declare class SPI { + /** + * Try and find an SPI hardware device that will work on this pin (e.g. `SPI1`) + * May return undefined if no device can be found. + * + * @param {Pin} pin - A pin to search with + * @returns {any} An object of type `SPI`, or `undefined` if one couldn't be found. + * @url http://www.espruino.com/Reference#l_SPI_find + */ + static find(pin: Pin): any; + + /** + * Create a software SPI port. This has limited functionality (no baud rate), but + * it can work on any pins. + * Use `SPI.setup` to configure this port. + * @constructor + * @returns {any} A SPI object + * @url http://www.espruino.com/Reference#l_SPI_SPI + */ + static new(): any; + + /** + * Set up this SPI port as an SPI Master. + * Options can contain the following (defaults are shown where relevant): + * ``` + * { + * sck:pin, + * miso:pin, + * mosi:pin, + * baud:integer=100000, // ignored on software SPI + * mode:integer=0, // between 0 and 3 + * order:string='msb' // can be 'msb' or 'lsb' + * bits:8 // only available for software SPI + * } + * ``` + * If `sck`,`miso` and `mosi` are left out, they will automatically be chosen. + * However if one or more is specified then the unspecified pins will not be set + * up. + * You can find out which pins to use by looking at [your board's reference + * page](#boards) and searching for pins with the `SPI` marker. Some boards such as + * those based on `nRF52` chips can have SPI on any pins, so don't have specific + * markings. + * The SPI `mode` is between 0 and 3 - see + * http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase + * On STM32F1-based parts, you cannot mix AF and non-AF pins (SPI pins are usually + * grouped on the chip - and you can't mix pins from two groups). Espruino will not + * warn you about this. + * + * @param {any} options - An Object containing extra information on initialising the SPI port + * @url http://www.espruino.com/Reference#l_SPI_setup + */ + setup(options: any): void; + + /** + * Send data down SPI, and return the result. Sending an integer will return an + * integer, a String will return a String, and anything else will return a + * Uint8Array. + * Sending multiple bytes in one call to send is preferable as they can then be + * transmitted end to end. Using multiple calls to send() will result in + * significantly slower transmission speeds. + * For maximum speeds, please pass either Strings or Typed Arrays as arguments. + * Note that you can even pass arrays of arrays, like `[1,[2,3,4],5]` + * + * @param {any} data - The data to send - either an Integer, Array, String, or Object of the form `{data: ..., count:#}` + * @param {Pin} nss_pin - An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised. + * @returns {any} The data that was returned + * @url http://www.espruino.com/Reference#l_SPI_send + */ + send(data: any, nss_pin: Pin): any; + + /** + * Write a character or array of characters to SPI - without reading the result + * back. + * For maximum speeds, please pass either Strings or Typed Arrays as arguments. + * + * @param {any} data + * One or more items to write. May be ints, strings, arrays, or special objects (see `E.toUint8Array` for more info). + * If the last argument is a pin, it is taken to be the NSS pin + * @url http://www.espruino.com/Reference#l_SPI_write + */ + write(...data: any[]): void; + + /** + * Send data down SPI, using 4 bits for each 'real' bit (MSB first). This can be + * useful for faking one-wire style protocols + * Sending multiple bytes in one call to send is preferable as they can then be + * transmitted end to end. Using multiple calls to send() will result in + * significantly slower transmission speeds. + * + * @param {any} data - The data to send - either an integer, array, or string + * @param {number} bit0 - The 4 bits to send for a 0 (MSB first) + * @param {number} bit1 - The 4 bits to send for a 1 (MSB first) + * @param {Pin} nss_pin - An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised. + * @url http://www.espruino.com/Reference#l_SPI_send4bit + */ + send4bit(data: any, bit0: number, bit1: number, nss_pin: Pin): void; + + /** + * Send data down SPI, using 8 bits for each 'real' bit (MSB first). This can be + * useful for faking one-wire style protocols + * Sending multiple bytes in one call to send is preferable as they can then be + * transmitted end to end. Using multiple calls to send() will result in + * significantly slower transmission speeds. + * + * @param {any} data - The data to send - either an integer, array, or string + * @param {number} bit0 - The 8 bits to send for a 0 (MSB first) + * @param {number} bit1 - The 8 bits to send for a 1 (MSB first) + * @param {Pin} nss_pin - An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised + * @url http://www.espruino.com/Reference#l_SPI_send8bit + */ + send8bit(data: any, bit0: number, bit1: number, nss_pin: Pin): void; +} + +/** + * This class allows use of the built-in I2C ports. Currently it allows I2C Master + * mode only. + * All addresses are in 7 bit format. If you have an 8 bit address then you need to + * shift it one bit to the right. + * @url http://www.espruino.com/Reference#I2C + */ +declare class I2C { + /** + * Try and find an I2C hardware device that will work on this pin (e.g. `I2C1`) + * May return undefined if no device can be found. + * + * @param {Pin} pin - A pin to search with + * @returns {any} An object of type `I2C`, or `undefined` if one couldn't be found. + * @url http://www.espruino.com/Reference#l_I2C_find + */ + static find(pin: Pin): any; + + /** + * Create a software I2C port. This has limited functionality (no baud rate), but + * it can work on any pins. + * Use `I2C.setup` to configure this port. + * @constructor + * @returns {any} An I2C object + * @url http://www.espruino.com/Reference#l_I2C_I2C + */ + static new(): any; + + /** + * Set up this I2C port + * If not specified in options, the default pins are used (usually the lowest + * numbered pins on the lowest port that supports this peripheral) + * + * @param {any} [options] + * [optional] A structure containing extra information on initialising the I2C port + * ```{scl:pin, sda:pin, bitrate:100000}``` + * You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `I2C` marker. Note that 400kHz is the maximum bitrate for most parts. + * @url http://www.espruino.com/Reference#l_I2C_setup + */ + setup(options?: any): void; + + /** + * Transmit to the slave device with the given address. This is like Arduino's + * beginTransmission, write, and endTransmission rolled up into one. + * + * @param {any} address - The 7 bit address of the device to transmit to, or an object of the form `{address:12, stop:false}` to send this data without a STOP signal. + * @param {any} data - One or more items to write. May be ints, strings, arrays, or special objects (see `E.toUint8Array` for more info). + * @url http://www.espruino.com/Reference#l_I2C_writeTo + */ + writeTo(address: any, ...data: any[]): void; + + /** + * Request bytes from the given slave device, and return them as a Uint8Array + * (packed array of bytes). This is like using Arduino Wire's requestFrom, + * available and read functions. Sends a STOP + * + * @param {any} address - The 7 bit address of the device to request bytes from, or an object of the form `{address:12, stop:false}` to send this data without a STOP signal. + * @param {number} quantity - The number of bytes to request + * @returns {any} The data that was returned - as a Uint8Array + * @url http://www.espruino.com/Reference#l_I2C_readFrom + */ + readFrom(address: any, quantity: number): Uint8Array; +} + +interface PromiseConstructor { + /** + * Return a new promise that is resolved when all promises in the supplied array + * are resolved. + * + * @param {any} promises - An array of promises + * @returns {any} A new Promise + * @url http://www.espruino.com/Reference#l_Promise_all + */ + all(promises: Promise[]): Promise; + + /** + * Return a new promise that is already resolved (at idle it'll call `.then`) + * + * @param {any} promises - Data to pass to the `.then` handler + * @returns {any} A new Promise + * @url http://www.espruino.com/Reference#l_Promise_resolve + */ + resolve(promises: T): Promise; + + /** + * Return a new promise that is already rejected (at idle it'll call `.catch`) + * + * @param {any} promises - Data to pass to the `.catch` handler + * @returns {any} A new Promise + * @url http://www.espruino.com/Reference#l_Promise_reject + */ + reject(promises: any): any; + + /** + * Create a new Promise. The executor function is executed immediately (before the + * constructor even returns) and + * @constructor + * + * @param {any} executor - A function of the form `function (resolve, reject)` + * @returns {any} A Promise + * @url http://www.espruino.com/Reference#l_Promise_Promise + */ + new(executor: (resolve: (value: T) => void, reject: (reason?: any) => void) => void): Promise; +} + +interface Promise { + /** + * + * @param {any} onFulfilled - A callback that is called when this promise is resolved + * @param {any} [onRejected] - [optional] A callback that is called when this promise is rejected (or nothing) + * @returns {any} The original Promise + * @url http://www.espruino.com/Reference#l_Promise_then + */ + then(onfulfilled?: ((value: T) => TResult1 | Promise) | undefined | null, onrejected?: ((reason: any) => TResult2 | Promise) | undefined | null): Promise; + + /** + * + * @param {any} onRejected - A callback that is called when this promise is rejected + * @returns {any} The original Promise + * @url http://www.espruino.com/Reference#l_Promise_catch + */ + catch(onRejected: any): any; +} + +/** + * This is the built-in class for ES6 Promises + * @url http://www.espruino.com/Reference#Promise + */ +declare const Promise: PromiseConstructor + +/** + * These objects are created from `require("Storage").open` and allow Storage items + * to be read/written. + * The `Storage` library writes into Flash memory (which can only be erased in + * chunks), and unlike a normal filesystem it allocates files in one long + * contiguous area to allow them to be accessed easily from Espruino. + * This presents a challenge for `StorageFile` which allows you to append to a + * file, so instead `StorageFile` stores files in chunks. It uses the last + * character of the filename to denote the chunk number (e.g. `"foobar\1"`, + * `"foobar\2"`, etc). + * This means that while `StorageFile` files exist in the same area as those from + * `Storage`, they should be read using `Storage.open` (and not `Storage.read`). + * ``` + * f = s.open("foobar","w"); + * f.write("Hell"); + * f.write("o World\n"); + * f.write("Hello\n"); + * f.write("World 2\n"); + * // there's no need to call 'close' + * // then + * f = s.open("foobar","r"); + * f.read(13) // "Hello World\nH" + * f.read(13) // "ello\nWorld 2\n" + * f.read(13) // "Hello World 3" + * f.read(13) // "\n" + * f.read(13) // undefined + * // or + * f = s.open("foobar","r"); + * f.readLine() // "Hello World\n" + * f.readLine() // "Hello\n" + * f.readLine() // "World 2\n" + * f.readLine() // "Hello World 3\n" + * f.readLine() // undefined + * // now get rid of file + * f.erase(); + * ``` + * **Note:** `StorageFile` uses the fact that all bits of erased flash memory are 1 + * to detect the end of a file. As such you should not write character code 255 + * (`"\xFF"`) to these files. + * @url http://www.espruino.com/Reference#StorageFile + */ +declare class StorageFile { + + + /** + * Read 'len' bytes of data from the file, and return a String containing those + * bytes. + * If the end of the file is reached, the String may be smaller than the amount of + * bytes requested, or if the file is already at the end, `undefined` is returned. + * + * @param {number} len - How many bytes to read + * @returns {any} A String, or undefined + * @url http://www.espruino.com/Reference#l_StorageFile_read + */ + read(len: number): string; + + /** + * Read a line of data from the file (up to and including `"\n"`) + * @returns {any} A line of data + * @url http://www.espruino.com/Reference#l_StorageFile_readLine + */ + readLine(): string; + + /** + * Return the length of the current file. + * This requires Espruino to read the file from scratch, which is not a fast + * operation. + * @returns {number} The current length in bytes of the file + * @url http://www.espruino.com/Reference#l_StorageFile_getLength + */ + getLength(): number; + + /** + * Append the given data to a file. You should not attempt to append `"\xFF"` + * (character code 255). + * + * @param {any} data - The data to write. This should not include `'\xFF'` (character code 255) + * @url http://www.espruino.com/Reference#l_StorageFile_write + */ + write(data: string): void; + + /** + * Erase this file + * @url http://www.espruino.com/Reference#l_StorageFile_erase + */ + erase(): void; +} + +interface processConstructor { + /** + * This event is called when an exception gets thrown and isn't caught (e.g. it gets + * all the way back to the event loop). + * You can use this for logging potential problems that might occur during + * execution when you might not be able to see what is written to the console, for + * example: + * ``` + * var lastError; + * process.on('uncaughtException', function(e) { + * lastError=e; + * print(e,e.stack?"\n"+e.stack:"") + * }); + * function checkError() { + * if (!lastError) return print("No Error"); + * print(lastError,lastError.stack?"\n"+lastError.stack:"") + * } + * ``` + * **Note:** When this is used, exceptions will cease to be reported on the + * console - which may make debugging difficult! + * @param {string} event - The event to listen to. + * @param {(exception: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `exception` The uncaught exception + * @url http://www.espruino.com/Reference#l_process_uncaughtException + */ + on(event: "uncaughtException", callback: (exception: any) => void): void; + + /** + * Returns the version of Espruino as a String + * @returns {any} The version of Espruino + * @url http://www.espruino.com/Reference#l_process_version + */ + version: any; + + /** + * Returns an Object containing various pre-defined variables. + * * `VERSION` - is the Espruino version + * * `GIT_COMMIT` - is Git commit hash this firmware was built from + * * `BOARD` - the board's ID (e.g. `PUCKJS`) + * * `RAM` - total amount of on-chip RAM in bytes + * * `FLASH` - total amount of on-chip flash memory in bytes + * * `SPIFLASH` - (on Bangle.js) total amount of off-chip flash memory in bytes + * * `HWVERSION` - For Puck.js this is the board revision (1, 2, 2.1), or for + * Bangle.js it's 1 or 2 + * * `STORAGE` - memory in bytes dedicated to the `Storage` module + * * `SERIAL` - the serial number of this chip + * * `CONSOLE` - the name of the current console device being used (`Serial1`, + * `USB`, `Bluetooth`, etc) + * * `MODULES` - a list of built-in modules separated by commas + * * `EXPTR` - The address of the `exportPtrs` structure in flash (this includes + * links to built-in functions that compiled JS code needs) + * * `APP_RAM_BASE` - On nRF5x boards, this is the RAM required by the Softdevice + * *if it doesn't exactly match what was allocated*. You can use this to update + * `LD_APP_RAM_BASE` in the `BOARD.py` file + * For example, to get a list of built-in modules, you can use + * `process.env.MODULES.split(',')` + * **Note:** `process.env` is not writeable - so as not to waste RAM, the contents + * are generated on demand. If you need to be able to change them, use `process.env=process.env;` + * first to ensure the values stay allocated. + * @returns {any} An object + * @url http://www.espruino.com/Reference#l_process_env + */ + env: any; + + /** + * Run a Garbage Collection pass, and return an object containing information on + * memory usage. + * * `free` : Memory that is available to be used (in blocks) + * * `usage` : Memory that has been used (in blocks) + * * `total` : Total memory (in blocks) + * * `history` : Memory used for command history - that is freed if memory is low. + * Note that this is INCLUDED in the figure for 'free' + * * `gc` : Memory freed during the GC pass + * * `gctime` : Time taken for GC pass (in milliseconds) + * * `blocksize` : Size of a block (variable) in bytes + * * `stackEndAddress` : (on ARM) the address (that can be used with peek/poke/etc) + * of the END of the stack. The stack grows down, so unless you do a lot of + * recursion the bytes above this can be used. + * * `stackFree` : (on ARM) how many bytes of free execution stack are there + * at the point of execution. + * * `flash_start` : (on ARM) the address of the start of flash memory (usually + * `0x8000000`) + * * `flash_binary_end` : (on ARM) the address in flash memory of the end of + * Espruino's firmware. + * * `flash_code_start` : (on ARM) the address in flash memory of pages that store + * any code that you save with `save()`. + * * `flash_length` : (on ARM) the amount of flash memory this firmware was built + * for (in bytes). **Note:** Some STM32 chips actually have more memory than is + * advertised. + * Memory units are specified in 'blocks', which are around 16 bytes each + * (depending on your device). The actual size is available in `blocksize`. See + * http://www.espruino.com/Performance for more information. + * **Note:** To find free areas of flash memory, see `require('Flash').getFree()` + * + * @param {any} [gc] - [optional] A boolean. If `undefined` or `true` Garbage collection is performed, if `false` it is not + * @returns {any} Information about memory usage + * @url http://www.espruino.com/Reference#l_process_memory + */ + memory(gc?: any): any; +} + +interface process { + +} + +/** + * This class contains information about Espruino itself + * @url http://www.espruino.com/Reference#process + */ +declare const process: processConstructor + +/** + * This class allows use of the built-in USARTs + * Methods may be called on the `USB`, `Serial1`, `Serial2`, `Serial3`, `Serial4`, + * `Serial5` and `Serial6` objects. While different processors provide different + * numbers of USARTs, on official Espruino boards you can always rely on at least + * `Serial1` being available + * @url http://www.espruino.com/Reference#Serial + */ +declare class Serial { + /** + * The `data` event is called when data is received. If a handler is defined with + * `X.on('data', function(data) { ... })` then it will be called, otherwise data + * will be stored in an internal buffer, where it can be retrieved with `X.read()` + * @param {string} event - The event to listen to. + * @param {(data: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `data` A string containing one or more characters of received data + * @url http://www.espruino.com/Reference#l_Serial_data + */ + static on(event: "data", callback: (data: any) => void): void; + + /** + * The `framing` event is called when there was activity on the input to the UART + * but the `STOP` bit wasn't in the correct place. This is either because there was + * noise on the line, or the line has been pulled to 0 for a long period of time. + * To enable this, you must initialise Serial with `SerialX.setup(..., { ..., + * errors:true });` + * **Note:** Even though there was an error, the byte will still be received and + * passed to the `data` handler. + * **Note:** This only works on STM32 and NRF52 based devices (e.g. all official + * Espruino boards) + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_Serial_framing + */ + static on(event: "framing", callback: () => void): void; + + /** + * The `parity` event is called when the UART was configured with a parity bit, and + * this doesn't match the bits that have actually been received. + * To enable this, you must initialise Serial with `SerialX.setup(..., { ..., + * errors:true });` + * **Note:** Even though there was an error, the byte will still be received and + * passed to the `data` handler. + * **Note:** This only works on STM32 and NRF52 based devices (e.g. all official + * Espruino boards) + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_Serial_parity + */ + static on(event: "parity", callback: () => void): void; + + /** + * Try and find a USART (Serial) hardware device that will work on this pin (e.g. + * `Serial1`) + * May return undefined if no device can be found. + * + * @param {Pin} pin - A pin to search with + * @returns {any} An object of type `Serial`, or `undefined` if one couldn't be found. + * @url http://www.espruino.com/Reference#l_Serial_find + */ + static find(pin: Pin): any; + + /** + * Create a software Serial port. This has limited functionality (only low baud + * rates), but it can work on any pins. + * Use `Serial.setup` to configure this port. + * @constructor + * @returns {any} A Serial object + * @url http://www.espruino.com/Reference#l_Serial_Serial + */ + static new(): any; + + /** + * Set this Serial port as the port for the JavaScript console (REPL). + * Unless `force` is set to true, changes in the connection state of the board (for + * instance plugging in USB) will cause the console to change. + * See `E.setConsole` for a more flexible version of this function. + * + * @param {boolean} force - Whether to force the console to this port + * @url http://www.espruino.com/Reference#l_Serial_setConsole + */ + setConsole(force: boolean): void; + + /** + * Setup this Serial port with the given baud rate and options. + * e.g. + * ``` + * Serial1.setup(9600,{rx:a_pin, tx:a_pin}); + * ``` + * The second argument can contain: + * ``` + * { + * rx:pin, // Receive pin (data in to Espruino) + * tx:pin, // Transmit pin (data out of Espruino) + * ck:pin, // (default none) Clock Pin + * cts:pin, // (default none) Clear to Send Pin + * bytesize:8, // (default 8)How many data bits - 7 or 8 + * parity:null/'none'/'o'/'odd'/'e'/'even', + * // (default none) Parity bit + * stopbits:1, // (default 1) Number of stop bits to use + * flow:null/undefined/'none'/'xon', // (default none) software flow control + * path:null/undefined/string // Linux Only - the path to the Serial device to use + * errors:false // (default false) whether to forward framing/parity errors + * } + * ``` + * You can find out which pins to use by looking at [your board's reference + * page](#boards) and searching for pins with the `UART`/`USART` markers. + * If not specified in options, the default pins are used for rx and tx (usually + * the lowest numbered pins on the lowest port that supports this peripheral). `ck` + * and `cts` are not used unless specified. + * Note that even after changing the RX and TX pins, if you have called setup + * before then the previous RX and TX pins will still be connected to the Serial + * port as well - until you set them to something else using `digitalWrite` or + * `pinMode`. + * Flow control can be xOn/xOff (`flow:'xon'`) or hardware flow control (receive + * only) if `cts` is specified. If `cts` is set to a pin, the pin's value will be 0 + * when Espruino is ready for data and 1 when it isn't. + * By default, framing or parity errors don't create `framing` or `parity` events + * on the `Serial` object because storing these errors uses up additional storage + * in the queue. If you're intending to receive a lot of malformed data then the + * queue might overflow `E.getErrorFlags()` would return `FIFO_FULL`. However if + * you need to respond to `framing` or `parity` errors then you'll need to use + * `errors:true` when initialising serial. + * On Linux builds there is no default Serial device, so you must specify a path to + * a device - for instance: `Serial1.setup(9600,{path:"/dev/ttyACM0"})` + * You can also set up 'software serial' using code like: + * ``` + * var s = new Serial(); + * s.setup(9600,{rx:a_pin, tx:a_pin}); + * ``` + * However software serial doesn't use `ck`, `cts`, `parity`, `flow` or `errors` + * parts of the initialisation object. + * + * @param {any} baudrate - The baud rate - the default is 9600 + * @param {any} [options] - [optional] A structure containing extra information on initialising the serial port - see below. + * @url http://www.espruino.com/Reference#l_Serial_setup + */ + setup(baudrate: any, options?: any): void; + + /** + * If the serial (or software serial) device was set up, uninitialise it. + * @url http://www.espruino.com/Reference#l_Serial_unsetup + */ + unsetup(): void; + + /** + * Print a string to the serial port - without a line feed + * **Note:** This function replaces any occurrences of `\n` in the string with + * `\r\n`. To avoid this, use `Serial.write`. + * + * @param {any} string - A String to print + * @url http://www.espruino.com/Reference#l_Serial_print + */ + print(string: any): void; + + /** + * Print a line to the serial port with a newline (`\r\n`) at the end of it. + * **Note:** This function converts data to a string first, e.g. + * `Serial.print([1,2,3])` is equivalent to `Serial.print("1,2,3"). If you'd like + * to write raw bytes, use `Serial.write`. + * + * @param {any} string - A String to print + * @url http://www.espruino.com/Reference#l_Serial_println + */ + println(string: any): void; + + /** + * Write a character or array of data to the serial port + * This method writes unmodified data, e.g. `Serial.write([1,2,3])` is equivalent to + * `Serial.write("\1\2\3")`. If you'd like data converted to a string first, use + * `Serial.print`. + * + * @param {any} data - One or more items to write. May be ints, strings, arrays, or special objects (see `E.toUint8Array` for more info). + * @url http://www.espruino.com/Reference#l_Serial_write + */ + write(...data: any[]): void; + + /** + * Add data to this device as if it came directly from the input - it will be + * returned via `serial.on('data', ...)`; + * ``` + * Serial1.on('data', function(d) { print("Got",d); }); + * Serial1.inject('Hello World'); + * // prints "Got Hel","Got lo World" (characters can be split over multiple callbacks) + * ``` + * This is most useful if you wish to send characters to Espruino's REPL (console) + * while it is on another device. + * + * @param {any} data - One or more items to write. May be ints, strings, arrays, or special objects (see `E.toUint8Array` for more info). + * @url http://www.espruino.com/Reference#l_Serial_inject + */ + inject(...data: any[]): void; + + /** + * Return how many bytes are available to read. If there is already a listener for + * data, this will always return 0. + * @returns {number} How many bytes are available + * @url http://www.espruino.com/Reference#l_Serial_available + */ + available(): number; + + /** + * Return a string containing characters that have been received + * + * @param {number} chars - The number of characters to read, or undefined/0 for all available + * @returns {any} A string containing the required bytes. + * @url http://www.espruino.com/Reference#l_Serial_read + */ + read(chars: number): any; + + /** + * Pipe this USART to a stream (an object with a 'write' method) + * + * @param {any} destination - The destination file/stream that will receive content from the source. + * @param {any} [options] + * [optional] An object `{ chunkSize : int=32, end : bool=true, complete : function }` + * chunkSize : The amount of data to pipe from source to destination at a time + * complete : a function to call when the pipe activity is complete + * end : call the 'end' function on the destination when the source is finished + * @url http://www.espruino.com/Reference#l_Serial_pipe + */ + pipe(destination: any, options?: any): void; +} + +interface StringConstructor { + /** + * Return the character(s) represented by the given character code(s). + * + * @param {any} code - One or more character codes to create a string from (range 0-255). + * @returns {any} The character + * @url http://www.espruino.com/Reference#l_String_fromCharCode + */ + fromCharCode(...code: any[]): any; + + /** + * Create a new String + * @constructor + * + * @param {any} str - A value to turn into a string. If undefined or not supplied, an empty String is created. + * @returns {any} A String + * @url http://www.espruino.com/Reference#l_String_String + */ + new(...str: any[]): any; +} + +interface String { + /** + * Find the length of the string + * @returns {any} The value of the string + * @url http://www.espruino.com/Reference#l_String_length + */ + length: any; + + /** + * Return a single character at the given position in the String. + * + * @param {number} pos - The character number in the string. Negative values return characters from end of string (-1 = last char) + * @returns {any} The character in the string + * @url http://www.espruino.com/Reference#l_String_charAt + */ + charAt(pos: number): any; + + /** + * Return the integer value of a single character at the given position in the + * String. + * Note that this returns 0 not 'NaN' for out of bounds characters + * + * @param {number} pos - The character number in the string. Negative values return characters from end of string (-1 = last char) + * @returns {number} The integer value of a character in the string + * @url http://www.espruino.com/Reference#l_String_charCodeAt + */ + charCodeAt(pos: number): number; + + /** + * Return the index of substring in this string, or -1 if not found + * + * @param {any} substring - The string to search for + * @param {any} fromIndex - Index to search from + * @returns {number} The index of the string, or -1 if not found + * @url http://www.espruino.com/Reference#l_String_indexOf + */ + indexOf(substring: any, fromIndex: any): number; + + /** + * Return the last index of substring in this string, or -1 if not found + * + * @param {any} substring - The string to search for + * @param {any} fromIndex - Index to search from + * @returns {number} The index of the string, or -1 if not found + * @url http://www.espruino.com/Reference#l_String_lastIndexOf + */ + lastIndexOf(substring: any, fromIndex: any): number; + + /** + * Matches an occurrence `subStr` in the string. + * Returns `null` if no match, or: + * ``` + * "abcdef".match("b") == [ + * "b", // array index 0 - the matched string + * index: 1, // the start index of the match + * input: "b" // the input string + * ] + * "abcdefabcdef".match(/bcd/) == [ + * "bcd", index: 1, + * input: "abcdefabcdef" + * ] + * ``` + * 'Global' RegExp matches just return an array of matches (with no indices): + * ``` + * "abcdefabcdef".match(/bcd/g) = [ + * "bcd", + * "bcd" + * ] + * ``` + * + * @param {any} substr - Substring or RegExp to match + * @returns {any} A match array or `null` (see below): + * @url http://www.espruino.com/Reference#l_String_match + */ + match(substr: any): any; + + /** + * Search and replace ONE occurrence of `subStr` with `newSubStr` and return the + * result. This doesn't alter the original string. Regular expressions not + * supported. + * + * @param {any} subStr - The string to search for + * @param {any} newSubStr - The string to replace it with + * @returns {any} This string with `subStr` replaced + * @url http://www.espruino.com/Reference#l_String_replace + */ + replace(subStr: any, newSubStr: any): any; + + /** + * + * @param {number} start - The start character index (inclusive) + * @param {any} end - The end character index (exclusive) + * @returns {any} The part of this string between start and end + * @url http://www.espruino.com/Reference#l_String_substring + */ + substring(start: number, end: any): any; + + /** + * + * @param {number} start - The start character index + * @param {any} len - The number of characters + * @returns {any} Part of this string from start for len characters + * @url http://www.espruino.com/Reference#l_String_substr + */ + substr(start: number, len: any): any; + + /** + * + * @param {number} start - The start character index, if negative it is from the end of the string + * @param {any} end - The end character index, if negative it is from the end of the string, and if omitted it is the end of the string + * @returns {any} Part of this string from start for len characters + * @url http://www.espruino.com/Reference#l_String_slice + */ + slice(start: number, end: any): any; + + /** + * Return an array made by splitting this string up by the separator. e.g. + * ```'1,2,3'.split(',')==['1', '2', '3']``` + * Regular Expressions can also be used to split strings, e.g. `'1a2b3 + * 4'.split(/[^0-9]/)==['1', '2', '3', '4']`. + * + * @param {any} separator - The separator `String` or `RegExp` to use + * @returns {any} Part of this string from start for len characters + * @url http://www.espruino.com/Reference#l_String_split + */ + split(separator: any): any; + + /** + * + * @returns {any} The lowercase version of this string + * @url http://www.espruino.com/Reference#l_String_toLowerCase + */ + toLowerCase(): any; + + /** + * + * @returns {any} The uppercase version of this string + * @url http://www.espruino.com/Reference#l_String_toUpperCase + */ + toUpperCase(): any; + + /** + * Return a new string with any whitespace (tabs, space, form feed, newline, + * carriage return, etc) removed from the beginning and end. + * @returns {any} A String with Whitespace removed from the beginning and end + * @url http://www.espruino.com/Reference#l_String_trim + */ + trim(): string; + + /** + * Append all arguments to this `String` and return the result. Does not modify the + * original `String`. + * + * @param {any} args - Strings to append + * @returns {any} The result of appending all arguments to this string + * @url http://www.espruino.com/Reference#l_String_concat + */ + concat(...args: any[]): any; + + /** + * + * @param {any} searchString - The string to search for + * @param {number} position - The start character index (or 0 if not defined) + * @returns {boolean} `true` if the given characters are found at the beginning of the string, otherwise, `false`. + * @url http://www.espruino.com/Reference#l_String_startsWith + */ + startsWith(searchString: any, position: number): boolean; + + /** + * + * @param {any} searchString - The string to search for + * @param {any} length - The 'end' of the string - if left off the actual length of the string is used + * @returns {boolean} `true` if the given characters are found at the end of the string, otherwise, `false`. + * @url http://www.espruino.com/Reference#l_String_endsWith + */ + endsWith(searchString: any, length: any): boolean; + + /** + * + * @param {any} substring - The string to search for + * @param {any} fromIndex - The start character index (or 0 if not defined) + * @returns {boolean} `true` if the given characters are in the string, otherwise, `false`. + * @url http://www.espruino.com/Reference#l_String_includes + */ + includes(substring: any, fromIndex: any): boolean; + + /** + * Repeat this string the given number of times. + * + * @param {number} count - An integer with the amount of times to repeat this String + * @returns {any} A string containing repetitions of this string + * @url http://www.espruino.com/Reference#l_String_repeat + */ + repeat(count: number): string; + + /** + * Pad this string at the beginning to the required number of characters + * ``` + * "Hello".padStart(10) == " Hello" + * "123".padStart(10,".-") == ".-.-.-.123" + * ``` + * + * @param {number} targetLength - The length to pad this string to + * @param {any} [padString] - [optional] The string to pad with, default is `' '` + * @returns {any} A string containing this string padded to the correct length + * @url http://www.espruino.com/Reference#l_String_padStart + */ + padStart(targetLength: number, padString?: any): string; + + /** + * Pad this string at the end to the required number of characters + * ``` + * "Hello".padEnd(10) == "Hello " + * "123".padEnd(10,".-") == "123.-.-.-." + * ``` + * + * @param {number} targetLength - The length to pad this string to + * @param {any} [padString] - [optional] The string to pad with, default is `' '` + * @returns {any} A string containing this string padded to the correct length + * @url http://www.espruino.com/Reference#l_String_padEnd + */ + padEnd(targetLength: number, padString?: any): string; +} + +/** + * This is the built-in class for Text Strings. + * Text Strings in Espruino are not zero-terminated, so you can store zeros in + * them. + * @url http://www.espruino.com/Reference#String + */ +declare const String: StringConstructor + interface RegExpConstructor { /** * Creates a RegExp object, for handling Regular Expressions @@ -10041,418 +10279,174 @@ interface RegExp { */ declare const RegExp: RegExpConstructor -/** - * This is the built-in class for the Arduino-style pin namings on ST Nucleo boards - * @url http://www.espruino.com/Reference#Nucleo - */ -declare class Nucleo { +interface NumberConstructor { /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_A0 + * @returns {number} Not a Number + * @url http://www.espruino.com/Reference#l_Number_NaN */ - static A0: Pin; + NaN: number; /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_A1 + * @returns {number} Maximum representable value + * @url http://www.espruino.com/Reference#l_Number_MAX_VALUE */ - static A1: Pin; + MAX_VALUE: number; /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_A2 + * @returns {number} Smallest representable value + * @url http://www.espruino.com/Reference#l_Number_MIN_VALUE */ - static A2: Pin; + MIN_VALUE: number; /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_A3 + * @returns {number} Negative Infinity (-1/0) + * @url http://www.espruino.com/Reference#l_Number_NEGATIVE_INFINITY */ - static A3: Pin; + NEGATIVE_INFINITY: number; /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_A4 + * @returns {number} Positive Infinity (1/0) + * @url http://www.espruino.com/Reference#l_Number_POSITIVE_INFINITY */ - static A4: Pin; + POSITIVE_INFINITY: number; /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_A5 - */ - static A5: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D0 - */ - static D0: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D1 - */ - static D1: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D2 - */ - static D2: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D3 - */ - static D3: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D4 - */ - static D4: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D5 - */ - static D5: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D6 - */ - static D6: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D7 - */ - static D7: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D8 - */ - static D8: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D9 - */ - static D9: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D10 - */ - static D10: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D11 - */ - static D11: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D12 - */ - static D12: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D13 - */ - static D13: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D14 - */ - static D14: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_Nucleo_D15 - */ - static D15: Pin; - - -} - -/** - * This is a built-in class to allow you to use the ESP8266 NodeMCU boards's pin - * namings to access pins. It is only available on ESP8266-based boards. - * @url http://www.espruino.com/Reference#NodeMCU - */ -declare class NodeMCU { - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_A0 - */ - static A0: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D0 - */ - static D0: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D1 - */ - static D1: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D2 - */ - static D2: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D3 - */ - static D3: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D4 - */ - static D4: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D5 - */ - static D5: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D6 - */ - static D6: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D7 - */ - static D7: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D8 - */ - static D8: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D9 - */ - static D9: Pin; - - /** - * @returns {Pin} A Pin - * @url http://www.espruino.com/Reference#l_NodeMCU_D10 - */ - static D10: Pin; - - -} - -/** - * Class containing utility functions for the - * [ESP32](http://www.espruino.com/ESP32) - * @url http://www.espruino.com/Reference#ESP32 - */ -declare class ESP32 { - /** - * - * @param {Pin} pin - Pin for Analog read - * @param {number} atten - Attenuate factor - * @url http://www.espruino.com/Reference#l_ESP32_setAtten - */ - static setAtten(pin: Pin, atten: number): void; - - /** - * Perform a hardware reset/reboot of the ESP32. - * @url http://www.espruino.com/Reference#l_ESP32_reboot - */ - static reboot(): void; - - /** - * Put device in deepsleep state for "us" microseconds. - * - * @param {number} us - Sleeptime in us - * @url http://www.espruino.com/Reference#l_ESP32_deepSleep - */ - static deepSleep(us: number): void; - - /** - * Returns an object that contains details about the state of the ESP32 with the - * following fields: - * * `sdkVersion` - Version of the SDK. - * * `freeHeap` - Amount of free heap in bytes. - * * `BLE` - Status of BLE, enabled if true. - * * `Wifi` - Status of Wifi, enabled if true. - * * `minHeap` - Minimum heap, calculated by heap_caps_get_minimum_free_size - * @returns {any} The state of the ESP32 - * @url http://www.espruino.com/Reference#l_ESP32_getState - */ - static getState(): any; - - /** - * - * @param {number} level - which events should be shown (GATTS, GATTC, GAP) - * @url http://www.espruino.com/Reference#l_ESP32_setBLE_Debug - */ - static setBLE_Debug(level: number): void; - - /** - * Switches Bluetooth off/on, removes saved code from Flash, resets the board, and - * on restart creates jsVars depending on available heap (actual additional 1800) - * - * @param {boolean} enable - switches Bluetooth on or off - * @url http://www.espruino.com/Reference#l_ESP32_enableBLE - */ - static enableBLE(enable: boolean): void; - - /** - * Switches Wifi off/on, removes saved code from Flash, resets the board, and on - * restart creates jsVars depending on available heap (actual additional 3900) - * - * @param {boolean} enable - switches Wifi on or off - * @url http://www.espruino.com/Reference#l_ESP32_enableWifi - */ - static enableWifi(enable: boolean): void; - - -} - -/** - * A class to support some simple Queue handling for RTOS queues - * @url http://www.espruino.com/Reference#Queue - */ -declare class Queue { - /** - * Creates a Queue Object + * Creates a number * @constructor * - * @param {any} queueName - Name of the queue - * @returns {any} A Queue object - * @url http://www.espruino.com/Reference#l_Queue_Queue + * @param {any} value - A single value to be converted to a number + * @returns {any} A Number object + * @url http://www.espruino.com/Reference#l_Number_Number */ - static new(queueName: any): any; + new(...value: any[]): any; +} +interface Number { /** - * reads one character from queue, if available - * @url http://www.espruino.com/Reference#l_Queue_read - */ - read(): void; - - /** - * Writes one character to queue + * Format the number as a fixed point number * - * @param {any} char - char to be send - * @url http://www.espruino.com/Reference#l_Queue_writeChar + * @param {number} decimalPlaces - A number between 0 and 20 specifying the number of decimal digits after the decimal point + * @returns {any} A string + * @url http://www.espruino.com/Reference#l_Number_toFixed */ - writeChar(char: any): void; - - /** - * logs list of queues - * @url http://www.espruino.com/Reference#l_Queue_log - */ - log(): void; + toFixed(decimalPlaces: number): any; } /** - * A class to support some simple Task handling for RTOS tasks - * @url http://www.espruino.com/Reference#Task + * This is the built-in JavaScript class for numbers. + * @url http://www.espruino.com/Reference#Number */ -declare class Task { - /** - * Creates a Task Object - * @constructor - * - * @param {any} taskName - Name of the task - * @returns {any} A Task object - * @url http://www.espruino.com/Reference#l_Task_Task - */ - static new(taskName: any): any; - - /** - * Suspend task, be careful not to suspend Espruino task itself - * @url http://www.espruino.com/Reference#l_Task_suspend - */ - suspend(): void; - - /** - * Resumes a suspended task - * @url http://www.espruino.com/Reference#l_Task_resume - */ - resume(): void; - - /** - * returns name of actual task - * @returns {any} Name of current task - * @url http://www.espruino.com/Reference#l_Task_getCurrent - */ - getCurrent(): any; - - /** - * Sends a binary notify to task - * @url http://www.espruino.com/Reference#l_Task_notify - */ - notify(): void; - - /** - * logs list of tasks - * @url http://www.espruino.com/Reference#l_Task_log - */ - log(): void; -} +declare const Number: NumberConstructor /** - * A class to handle Timer on base of ESP32 Timer - * @url http://www.espruino.com/Reference#Timer + * This is the built-in class for Pins, such as D0,D1,LED1, or BTN + * You can call the methods on Pin, or you can use Wiring-style functions such as + * digitalWrite + * @url http://www.espruino.com/Reference#Pin */ -declare class Timer { +declare class Pin { /** - * Creates a Timer Object + * Creates a pin from the given argument (or returns undefined if no argument) * @constructor * - * @param {any} timerName - Timer Name - * @param {number} group - Timer group - * @param {number} index - Timer index - * @param {number} isrIndex - isr (0 = Espruino, 1 = test) - * @returns {any} A Timer Object - * @url http://www.espruino.com/Reference#l_Timer_Timer + * @param {any} value - A value to be converted to a pin. Can be a number, pin, or String. + * @returns {any} A Pin object + * @url http://www.espruino.com/Reference#l_Pin_Pin */ - static new(timerName: any, group: number, index: number, isrIndex: number): any; + static new(value: any): any; /** - * Starts a timer + * Returns the input state of the pin as a boolean. + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset the pin's state to `"input"` + * @returns {boolean} Whether pin is a logical 1 or 0 + * @url http://www.espruino.com/Reference#l_Pin_read + */ + read(): boolean; + + /** + * Sets the output state of the pin to a 1 + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset the pin's state to `"output"` + * @url http://www.espruino.com/Reference#l_Pin_set + */ + set(): void; + + /** + * Sets the output state of the pin to a 0 + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset the pin's state to `"output"` + * @url http://www.espruino.com/Reference#l_Pin_reset + */ + reset(): void; + + /** + * Sets the output state of the pin to the parameter given + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset the pin's state to `"output"` * - * @param {number} duration - duration of timmer in micro secs - * @url http://www.espruino.com/Reference#l_Timer_start + * @param {boolean} value - Whether to set output high (true/1) or low (false/0) + * @url http://www.espruino.com/Reference#l_Pin_write */ - start(duration: number): void; + write(value: boolean): void; /** - * Reschedules a timer, needs to be started at least once + * Sets the output state of the pin to the parameter given at the specified time. + * **Note:** this **doesn't** change the mode of the pin to an output. To do that, + * you need to use `pin.write(0)` or `pinMode(pin, 'output')` first. * - * @param {number} duration - duration of timmer in micro secs - * @url http://www.espruino.com/Reference#l_Timer_reschedule + * @param {boolean} value - Whether to set output high (true/1) or low (false/0) + * @param {number} time - Time at which to write + * @url http://www.espruino.com/Reference#l_Pin_writeAtTime */ - reschedule(duration: number): void; + writeAtTime(value: boolean, time: number): void; /** - * logs list of timers - * @url http://www.espruino.com/Reference#l_Timer_log + * Return the current mode of the given pin. See `pinMode` for more information. + * @returns {any} The pin mode, as a string + * @url http://www.espruino.com/Reference#l_Pin_getMode */ - log(): void; + getMode(): any; + + /** + * Set the mode of the given pin. See [`pinMode`](#l__global_pinMode) for more + * information on pin modes. + * + * @param {any} mode - The mode - a string that is either 'analog', 'input', 'input_pullup', 'input_pulldown', 'output', 'opendrain', 'af_output' or 'af_opendrain'. Do not include this argument if you want to revert to automatic pin mode setting. + * @url http://www.espruino.com/Reference#l_Pin_mode + */ + mode(mode: any): void; + + /** + * Toggles the state of the pin from off to on, or from on to off. + * **Note:** This method doesn't currently work on the ESP8266 port of Espruino. + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset the pin's state to `"output"` + * @returns {boolean} True if the pin is high after calling the function + * @url http://www.espruino.com/Reference#l_Pin_toggle + */ + toggle(): boolean; + + /** + * Get information about this pin and its capabilities. Of the form: + * ``` + * { + * "port" : "A", // the Pin's port on the chip + * "num" : 12, // the Pin's number + * "in_addr" : 0x..., // (if available) the address of the pin's input address in bit-banded memory (can be used with peek) + * "out_addr" : 0x..., // (if available) the address of the pin's output address in bit-banded memory (can be used with poke) + * "analog" : { ADCs : [1], channel : 12 }, // If analog input is available + * "functions" : { + * "TIM1":{type:"CH1, af:0}, + * "I2C3":{type:"SCL", af:1} + * } + * } + * ``` + * Will return undefined if pin is not valid. + * @returns {any} An object containing information about this pins + * @url http://www.espruino.com/Reference#l_Pin_getInfo + */ + getInfo(): any; } interface BooleanConstructor { @@ -10476,16 +10470,32 @@ declare const Boolean: BooleanConstructor // GLOBALS +/** + * The pin marked SDA on the Arduino pin footprint. This is connected directly to + * pin A4. + * @returns {Pin} + * @url http://www.espruino.com/Reference#l__global_SDA + */ +declare const SDA: Pin; + +/** + * The pin marked SDA on the Arduino pin footprint. This is connected directly to + * pin A5. + * @returns {Pin} + * @url http://www.espruino.com/Reference#l__global_SCL + */ +declare const SCL: Pin; + /** * **Note:** This function is only available on the [BBC micro:bit](/MicroBit) * board * Show an image on the in-built 5x5 LED screen. * Image can be: - * * A number where each bit represents a pixel (so 25 bits). eg. `5` or + * * A number where each bit represents a pixel (so 25 bits). e.g. `5` or * `0x1FFFFFF` - * * A string, eg: `show("10001")`. Newlines are ignored, and anything that is not + * * A string, e.g: `show("10001")`. Newlines are ignored, and anything that is not * a space or `0` is treated as a 1. - * * An array of 4 bytes (more will be ignored), eg `show([1,2,3,0])` + * * An array of 4 bytes (more will be ignored), e.g `show([1,2,3,0])` * For instance the following works for images: * ``` * show("# #"+ @@ -10527,6 +10537,54 @@ declare function acceleration(): any; */ declare function compass(): any; +/** + * On Puck.js V2 (not v1.0) this is the pin that controls the FET, for high-powered + * outputs. + * @returns {Pin} + * @url http://www.espruino.com/Reference#l__global_FET + */ +declare const FET: Pin; + +/** + * The Bangle.js's vibration motor. + * @returns {Pin} + * @url http://www.espruino.com/Reference#l__global_VIBRATE + */ +declare const VIBRATE: Pin; + +/** + * On most Espruino board there are LEDs, in which case `LED` will be an actual + * Pin. + * On Bangle.js there are no LEDs, so to remain compatible with example code that + * might expect an LED, this is an object that behaves like a pin, but which just + * displays a circle on the display + * @returns {any} A `Pin` object for a fake LED which appears on + * @url http://www.espruino.com/Reference#l__global_LED + */ +declare const LED: any; + +/** + * On most Espruino board there are LEDs, in which case `LED1` will be an actual + * Pin. + * On Bangle.js there are no LEDs, so to remain compatible with example code that + * might expect an LED, this is an object that behaves like a pin, but which just + * displays a circle on the display + * @returns {any} A `Pin` object for a fake LED which appears on + * @url http://www.espruino.com/Reference#l__global_LED1 + */ +declare const LED1: any; + +/** + * On most Espruino board there are LEDs, in which case `LED2` will be an actual + * Pin. + * On Bangle.js there are no LEDs, so to remain compatible with example code that + * might expect an LED, this is an object that behaves like a pin, but which just + * displays a circle on the display + * @returns {any} A `Pin` object for a fake LED which appears on + * @url http://www.espruino.com/Reference#l__global_LED2 + */ +declare const LED2: any; + /** * The pin connected to the 'A' button. Reads as `1` when pressed, `0` when not * @returns {Pin} @@ -10612,68 +10670,11 @@ declare const CORNER5: Pin; declare const CORNER6: Pin; /** - * On Puck.js V2 (not v1.0) this is the pin that controls the FET, for high-powered - * outputs. - * @returns {Pin} - * @url http://www.espruino.com/Reference#l__global_FET + * The Bluetooth Serial port - used when data is sent or received over Bluetooth + * Smart on nRF51/nRF52 chips. + * @url http://www.espruino.com/Reference#l__global_Bluetooth */ -declare const FET: Pin; - -/** - * The pin marked SDA on the Arduino pin footprint. This is connected directly to - * pin A4. - * @returns {Pin} - * @url http://www.espruino.com/Reference#l__global_SDA - */ -declare const SDA: Pin; - -/** - * The pin marked SDA on the Arduino pin footprint. This is connected directly to - * pin A5. - * @returns {Pin} - * @url http://www.espruino.com/Reference#l__global_SCL - */ -declare const SCL: Pin; - -/** - * The Bangle.js's vibration motor. - * @returns {Pin} - * @url http://www.espruino.com/Reference#l__global_VIBRATE - */ -declare const VIBRATE: Pin; - -/** - * On most Espruino board there are LEDs, in which case `LED` will be an actual - * Pin. - * On Bangle.js there are no LEDs, so to remain compatible with example code that - * might expect an LED, this is an object that behaves like a pin, but which just - * displays a circle on the display - * @returns {any} A `Pin` object for a fake LED which appears on - * @url http://www.espruino.com/Reference#l__global_LED - */ -declare const LED: any; - -/** - * On most Espruino board there are LEDs, in which case `LED1` will be an actual - * Pin. - * On Bangle.js there are no LEDs, so to remain compatible with example code that - * might expect an LED, this is an object that behaves like a pin, but which just - * displays a circle on the display - * @returns {any} A `Pin` object for a fake LED which appears on - * @url http://www.espruino.com/Reference#l__global_LED1 - */ -declare const LED1: any; - -/** - * On most Espruino board there are LEDs, in which case `LED2` will be an actual - * Pin. - * On Bangle.js there are no LEDs, so to remain compatible with example code that - * might expect an LED, this is an object that behaves like a pin, but which just - * displays a circle on the display - * @returns {any} A `Pin` object for a fake LED which appears on - * @url http://www.espruino.com/Reference#l__global_LED2 - */ -declare const LED2: any; +declare const Bluetooth: Serial; /** * @returns {Pin} A Pin @@ -10724,458 +10725,24 @@ declare const IOEXT2: Pin; declare const IOEXT3: Pin; /** - * @returns {number} Not a Number - * @url http://www.espruino.com/Reference#l__global_NaN + * A simple VT100 terminal emulator. + * When data is sent to the `Terminal` object, `Graphics.getInstance()` is called + * and if an instance of `Graphics` is found then characters are written to it. + * @url http://www.espruino.com/Reference#l__global_Terminal */ -declare const NaN: number; - -/** - * @returns {number} Positive Infinity (1/0) - * @url http://www.espruino.com/Reference#l__global_Infinity - */ -declare const Infinity: number; - -/** - * @returns {number} Logic 1 for Arduino compatibility - this is the same as just typing `1` - * @url http://www.espruino.com/Reference#l__global_HIGH - */ -declare const HIGH: 1; - -/** - * @returns {number} Logic 0 for Arduino compatibility - this is the same as just typing `0` - * @url http://www.espruino.com/Reference#l__global_LOW - */ -declare const LOW: 0; - -/** - * A variable containing the arguments given to the function: - * ``` - * function hello() { - * console.log(arguments.length, JSON.stringify(arguments)); - * } - * hello() // 0 [] - * hello("Test") // 1 ["Test"] - * hello(1,2,3) // 3 [1,2,3] - * ``` - * **Note:** Due to the way Espruino works this is doesn't behave exactly the same - * as in normal JavaScript. The length of the arguments array will never be less - * than the number of arguments specified in the function declaration: - * `(function(a){ return arguments.length; })() == 1`. Normal JavaScript - * interpreters would return `0` in the above case. - * @returns {any} An array containing all the arguments given to the function - * @url http://www.espruino.com/Reference#l__global_arguments - */ -declare const arguments: any; - -/** - * Evaluate a string containing JavaScript code - * - * @param {any} code - * @returns {any} The result of evaluating the string - * @url http://www.espruino.com/Reference#l__global_eval - */ -declare function eval(code: any): any; - -/** - * Convert a string representing a number into an integer - * - * @param {any} string - * @param {any} radix - The Radix of the string (optional) - * @returns {any} The integer value of the string (or NaN) - * @url http://www.espruino.com/Reference#l__global_parseInt - */ -declare function parseInt(string: any, radix: any): any; - -/** - * Convert a string representing a number into an float - * - * @param {any} string - * @returns {number} The value of the string - * @url http://www.espruino.com/Reference#l__global_parseFloat - */ -declare function parseFloat(string: any): number; - -/** - * Is the parameter a finite num,ber or not? If needed, the parameter is first - * converted to a number. - * - * @param {any} x - * @returns {boolean} True is the value is a Finite number, false if not. - * @url http://www.espruino.com/Reference#l__global_isFinite - */ -declare function isFinite(x: any): boolean; - -/** - * Whether the x is NaN (Not a Number) or not - * - * @param {any} x - * @returns {boolean} True is the value is NaN, false if not. - * @url http://www.espruino.com/Reference#l__global_isNaN - */ -declare function isNaN(x: any): boolean; - -/** - * Encode the supplied string (or array) into a base64 string - * - * @param {any} binaryData - A string of data to encode - * @returns {any} A base64 encoded string - * @url http://www.espruino.com/Reference#l__global_btoa - */ -declare function btoa(binaryData: any): any; - -/** - * Decode the supplied base64 string into a normal string - * - * @param {any} base64Data - A string of base64 data to decode - * @returns {any} A string containing the decoded data - * @url http://www.espruino.com/Reference#l__global_atob - */ -declare function atob(base64Data: any): any; - -/** - * Convert a string with any character not alphanumeric or `- _ . ! ~ * ' ( )` - * converted to the form `%XY` where `XY` is its hexadecimal representation - * - * @param {any} str - A string to encode as a URI - * @returns {any} A string containing the encoded data - * @url http://www.espruino.com/Reference#l__global_encodeURIComponent - */ -declare function encodeURIComponent(str: any): any; - -/** - * Convert any groups of characters of the form '%ZZ', into characters with hex - * code '0xZZ' - * - * @param {any} str - A string to decode from a URI - * @returns {any} A string containing the decoded data - * @url http://www.espruino.com/Reference#l__global_decodeURIComponent - */ -declare function decodeURIComponent(str: any): any; - -/** - * Load the given module, and return the exported functions and variables. - * For example: - * ``` - * var s = require("Storage"); - * s.write("test", "hello world"); - * print(s.read("test")); - * // prints "hello world" - * ``` - * Check out [the page on Modules](/Modules) for an explanation of what modules are - * and how you can use them. - * - * @param {any} moduleName - A String containing the name of the given module - * @returns {any} The result of evaluating the string - * @url http://www.espruino.com/Reference#l__global_require - */ -declare function require(moduleName: T): Libraries[T]; -declare function require>(moduleName: T): any; - -/** - * Read 8 bits of memory at the given location - DANGEROUS! - * - * @param {number} addr - The address in memory to read - * @param {number} count - (optional) the number of items to read. If >1 a Uint8Array will be returned. - * @returns {any} The value of memory at the given location - * @url http://www.espruino.com/Reference#l__global_peek8 - */ -declare function peek8(addr: number, count?: 1): number; -declare function peek8(addr: number, count: number): Uint8Array; - -/** - * Write 8 bits of memory at the given location - VERY DANGEROUS! - * - * @param {number} addr - The address in memory to write - * @param {any} value - The value to write, or an array of values - * @url http://www.espruino.com/Reference#l__global_poke8 - */ -declare function poke8(addr: number, value: number | number[]): void; - -/** - * Read 16 bits of memory at the given location - DANGEROUS! - * - * @param {number} addr - The address in memory to read - * @param {number} count - (optional) the number of items to read. If >1 a Uint16Array will be returned. - * @returns {any} The value of memory at the given location - * @url http://www.espruino.com/Reference#l__global_peek16 - */ -declare function peek16(addr: number, count?: 1): number; -declare function peek16(addr: number, count: number): Uint8Array; - -/** - * Write 16 bits of memory at the given location - VERY DANGEROUS! - * - * @param {number} addr - The address in memory to write - * @param {any} value - The value to write, or an array of values - * @url http://www.espruino.com/Reference#l__global_poke16 - */ -declare function poke16(addr: number, value: number | number[]): void; - -/** - * Read 32 bits of memory at the given location - DANGEROUS! - * - * @param {number} addr - The address in memory to read - * @param {number} count - (optional) the number of items to read. If >1 a Uint32Array will be returned. - * @returns {any} The value of memory at the given location - * @url http://www.espruino.com/Reference#l__global_peek32 - */ -declare function peek32(addr: number, count?: 1): number; -declare function peek32(addr: number, count: number): Uint8Array; - -/** - * Write 32 bits of memory at the given location - VERY DANGEROUS! - * - * @param {number} addr - The address in memory to write - * @param {any} value - The value to write, or an array of values - * @url http://www.espruino.com/Reference#l__global_poke32 - */ -declare function poke32(addr: number, value: number | number[]): void; - -/** - * Get the analog value of the given pin - * This is different to Arduino which only returns an integer between 0 and 1023 - * However only pins connected to an ADC will work (see the datasheet) - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset pin's state to `"analog"` - * - * @param {Pin} pin - * The pin to use - * You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `ADC` markers. - * @returns {number} The analog Value of the Pin between 0 and 1 - * @url http://www.espruino.com/Reference#l__global_analogRead - */ -declare function analogRead(pin: Pin): number; - -/** - * Set the analog Value of a pin. It will be output using PWM. - * Objects can contain: - * * `freq` - pulse frequency in Hz, eg. ```analogWrite(A0,0.5,{ freq : 10 });``` - - * specifying a frequency will force PWM output, even if the pin has a DAC - * * `soft` - boolean, If true software PWM is used if hardware is not available. - * * `forceSoft` - boolean, If true software PWM is used even if hardware PWM or a - * DAC is available - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset pin's state to `"output"` - * - * @param {Pin} pin - * The pin to use - * You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `PWM` or `DAC` markers. - * @param {number} value - A value between 0 and 1 - * @param {any} options - * An object containing options for analog output - see below - * @url http://www.espruino.com/Reference#l__global_analogWrite - */ -declare function analogWrite(pin: Pin, value: number, options?: { freq?: number, soft?: boolean, forceSoft?: boolean }): void; - -/** - * Pulse the pin with the value for the given time in milliseconds. It uses a - * hardware timer to produce accurate pulses, and returns immediately (before the - * pulse has finished). Use `digitalPulse(A0,1,0)` to wait until a previous pulse - * has finished. - * eg. `digitalPulse(A0,1,5);` pulses A0 high for 5ms. - * `digitalPulse(A0,1,[5,2,4]);` pulses A0 high for 5ms, low for 2ms, and high for - * 4ms - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset pin's state to `"output"` - * digitalPulse is for SHORT pulses that need to be very accurate. If you're doing - * anything over a few milliseconds, use setTimeout instead. - * - * @param {Pin} pin - The pin to use - * @param {boolean} value - Whether to pulse high (true) or low (false) - * @param {any} time - A time in milliseconds, or an array of times (in which case a square wave will be output starting with a pulse of 'value') - * @url http://www.espruino.com/Reference#l__global_digitalPulse - */ -declare function digitalPulse(pin: Pin, value: boolean, time: number | number[]): void; - -/** - * Set the digital value of the given pin. - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset pin's state to `"output"` - * If pin argument is an array of pins (eg. `[A2,A1,A0]`) the value argument will - * be treated as an array of bits where the last array element is the least - * significant bit. - * In this case, pin values are set least significant bit first (from the - * right-hand side of the array of pins). This means you can use the same pin - * multiple times, for example `digitalWrite([A1,A1,A0,A0],0b0101)` would pulse A0 - * followed by A1. - * If the pin argument is an object with a `write` method, the `write` method will - * be called with the value passed through. - * - * @param {any} pin - The pin to use - * @param {number} value - Whether to pulse high (true) or low (false) - * @url http://www.espruino.com/Reference#l__global_digitalWrite - */ -declare function digitalWrite(pin: Pin, value: typeof HIGH | typeof LOW): void; - -/** - * Get the digital value of the given pin. - * **Note:** if you didn't call `pinMode` beforehand then this function will also - * reset pin's state to `"input"` - * If the pin argument is an array of pins (eg. `[A2,A1,A0]`) the value returned - * will be an number where the last array element is the least significant bit, for - * example if `A0=A1=1` and `A2=0`, `digitalRead([A2,A1,A0]) == 0b011` - * If the pin argument is an object with a `read` method, the `read` method will be - * called and the integer value it returns passed back. - * - * @param {any} pin - The pin to use - * @returns {number} The digital Value of the Pin - * @url http://www.espruino.com/Reference#l__global_digitalRead - */ -declare function digitalRead(pin: Pin): number; - -/** - * Set the mode of the given pin. - * * `auto`/`undefined` - Don't change state, but allow `digitalWrite`/etc to - * automatically change state as appropriate - * * `analog` - Analog input - * * `input` - Digital input - * * `input_pullup` - Digital input with internal ~40k pull-up resistor - * * `input_pulldown` - Digital input with internal ~40k pull-down resistor - * * `output` - Digital output - * * `opendrain` - Digital output that only ever pulls down to 0v. Sending a - * logical `1` leaves the pin open circuit - * * `opendrain_pullup` - Digital output that pulls down to 0v. Sending a logical - * `1` enables internal ~40k pull-up resistor - * * `af_output` - Digital output from built-in peripheral - * * `af_opendrain` - Digital output from built-in peripheral that only ever pulls - * down to 0v. Sending a logical `1` leaves the pin open circuit - * **Note:** `digitalRead`/`digitalWrite`/etc set the pin mode automatically - * *unless* `pinMode` has been called first. If you want `digitalRead`/etc to set - * the pin mode automatically after you have called `pinMode`, simply call it again - * with no mode argument (`pinMode(pin)`), `auto` as the argument (`pinMode(pin, - * "auto")`), or with the 3rd 'automatic' argument set to true (`pinMode(pin, - * "output", true)`). - * - * @param {Pin} pin - The pin to set pin mode for - * @param {any} mode - The mode - a string that is either 'analog', 'input', 'input_pullup', 'input_pulldown', 'output', 'opendrain', 'af_output' or 'af_opendrain'. Do not include this argument or use 'auto' if you want to revert to automatic pin mode setting. - * @param {boolean} automatic - Optional, default is false. If true, subsequent commands will automatically change the state (see notes below) - * @url http://www.espruino.com/Reference#l__global_pinMode - */ -declare function pinMode(pin: Pin, mode?: PinMode | "auto", automatic?: boolean): void; - -/** - * Return the current mode of the given pin. See `pinMode` for more information on - * returned values. - * - * @param {Pin} pin - The pin to check - * @returns {any} The pin mode, as a string - * @url http://www.espruino.com/Reference#l__global_getPinMode - */ -declare function getPinMode(pin: Pin): PinMode; - -/** - * Shift an array of data out using the pins supplied *least significant bit - * first*, for example: - * ``` - * // shift out to single clk+data - * shiftOut(A0, { clk : A1 }, [1,0,1,0]); - * ``` - * ``` - * // shift out a whole byte (like software SPI) - * shiftOut(A0, { clk : A1, repeat: 8 }, [1,2,3,4]); - * ``` - * ``` - * // shift out via 4 data pins - * shiftOut([A3,A2,A1,A0], { clk : A4 }, [1,2,3,4]); - * ``` - * `options` is an object of the form: - * ``` - * { - * clk : pin, // a pin to use as the clock (undefined = no pin) - * clkPol : bool, // clock polarity - default is 0 (so 1 normally, pulsing to 0 to clock data in) - * repeat : int, // number of clocks per array item - * } - * ``` - * Each item in the `data` array will be output to the pins, with the first pin in - * the array being the MSB and the last the LSB, then the clock will be pulsed in - * the polarity given. - * `repeat` is the amount of times shift data out for each array item. For instance - * we may want to shift 8 bits out through 2 pins - in which case we need to set - * repeat to 4. - * - * @param {any} pins - A pin, or an array of pins to use - * @param {any} options - Options, for instance the clock (see below) - * @param {any} data - The data to shift out (see `E.toUint8Array` for info on the forms this can take) - * @url http://www.espruino.com/Reference#l__global_shiftOut - */ -declare function shiftOut(pins: Pin | Pin[], options: { clk?: Pin, clkPol?: boolean, repeat?: number }, data: Uint8ArrayResolvable): void; - -/** - * Call the function specified when the pin changes. Watches set with `setWatch` - * can be removed using `clearWatch`. - * If the `options` parameter is an object, it can contain the following - * information (all optional): - * ``` - * { - * // Whether to keep producing callbacks, or remove the watch after the first callback - * repeat: true/false(default), - * // Trigger on the rising or falling edge of the signal. Can be a string, or 1='rising', -1='falling', 0='both' - * edge:'rising'(default for built-in buttons)/'falling'/'both'(default for pins), - * // Use software-debouncing to stop multiple calls if a switch bounces - * // This is the time in milliseconds to wait for bounces to subside, or 0 to disable - * debounce:10 (0 is default for pins, 25 is default for built-in buttons), - * // Advanced: If the function supplied is a 'native' function (compiled or assembly) - * // setting irq:true will call that function in the interrupt itself - * irq : false(default) - * // Advanced: If specified, the given pin will be read whenever the watch is called - * // and the state will be included as a 'data' field in the callback - * data : pin - * // Advanced: On Nordic devices, a watch may be 'high' or 'low' accuracy. By default low - * // accuracy is used (which is better for power consumption), but this means that - * // high speed pulses (less than 25us) may not be reliably received. Setting hispeed=true - * // allows for detecting high speed pulses at the expense of higher idle power consumption - * hispeed : true - * } - * ``` - * The `function` callback is called with an argument, which is an object of type - * `{state:bool, time:float, lastTime:float}`. - * * `state` is whether the pin is currently a `1` or a `0` - * * `time` is the time in seconds at which the pin changed state - * * `lastTime` is the time in seconds at which the **pin last changed state**. - * When using `edge:'rising'` or `edge:'falling'`, this is not the same as when - * the function was last called. - * * `data` is included if `data:pin` was specified in the options, and can be - * used for reading in clocked data - * For instance, if you want to measure the length of a positive pulse you could - * use `setWatch(function(e) { console.log(e.time-e.lastTime); }, BTN, { - * repeat:true, edge:'falling' });`. This will only be called on the falling edge - * of the pulse, but will be able to measure the width of the pulse because - * `e.lastTime` is the time of the rising edge. - * Internally, an interrupt writes the time of the pin's state change into a queue - * with the exact time that it happened, and the function supplied to `setWatch` is - * executed only from the main message loop. However, if the callback is a native - * function `void (bool state)` then you can add `irq:true` to options, which will - * cause the function to be called from within the IRQ. When doing this, interrupts - * will happen on both edges and there will be no debouncing. - * **Note:** if you didn't call `pinMode` beforehand then this function will reset - * pin's state to `"input"` - * **Note:** The STM32 chip (used in the [Espruino Board](/EspruinoBoard) and - * [Pico](/Pico)) cannot watch two pins with the same number - eg `A0` and `B0`. - * **Note:** On nRF52 chips (used in Puck.js, Pixl.js, MDBT42Q) `setWatch` disables - * the GPIO output on that pin. In order to be able to write to the pin again you - * need to disable the watch with `clearWatch`. - * - * @param {any} function - A Function or String to be executed - * @param {Pin} pin - The pin to watch - * @param {any} options - If a boolean or integer, it determines whether to call this once (false = default) or every time a change occurs (true). Can be an object of the form `{ repeat: true/false(default), edge:'rising'/'falling'/'both'(default), debounce:10}` - see below for more information. - * @returns {any} An ID that can be passed to clearWatch - * @url http://www.espruino.com/Reference#l__global_setWatch - */ -declare function setWatch(func: ((arg: { state: boolean, time: number, lastTime: number }) => void) | string, pin: Pin, options?: boolean | { repeat?: boolean, edge?: "rising" | "falling" | "both", debounce?: number, irq?: boolean, data?: Pin, hispeed?: boolean }): number; - -/** - * Clear the Watch that was created with setWatch. If no parameter is supplied, all watches will be removed. - * To avoid accidentally deleting all Watches, if a parameter is supplied but is `undefined` then an Exception will be thrown. - * - * @param {any} id - The id returned by a previous call to setWatch. **Only one argument is allowed.** - * @url http://www.espruino.com/Reference#l__global_clearWatch - */ -declare function clearWatch(id: number): void; +declare const Terminal: Serial; declare const global: { + SDA: typeof SDA; + SCL: typeof SCL; show: typeof show; acceleration: typeof acceleration; compass: typeof compass; + FET: typeof FET; + VIBRATE: typeof VIBRATE; + LED: typeof LED; + LED1: typeof LED1; + LED2: typeof LED2; BTNA: typeof BTNA; BTNB: typeof BTNB; BTNU: typeof BTNU; @@ -11188,13 +10755,7 @@ declare const global: { CORNER4: typeof CORNER4; CORNER5: typeof CORNER5; CORNER6: typeof CORNER6; - FET: typeof FET; - SDA: typeof SDA; - SCL: typeof SCL; - VIBRATE: typeof VIBRATE; - LED: typeof LED; - LED1: typeof LED1; - LED2: typeof LED2; + Bluetooth: typeof Bluetooth; MOS1: typeof MOS1; MOS2: typeof MOS2; MOS3: typeof MOS3; @@ -11203,21 +10764,25 @@ declare const global: { IOEXT1: typeof IOEXT1; IOEXT2: typeof IOEXT2; IOEXT3: typeof IOEXT3; - NaN: typeof NaN; - Infinity: typeof Infinity; - HIGH: typeof HIGH; - LOW: typeof LOW; - arguments: typeof arguments; - eval: typeof eval; - parseInt: typeof parseInt; - parseFloat: typeof parseFloat; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - btoa: typeof btoa; - atob: typeof atob; - encodeURIComponent: typeof encodeURIComponent; - decodeURIComponent: typeof decodeURIComponent; - require: typeof require; + Terminal: typeof Terminal; + global: typeof global; + setBusyIndicator: typeof setBusyIndicator; + setSleepIndicator: typeof setSleepIndicator; + setDeepSleep: typeof setDeepSleep; + dump: typeof dump; + load: typeof load; + save: typeof save; + reset: typeof reset; + edit: typeof edit; + echo: typeof echo; + getTime: typeof getTime; + setTime: typeof setTime; + getSerial: typeof getSerial; + setInterval: typeof setInterval; + setTimeout: typeof setTimeout; + clearInterval: typeof clearInterval; + clearTimeout: typeof clearTimeout; + changeInterval: typeof changeInterval; peek8: typeof peek8; poke8: typeof poke8; peek16: typeof peek16; @@ -11234,26 +10799,40 @@ declare const global: { shiftOut: typeof shiftOut; setWatch: typeof setWatch; clearWatch: typeof clearWatch; - global: typeof global; - setBusyIndicator: typeof setBusyIndicator; - setSleepIndicator: typeof setSleepIndicator; - setDeepSleep: typeof setDeepSleep; + arguments: typeof arguments; + eval: typeof eval; + parseInt: typeof parseInt; + parseFloat: typeof parseFloat; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + btoa: typeof btoa; + atob: typeof atob; + encodeURIComponent: typeof encodeURIComponent; + decodeURIComponent: typeof decodeURIComponent; trace: typeof trace; - dump: typeof dump; - load: typeof load; - save: typeof save; - reset: typeof reset; print: typeof print; - edit: typeof edit; - echo: typeof echo; - getTime: typeof getTime; - setTime: typeof setTime; - getSerial: typeof getSerial; - setInterval: typeof setInterval; - setTimeout: typeof setTimeout; - clearInterval: typeof clearInterval; - clearTimeout: typeof clearTimeout; - changeInterval: typeof changeInterval; + require: typeof require; + __FILE__: typeof __FILE__; + SPI1: typeof SPI1; + SPI2: typeof SPI2; + SPI3: typeof SPI3; + I2C1: typeof I2C1; + I2C2: typeof I2C2; + I2C3: typeof I2C3; + USB: typeof USB; + Serial1: typeof Serial1; + Serial2: typeof Serial2; + Serial3: typeof Serial3; + Serial4: typeof Serial4; + Serial5: typeof Serial5; + Serial6: typeof Serial6; + LoopbackA: typeof LoopbackA; + LoopbackB: typeof LoopbackB; + Telnet: typeof Telnet; + NaN: typeof NaN; + Infinity: typeof Infinity; + HIGH: typeof HIGH; + LOW: typeof LOW; [key: string]: any; } @@ -11287,16 +10866,6 @@ declare function setSleepIndicator(pin: any): void; */ declare function setDeepSleep(sleep: boolean): void; -/** - * Output debugging information - * Note: This is not included on boards with low amounts of flash memory, or the - * Espruino board. - * - * @param {any} root - The symbol to output (optional). If nothing is specified, everything will be output - * @url http://www.espruino.com/Reference#l__global_trace - */ -declare function trace(root: any): void; - /** * Output current interpreter state in a text form such that it can be copied to a * new device @@ -11326,10 +10895,10 @@ declare function dump(): void; * Storage after reset** in much the same way as calling `reset()` then * `eval(require("Storage").read(filename))` * - * @param {any} filename - optional: The name of a text JS file to load from Storage after reset + * @param {any} [filename] - [optional] The name of a text JS file to load from Storage after reset * @url http://www.espruino.com/Reference#l__global_load */ -declare function load(filename: any): void; +declare function load(filename?: any): void; /** * Save the state of the interpreter into flash (including the results of calling @@ -11375,18 +10944,6 @@ declare function save(): void; */ declare function reset(clearFlash: boolean): void; -/** - * Print the supplied string(s) to the console - * **Note:** If you're connected to a computer (not a wall adaptor) via USB but - * **you are not running a terminal app** then when you print data Espruino may - * pause execution and wait until the computer requests the data it is trying to - * print. - * - * @param {any} text - * @url http://www.espruino.com/Reference#l__global_print - */ -declare function print(...text: any[]): void; - /** * Fill the console with the contents of the given function, so you can edit it. * NOTE: This is a convenience function - it will not edit 'inner functions'. For @@ -11545,1468 +11102,2201 @@ declare function clearTimeout(...id: any[]): void; */ declare function changeInterval(id: any, time: number): void; +/** + * Read 8 bits of memory at the given location - DANGEROUS! + * + * @param {number} addr - The address in memory to read + * @param {number} [count] - [optional] the number of items to read. If >1 a Uint8Array will be returned. + * @returns {any} The value of memory at the given location + * @url http://www.espruino.com/Reference#l__global_peek8 + */ +declare function peek8(addr: number, count?: 1): number; +declare function peek8(addr: number, count: number): Uint8Array; + +/** + * Write 8 bits of memory at the given location - VERY DANGEROUS! + * + * @param {number} addr - The address in memory to write + * @param {any} value - The value to write, or an array of values + * @url http://www.espruino.com/Reference#l__global_poke8 + */ +declare function poke8(addr: number, value: number | number[]): void; + +/** + * Read 16 bits of memory at the given location - DANGEROUS! + * + * @param {number} addr - The address in memory to read + * @param {number} [count] - [optional] the number of items to read. If >1 a Uint16Array will be returned. + * @returns {any} The value of memory at the given location + * @url http://www.espruino.com/Reference#l__global_peek16 + */ +declare function peek16(addr: number, count?: 1): number; +declare function peek16(addr: number, count: number): Uint8Array; + +/** + * Write 16 bits of memory at the given location - VERY DANGEROUS! + * + * @param {number} addr - The address in memory to write + * @param {any} value - The value to write, or an array of values + * @url http://www.espruino.com/Reference#l__global_poke16 + */ +declare function poke16(addr: number, value: number | number[]): void; + +/** + * Read 32 bits of memory at the given location - DANGEROUS! + * + * @param {number} addr - The address in memory to read + * @param {number} [count] - [optional] the number of items to read. If >1 a Uint32Array will be returned. + * @returns {any} The value of memory at the given location + * @url http://www.espruino.com/Reference#l__global_peek32 + */ +declare function peek32(addr: number, count?: 1): number; +declare function peek32(addr: number, count: number): Uint8Array; + +/** + * Write 32 bits of memory at the given location - VERY DANGEROUS! + * + * @param {number} addr - The address in memory to write + * @param {any} value - The value to write, or an array of values + * @url http://www.espruino.com/Reference#l__global_poke32 + */ +declare function poke32(addr: number, value: number | number[]): void; + +/** + * Get the analogue value of the given pin + * This is different to Arduino which only returns an integer between 0 and 1023 + * However only pins connected to an ADC will work (see the datasheet) + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset pin's state to `"analog"` + * + * @param {Pin} pin + * The pin to use + * You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `ADC` markers. + * @returns {number} The analog Value of the Pin between 0 and 1 + * @url http://www.espruino.com/Reference#l__global_analogRead + */ +declare function analogRead(pin: Pin): number; + +/** + * Set the analog Value of a pin. It will be output using PWM. + * Objects can contain: + * * `freq` - pulse frequency in Hz, e.g. ```analogWrite(A0,0.5,{ freq : 10 });``` - + * specifying a frequency will force PWM output, even if the pin has a DAC + * * `soft` - boolean, If true software PWM is used if hardware is not available. + * * `forceSoft` - boolean, If true software PWM is used even if hardware PWM or a + * DAC is available + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset pin's state to `"output"` + * + * @param {Pin} pin + * The pin to use + * You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `PWM` or `DAC` markers. + * @param {number} value - A value between 0 and 1 + * @param {any} options + * An object containing options for analog output - see below + * @url http://www.espruino.com/Reference#l__global_analogWrite + */ +declare function analogWrite(pin: Pin, value: number, options?: { freq?: number, soft?: boolean, forceSoft?: boolean }): void; + +/** + * Pulse the pin with the value for the given time in milliseconds. It uses a + * hardware timer to produce accurate pulses, and returns immediately (before the + * pulse has finished). Use `digitalPulse(A0,1,0)` to wait until a previous pulse + * has finished. + * e.g. `digitalPulse(A0,1,5);` pulses A0 high for 5ms. + * `digitalPulse(A0,1,[5,2,4]);` pulses A0 high for 5ms, low for 2ms, and high for + * 4ms + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset pin's state to `"output"` + * digitalPulse is for SHORT pulses that need to be very accurate. If you're doing + * anything over a few milliseconds, use setTimeout instead. + * + * @param {Pin} pin - The pin to use + * @param {boolean} value - Whether to pulse high (true) or low (false) + * @param {any} time - A time in milliseconds, or an array of times (in which case a square wave will be output starting with a pulse of 'value') + * @url http://www.espruino.com/Reference#l__global_digitalPulse + */ +declare function digitalPulse(pin: Pin, value: boolean, time: number | number[]): void; + +/** + * Set the digital value of the given pin. + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset pin's state to `"output"` + * If pin argument is an array of pins (e.g. `[A2,A1,A0]`) the value argument will + * be treated as an array of bits where the last array element is the least + * significant bit. + * In this case, pin values are set least significant bit first (from the + * right-hand side of the array of pins). This means you can use the same pin + * multiple times, for example `digitalWrite([A1,A1,A0,A0],0b0101)` would pulse A0 + * followed by A1. + * If the pin argument is an object with a `write` method, the `write` method will + * be called with the value passed through. + * + * @param {any} pin - The pin to use + * @param {number} value - Whether to pulse high (true) or low (false) + * @url http://www.espruino.com/Reference#l__global_digitalWrite + */ +declare function digitalWrite(pin: Pin, value: boolean): void; + +/** + * Get the digital value of the given pin. + * **Note:** if you didn't call `pinMode` beforehand then this function will also + * reset pin's state to `"input"` + * If the pin argument is an array of pins (e.g. `[A2,A1,A0]`) the value returned + * will be an number where the last array element is the least significant bit, for + * example if `A0=A1=1` and `A2=0`, `digitalRead([A2,A1,A0]) == 0b011` + * If the pin argument is an object with a `read` method, the `read` method will be + * called and the integer value it returns passed back. + * + * @param {any} pin - The pin to use + * @returns {number} The digital Value of the Pin + * @url http://www.espruino.com/Reference#l__global_digitalRead + */ +declare function digitalRead(pin: Pin): number; + +/** + * Set the mode of the given pin. + * * `auto`/`undefined` - Don't change state, but allow `digitalWrite`/etc to + * automatically change state as appropriate + * * `analog` - Analog input + * * `input` - Digital input + * * `input_pullup` - Digital input with internal ~40k pull-up resistor + * * `input_pulldown` - Digital input with internal ~40k pull-down resistor + * * `output` - Digital output + * * `opendrain` - Digital output that only ever pulls down to 0v. Sending a + * logical `1` leaves the pin open circuit + * * `opendrain_pullup` - Digital output that pulls down to 0v. Sending a logical + * `1` enables internal ~40k pull-up resistor + * * `af_output` - Digital output from built-in peripheral + * * `af_opendrain` - Digital output from built-in peripheral that only ever pulls + * down to 0v. Sending a logical `1` leaves the pin open circuit + * **Note:** `digitalRead`/`digitalWrite`/etc set the pin mode automatically + * *unless* `pinMode` has been called first. If you want `digitalRead`/etc to set + * the pin mode automatically after you have called `pinMode`, simply call it again + * with no mode argument (`pinMode(pin)`), `auto` as the argument (`pinMode(pin, + * "auto")`), or with the 3rd 'automatic' argument set to true (`pinMode(pin, + * "output", true)`). + * + * @param {Pin} pin - The pin to set pin mode for + * @param {any} mode - The mode - a string that is either 'analog', 'input', 'input_pullup', 'input_pulldown', 'output', 'opendrain', 'af_output' or 'af_opendrain'. Do not include this argument or use 'auto' if you want to revert to automatic pin mode setting. + * @param {boolean} automatic - Optional, default is false. If true, subsequent commands will automatically change the state (see notes below) + * @url http://www.espruino.com/Reference#l__global_pinMode + */ +declare function pinMode(pin: Pin, mode?: PinMode | "auto", automatic?: boolean): void; + +/** + * Return the current mode of the given pin. See `pinMode` for more information on + * returned values. + * + * @param {Pin} pin - The pin to check + * @returns {any} The pin mode, as a string + * @url http://www.espruino.com/Reference#l__global_getPinMode + */ +declare function getPinMode(pin: Pin): PinMode; + +/** + * Shift an array of data out using the pins supplied *least significant bit + * first*, for example: + * ``` + * // shift out to single clk+data + * shiftOut(A0, { clk : A1 }, [1,0,1,0]); + * ``` + * ``` + * // shift out a whole byte (like software SPI) + * shiftOut(A0, { clk : A1, repeat: 8 }, [1,2,3,4]); + * ``` + * ``` + * // shift out via 4 data pins + * shiftOut([A3,A2,A1,A0], { clk : A4 }, [1,2,3,4]); + * ``` + * `options` is an object of the form: + * ``` + * { + * clk : pin, // a pin to use as the clock (undefined = no pin) + * clkPol : bool, // clock polarity - default is 0 (so 1 normally, pulsing to 0 to clock data in) + * repeat : int, // number of clocks per array item + * } + * ``` + * Each item in the `data` array will be output to the pins, with the first pin in + * the array being the MSB and the last the LSB, then the clock will be pulsed in + * the polarity given. + * `repeat` is the amount of times shift data out for each array item. For instance + * we may want to shift 8 bits out through 2 pins - in which case we need to set + * repeat to 4. + * + * @param {any} pins - A pin, or an array of pins to use + * @param {any} options - Options, for instance the clock (see below) + * @param {any} data - The data to shift out (see `E.toUint8Array` for info on the forms this can take) + * @url http://www.espruino.com/Reference#l__global_shiftOut + */ +declare function shiftOut(pins: Pin | Pin[], options: { clk?: Pin, clkPol?: boolean, repeat?: number }, data: Uint8ArrayResolvable): void; + +/** + * Call the function specified when the pin changes. Watches set with `setWatch` + * can be removed using `clearWatch`. + * If the `options` parameter is an object, it can contain the following + * information (all optional): + * ``` + * { + * // Whether to keep producing callbacks, or remove the watch after the first callback + * repeat: true/false(default), + * // Trigger on the rising or falling edge of the signal. Can be a string, or 1='rising', -1='falling', 0='both' + * edge:'rising'(default for built-in buttons)/'falling'/'both'(default for pins), + * // Use software-debouncing to stop multiple calls if a switch bounces + * // This is the time in milliseconds to wait for bounces to subside, or 0 to disable + * debounce:10 (0 is default for pins, 25 is default for built-in buttons), + * // Advanced: If the function supplied is a 'native' function (compiled or assembly) + * // setting irq:true will call that function in the interrupt itself + * irq : false(default) + * // Advanced: If specified, the given pin will be read whenever the watch is called + * // and the state will be included as a 'data' field in the callback + * data : pin + * // Advanced: On Nordic devices, a watch may be 'high' or 'low' accuracy. By default low + * // accuracy is used (which is better for power consumption), but this means that + * // high speed pulses (less than 25us) may not be reliably received. Setting hispeed=true + * // allows for detecting high speed pulses at the expense of higher idle power consumption + * hispeed : true + * } + * ``` + * The `function` callback is called with an argument, which is an object of type + * `{state:bool, time:float, lastTime:float}`. + * * `state` is whether the pin is currently a `1` or a `0` + * * `time` is the time in seconds at which the pin changed state + * * `lastTime` is the time in seconds at which the **pin last changed state**. + * When using `edge:'rising'` or `edge:'falling'`, this is not the same as when + * the function was last called. + * * `data` is included if `data:pin` was specified in the options, and can be + * used for reading in clocked data + * For instance, if you want to measure the length of a positive pulse you could + * use `setWatch(function(e) { console.log(e.time-e.lastTime); }, BTN, { + * repeat:true, edge:'falling' });`. This will only be called on the falling edge + * of the pulse, but will be able to measure the width of the pulse because + * `e.lastTime` is the time of the rising edge. + * Internally, an interrupt writes the time of the pin's state change into a queue + * with the exact time that it happened, and the function supplied to `setWatch` is + * executed only from the main message loop. However, if the callback is a native + * function `void (bool state)` then you can add `irq:true` to options, which will + * cause the function to be called from within the IRQ. When doing this, interrupts + * will happen on both edges and there will be no debouncing. + * **Note:** if you didn't call `pinMode` beforehand then this function will reset + * pin's state to `"input"` + * **Note:** The STM32 chip (used in the [Espruino Board](/EspruinoBoard) and + * [Pico](/Pico)) cannot watch two pins with the same number - e.g. `A0` and `B0`. + * **Note:** On nRF52 chips (used in Puck.js, Pixl.js, MDBT42Q) `setWatch` disables + * the GPIO output on that pin. In order to be able to write to the pin again you + * need to disable the watch with `clearWatch`. + * + * @param {any} function - A Function or String to be executed + * @param {Pin} pin - The pin to watch + * @param {any} options - If a boolean or integer, it determines whether to call this once (false = default) or every time a change occurs (true). Can be an object of the form `{ repeat: true/false(default), edge:'rising'/'falling'/'both'(default), debounce:10}` - see below for more information. + * @returns {any} An ID that can be passed to clearWatch + * @url http://www.espruino.com/Reference#l__global_setWatch + */ +declare function setWatch(func: ((arg: { state: boolean, time: number, lastTime: number }) => void) | string, pin: Pin, options?: boolean | { repeat?: boolean, edge?: "rising" | "falling" | "both", debounce?: number, irq?: boolean, data?: Pin, hispeed?: boolean }): number; + +/** + * Clear the Watch that was created with setWatch. If no parameter is supplied, all watches will be removed. + * To avoid accidentally deleting all Watches, if a parameter is supplied but is `undefined` then an Exception will be thrown. + * + * @param {any} id - The id returned by a previous call to setWatch. **Only one argument is allowed.** + * @url http://www.espruino.com/Reference#l__global_clearWatch + */ +declare function clearWatch(id: number): void; + +/** + * A variable containing the arguments given to the function: + * ``` + * function hello() { + * console.log(arguments.length, JSON.stringify(arguments)); + * } + * hello() // 0 [] + * hello("Test") // 1 ["Test"] + * hello(1,2,3) // 3 [1,2,3] + * ``` + * **Note:** Due to the way Espruino works this is doesn't behave exactly the same + * as in normal JavaScript. The length of the arguments array will never be less + * than the number of arguments specified in the function declaration: + * `(function(a){ return arguments.length; })() == 1`. Normal JavaScript + * interpreters would return `0` in the above case. + * @returns {any} An array containing all the arguments given to the function + * @url http://www.espruino.com/Reference#l__global_arguments + */ +declare const arguments: any; + +/** + * Evaluate a string containing JavaScript code + * + * @param {any} code + * @returns {any} The result of evaluating the string + * @url http://www.espruino.com/Reference#l__global_eval + */ +declare function eval(code: any): any; + +/** + * Convert a string representing a number into an integer + * + * @param {any} string + * @param {any} [radix] - [optional] The Radix of the string + * @returns {any} The integer value of the string (or NaN) + * @url http://www.espruino.com/Reference#l__global_parseInt + */ +declare function parseInt(string: any, radix?: any): any; + +/** + * Convert a string representing a number into an float + * + * @param {any} string + * @returns {number} The value of the string + * @url http://www.espruino.com/Reference#l__global_parseFloat + */ +declare function parseFloat(string: any): number; + +/** + * Is the parameter a finite number or not? If needed, the parameter is first + * converted to a number. + * + * @param {any} x + * @returns {boolean} True is the value is a Finite number, false if not. + * @url http://www.espruino.com/Reference#l__global_isFinite + */ +declare function isFinite(x: any): boolean; + +/** + * Whether the x is NaN (Not a Number) or not + * + * @param {any} x + * @returns {boolean} True is the value is NaN, false if not. + * @url http://www.espruino.com/Reference#l__global_isNaN + */ +declare function isNaN(x: any): boolean; + +/** + * Encode the supplied string (or array) into a base64 string + * + * @param {any} binaryData - A string of data to encode + * @returns {any} A base64 encoded string + * @url http://www.espruino.com/Reference#l__global_btoa + */ +declare function btoa(binaryData: any): any; + +/** + * Decode the supplied base64 string into a normal string + * + * @param {any} base64Data - A string of base64 data to decode + * @returns {any} A string containing the decoded data + * @url http://www.espruino.com/Reference#l__global_atob + */ +declare function atob(base64Data: any): any; + +/** + * Convert a string with any character not alphanumeric or `- _ . ! ~ * ' ( )` + * converted to the form `%XY` where `XY` is its hexadecimal representation + * + * @param {any} str - A string to encode as a URI + * @returns {any} A string containing the encoded data + * @url http://www.espruino.com/Reference#l__global_encodeURIComponent + */ +declare function encodeURIComponent(str: any): any; + +/** + * Convert any groups of characters of the form '%ZZ', into characters with hex + * code '0xZZ' + * + * @param {any} str - A string to decode from a URI + * @returns {any} A string containing the decoded data + * @url http://www.espruino.com/Reference#l__global_decodeURIComponent + */ +declare function decodeURIComponent(str: any): any; + +/** + * Output debugging information + * Note: This is not included on boards with low amounts of flash memory, or the + * Espruino board. + * + * @param {any} root - The symbol to output (optional). If nothing is specified, everything will be output + * @url http://www.espruino.com/Reference#l__global_trace + */ +declare function trace(root: any): void; + +/** + * Print the supplied string(s) to the console + * **Note:** If you're connected to a computer (not a wall adaptor) via USB but + * **you are not running a terminal app** then when you print data Espruino may + * pause execution and wait until the computer requests the data it is trying to + * print. + * + * @param {any} text + * @url http://www.espruino.com/Reference#l__global_print + */ +declare function print(...text: any[]): void; + +declare function require(moduleName: "ESP8266"): typeof import("ESP8266"); +declare function require(moduleName: "crypto"): typeof import("crypto"); +declare function require(moduleName: "neopixel"): typeof import("neopixel"); +declare function require(moduleName: "net"): typeof import("net"); +declare function require(moduleName: "dgram"): typeof import("dgram"); +declare function require(moduleName: "tls"): typeof import("tls"); +declare function require(moduleName: "Wifi"): typeof import("Wifi"); +declare function require(moduleName: "NetworkJS"): typeof import("NetworkJS"); +declare function require(moduleName: "http"): typeof import("http"); +declare function require(moduleName: "WIZnet"): typeof import("WIZnet"); +declare function require(moduleName: "CC3000"): typeof import("CC3000"); +declare function require(moduleName: "TelnetServer"): typeof import("TelnetServer"); +declare function require(moduleName: "fs"): typeof import("fs"); +declare function require(moduleName: "tv"): typeof import("tv"); +declare function require(moduleName: "tensorflow"): typeof import("tensorflow"); +declare function require(moduleName: "heatshrink"): typeof import("heatshrink"); +declare function require(moduleName: "Flash"): typeof import("Flash"); +declare function require(moduleName: "Storage"): typeof import("Storage"); +declare function require(moduleName: string): any; + +/** + * The filename of the JavaScript that is currently executing. + * If `load` has been called with a filename (eg `load("myfile.js")`) then + * `__FILE__` is set to that filename. Otherwise (eg `load()`) or immediately + * after booting, `__FILE__` is not set. + * @returns {any} The filename of the JavaScript that is currently executing + * @url http://www.espruino.com/Reference#l__global___FILE__ + */ +declare const __FILE__: any; + +/** + * The first SPI port + * @url http://www.espruino.com/Reference#l__global_SPI1 + */ +declare const SPI1: SPI; + +/** + * The second SPI port + * @url http://www.espruino.com/Reference#l__global_SPI2 + */ +declare const SPI2: SPI; + +/** + * The third SPI port + * @url http://www.espruino.com/Reference#l__global_SPI3 + */ +declare const SPI3: SPI; + +/** + * The first I2C port + * @url http://www.espruino.com/Reference#l__global_I2C1 + */ +declare const I2C1: I2C; + +/** + * The second I2C port + * @url http://www.espruino.com/Reference#l__global_I2C2 + */ +declare const I2C2: I2C; + +/** + * The third I2C port + * @url http://www.espruino.com/Reference#l__global_I2C3 + */ +declare const I2C3: I2C; + +/** + * The USB Serial port + * @url http://www.espruino.com/Reference#l__global_USB + */ +declare const USB: Serial; + +/** + * The first Serial (USART) port + * @url http://www.espruino.com/Reference#l__global_Serial1 + */ +declare const Serial1: Serial; + +/** + * The second Serial (USART) port + * @url http://www.espruino.com/Reference#l__global_Serial2 + */ +declare const Serial2: Serial; + +/** + * The third Serial (USART) port + * @url http://www.espruino.com/Reference#l__global_Serial3 + */ +declare const Serial3: Serial; + +/** + * The fourth Serial (USART) port + * @url http://www.espruino.com/Reference#l__global_Serial4 + */ +declare const Serial4: Serial; + +/** + * The fifth Serial (USART) port + * @url http://www.espruino.com/Reference#l__global_Serial5 + */ +declare const Serial5: Serial; + +/** + * The sixth Serial (USART) port + * @url http://www.espruino.com/Reference#l__global_Serial6 + */ +declare const Serial6: Serial; + +/** + * A loopback serial device. Data sent to `LoopbackA` comes out of `LoopbackB` and + * vice versa + * @url http://www.espruino.com/Reference#l__global_LoopbackA + */ +declare const LoopbackA: Serial; + +/** + * A loopback serial device. Data sent to `LoopbackA` comes out of `LoopbackB` and + * vice versa + * @url http://www.espruino.com/Reference#l__global_LoopbackB + */ +declare const LoopbackB: Serial; + +/** + * A telnet serial device that maps to the built-in telnet console server (devices + * that have built-in wifi only). + * @url http://www.espruino.com/Reference#l__global_Telnet + */ +declare const Telnet: Serial; + +/** + * @returns {number} Not a Number + * @url http://www.espruino.com/Reference#l__global_NaN + */ +declare const NaN: number; + +/** + * @returns {number} Positive Infinity (1/0) + * @url http://www.espruino.com/Reference#l__global_Infinity + */ +declare const Infinity: number; + +/** + * @returns {number} Logic 1 for Arduino compatibility - this is the same as just typing `1` + * @url http://www.espruino.com/Reference#l__global_HIGH + */ +declare const HIGH: true; + +/** + * @returns {number} Logic 0 for Arduino compatibility - this is the same as just typing `0` + * @url http://www.espruino.com/Reference#l__global_LOW + */ +declare const LOW: false; + // LIBRARIES -type Libraries = { +/** + * The ESP8266 library is specific to the ESP8266 version of Espruino, i.e., + * running Espruino on an ESP8266 module (not to be confused with using the ESP8266 + * as Wifi add-on to an Espruino board). This library contains functions to handle + * ESP8266-specific actions. For example: `var esp8266 = require('ESP8266'); + * esp8266.reboot();` performs a hardware reset of the module. + * @url http://www.espruino.com/Reference#ESP8266 + */ +declare module "ESP8266" { /** - * @url http://www.espruino.com/Reference#tensorflow + * Perform a hardware reset/reboot of the esp8266. + * @url http://www.espruino.com/Reference#l_ESP8266_reboot */ - tensorflow: { - /** - * - * @param {number} arenaSize - The TensorFlow Arena size - * @param {any} model - The model to use - this should be a flat array/string - * @returns {any} A tensorflow instance - * @url http://www.espruino.com/Reference#l_tensorflow_create - */ - create(arenaSize: number, model: any): TFMicroInterpreter; - } + function reboot(): void; /** - * This library handles interfacing with a FAT32 filesystem on an SD card. The API - * is designed to be similar to node.js's - However Espruino does not currently - * support asynchronous file IO, so the functions behave like node.js's xxxxSync - * functions. Versions of the functions with 'Sync' after them are also provided - * for compatibility. - * To use this, you must type ```var fs = require('fs')``` to get access to the - * library - * See [the page on File IO](http://www.espruino.com/File+IO) for more information, - * and for examples on wiring up an SD card if your device doesn't come with one. - * **Note:** If you want to remove an SD card after you have started using it, you - * *must* call `E.unmountSD()` or you may cause damage to the card. - * @url http://www.espruino.com/Reference#fs + * At boot time the esp8266's firmware captures the cause of the reset/reboot. This + * function returns this information in an object with the following fields: + * * `reason`: "power on", "wdt reset", "exception", "soft wdt", "restart", "deep + * sleep", or "reset pin" + * * `exccause`: exception cause + * * `epc1`, `epc2`, `epc3`: instruction pointers + * * `excvaddr`: address being accessed + * * `depc`: (?) + * @returns {any} An object with the reset cause information + * @url http://www.espruino.com/Reference#l_ESP8266_getResetInfo */ - fs: { - /** - * List all files in the supplied directory, returning them as an array of strings. - * NOTE: Espruino does not yet support Async file IO, so this function behaves like - * the 'Sync' version. - * - * @param {any} path - The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory - * @returns {any} An array of filename strings (or undefined if the directory couldn't be listed) - * @url http://www.espruino.com/Reference#l_fs_readdir - */ - readdir(path: any): any; - - /** - * List all files in the supplied directory, returning them as an array of strings. - * - * @param {any} path - The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory - * @returns {any} An array of filename strings (or undefined if the directory couldn't be listed) - * @url http://www.espruino.com/Reference#l_fs_readdirSync - */ - readdirSync(path: any): any; - - /** - * Write the data to the given file - * NOTE: Espruino does not yet support Async file IO, so this function behaves like - * the 'Sync' version. - * - * @param {any} path - The path of the file to write - * @param {any} data - The data to write to the file - * @returns {boolean} True on success, false on failure - * @url http://www.espruino.com/Reference#l_fs_writeFile - */ - writeFile(path: any, data: any): boolean; - - /** - * Write the data to the given file - * - * @param {any} path - The path of the file to write - * @param {any} data - The data to write to the file - * @returns {boolean} True on success, false on failure - * @url http://www.espruino.com/Reference#l_fs_writeFileSync - */ - writeFileSync(path: any, data: any): boolean; - - /** - * Append the data to the given file, created a new file if it doesn't exist - * NOTE: Espruino does not yet support Async file IO, so this function behaves like - * the 'Sync' version. - * - * @param {any} path - The path of the file to write - * @param {any} data - The data to write to the file - * @returns {boolean} True on success, false on failure - * @url http://www.espruino.com/Reference#l_fs_appendFile - */ - appendFile(path: any, data: any): boolean; - - /** - * Append the data to the given file, created a new file if it doesn't exist - * - * @param {any} path - The path of the file to write - * @param {any} data - The data to write to the file - * @returns {boolean} True on success, false on failure - * @url http://www.espruino.com/Reference#l_fs_appendFileSync - */ - appendFileSync(path: any, data: any): boolean; - - /** - * Read all data from a file and return as a string - * NOTE: Espruino does not yet support Async file IO, so this function behaves like - * the 'Sync' version. - * - * @param {any} path - The path of the file to read - * @returns {any} A string containing the contents of the file (or undefined if the file doesn't exist) - * @url http://www.espruino.com/Reference#l_fs_readFile - */ - readFile(path: any): any; - - /** - * Read all data from a file and return as a string. - * **Note:** The size of files you can load using this method is limited by the - * amount of available RAM. To read files a bit at a time, see the `File` class. - * - * @param {any} path - The path of the file to read - * @returns {any} A string containing the contents of the file (or undefined if the file doesn't exist) - * @url http://www.espruino.com/Reference#l_fs_readFileSync - */ - readFileSync(path: any): any; - - /** - * Delete the given file - * NOTE: Espruino does not yet support Async file IO, so this function behaves like - * the 'Sync' version. - * - * @param {any} path - The path of the file to delete - * @returns {boolean} True on success, or false on failure - * @url http://www.espruino.com/Reference#l_fs_unlink - */ - unlink(path: any): boolean; - - /** - * Delete the given file - * - * @param {any} path - The path of the file to delete - * @returns {boolean} True on success, or false on failure - * @url http://www.espruino.com/Reference#l_fs_unlinkSync - */ - unlinkSync(path: any): boolean; - - /** - * Return information on the given file. This returns an object with the following - * fields: - * size: size in bytes dir: a boolean specifying if the file is a directory or not - * mtime: A Date structure specifying the time the file was last modified - * - * @param {any} path - The path of the file to get information on - * @returns {any} An object describing the file, or undefined on failure - * @url http://www.espruino.com/Reference#l_fs_statSync - */ - statSync(path: any): any; - - /** - * Create the directory - * NOTE: Espruino does not yet support Async file IO, so this function behaves like - * the 'Sync' version. - * - * @param {any} path - The name of the directory to create - * @returns {boolean} True on success, or false on failure - * @url http://www.espruino.com/Reference#l_fs_mkdir - */ - mkdir(path: any): boolean; - - /** - * Create the directory - * - * @param {any} path - The name of the directory to create - * @returns {boolean} True on success, or false on failure - * @url http://www.espruino.com/Reference#l_fs_mkdirSync - */ - mkdirSync(path: any): boolean; - - /** - * - * @param {any} source - The source file/stream that will send content. - * @param {any} destination - The destination file/stream that will receive content from the source. - * @param {any} options - * An optional object `{ chunkSize : int=64, end : bool=true, complete : function }` - * chunkSize : The amount of data to pipe from source to destination at a time - * complete : a function to call when the pipe activity is complete - * end : call the 'end' function on the destination when the source is finished - * @url http://www.espruino.com/Reference#l_fs_pipe - */ - pipe(source: any, destination: any, options: any): void; - } + function getResetInfo(): any; /** - * Cryptographic functions - * **Note:** This library is currently only included in builds for boards where - * there is space. For other boards there is `crypto.js` which implements SHA1 in - * JS. - * @url http://www.espruino.com/Reference#crypto + * Enable or disable the logging of debug information. A value of `true` enables + * debug logging while a value of `false` disables debug logging. Debug output is + * sent to UART1 (gpio2). + * + * @param {boolean} enable - Enable or disable the debug logging. + * @url http://www.espruino.com/Reference#l_ESP8266_logDebug */ - crypto: { - /** - * Class containing AES encryption/decryption - * @returns {any} - * @url http://www.espruino.com/Reference#l_crypto_AES - */ - AES: AES; - - /** - * Performs a SHA1 hash and returns the result as a 20 byte ArrayBuffer. - * **Note:** On some boards (currently only Espruino Original) there isn't space - * for a fully unrolled SHA1 implementation so a slower all-JS implementation is - * used instead. - * - * @param {any} message - The message to apply the hash to - * @returns {any} Returns a 20 byte ArrayBuffer - * @url http://www.espruino.com/Reference#l_crypto_SHA1 - */ - SHA1(message: any): ArrayBuffer; - - /** - * Performs a SHA224 hash and returns the result as a 28 byte ArrayBuffer - * - * @param {any} message - The message to apply the hash to - * @returns {any} Returns a 20 byte ArrayBuffer - * @url http://www.espruino.com/Reference#l_crypto_SHA224 - */ - SHA224(message: any): ArrayBuffer; - - /** - * Performs a SHA256 hash and returns the result as a 32 byte ArrayBuffer - * - * @param {any} message - The message to apply the hash to - * @returns {any} Returns a 20 byte ArrayBuffer - * @url http://www.espruino.com/Reference#l_crypto_SHA256 - */ - SHA256(message: any): ArrayBuffer; - - /** - * Performs a SHA384 hash and returns the result as a 48 byte ArrayBuffer - * - * @param {any} message - The message to apply the hash to - * @returns {any} Returns a 20 byte ArrayBuffer - * @url http://www.espruino.com/Reference#l_crypto_SHA384 - */ - SHA384(message: any): ArrayBuffer; - - /** - * Performs a SHA512 hash and returns the result as a 64 byte ArrayBuffer - * - * @param {any} message - The message to apply the hash to - * @returns {any} Returns a 32 byte ArrayBuffer - * @url http://www.espruino.com/Reference#l_crypto_SHA512 - */ - SHA512(message: any): ArrayBuffer; - - /** - * Password-Based Key Derivation Function 2 algorithm, using SHA512 - * - * @param {any} passphrase - Passphrase - * @param {any} salt - Salt for turning passphrase into a key - * @param {any} options - Object of Options, `{ keySize: 8 (in 32 bit words), iterations: 10, hasher: 'SHA1'/'SHA224'/'SHA256'/'SHA384'/'SHA512' }` - * @returns {any} Returns an ArrayBuffer - * @url http://www.espruino.com/Reference#l_crypto_PBKDF2 - */ - PBKDF2(passphrase: any, salt: any, options: any): ArrayBuffer; - } + function logDebug(enable: boolean): void; /** - * Library that initialises a network device that calls into JavaScript - * @url http://www.espruino.com/Reference#NetworkJS + * Set the debug logging mode. It can be disabled (which frees ~1.2KB of heap), + * enabled in-memory only, or in-memory and output to a UART. + * + * @param {number} mode - Debug log mode: 0=off, 1=in-memory only, 2=in-mem and uart0, 3=in-mem and uart1. + * @url http://www.espruino.com/Reference#l_ESP8266_setLog */ - NetworkJS: { - /** - * Initialise the network using the callbacks given and return the first argument. - * For instance: - * ``` - * require("NetworkJS").create({ - * create : function(host, port, socketType, options) { - * // Create a socket and return its index, host is a string, port is an integer. - * // If host isn't defined, create a server socket - * console.log("Create",host,port); - * return 1; - * }, - * close : function(sckt) { - * // Close the socket. returns nothing - * }, - * accept : function(sckt) { - * // Accept the connection on the server socket. Returns socket number or -1 if no connection - * return -1; - * }, - * recv : function(sckt, maxLen, socketType) { - * // Receive data. Returns a string (even if empty). - * // If non-string returned, socket is then closed - * return null;//or ""; - * }, - * send : function(sckt, data, socketType) { - * // Send data (as string). Returns the number of bytes sent - 0 is ok. - * // Less than 0 - * return data.length; - * } - * }); - * ``` - * `socketType` is an integer - 2 for UDP, or see SocketType in - * https://github.com/espruino/Espruino/blob/master/libs/network/network.h for more - * information. - * - * @param {any} obj - An object containing functions to access the network device - * @returns {any} The object passed in - * @url http://www.espruino.com/Reference#l_NetworkJS_create - */ - create(obj: any): any; - } + function setLog(mode: number): void; /** - * This library implements a telnet console for the Espruino interpreter. It - * requires a network connection, e.g. Wifi, and **currently only functions on the - * ESP8266 and on Linux **. It uses port 23 on the ESP8266 and port 2323 on Linux. - * **Note:** To enable on Linux, run `./espruino --telnet` - * @url http://www.espruino.com/Reference#TelnetServer + * Prints the contents of the debug log to the console. + * @url http://www.espruino.com/Reference#l_ESP8266_printLog */ - TelnetServer: { - /** - * - * @param {any} options - Options controlling the telnet console server `{ mode : 'on|off'}` - * @url http://www.espruino.com/Reference#l_TelnetServer_setOptions - */ - setOptions(options: any): void; - } + function printLog(): void; /** - * This library allows you to create TCPIP servers and clients - * In order to use this, you will need an extra module to get network connectivity. - * This is designed to be a cut-down version of the [node.js - * library](http://nodejs.org/api/net.html). Please see the [Internet](/Internet) - * page for more information on how to use it. - * @url http://www.espruino.com/Reference#net + * Returns one line from the log or up to 128 characters. + * @url http://www.espruino.com/Reference#l_ESP8266_readLog */ - net: { - /** - * Create a Server - * When a request to the server is made, the callback is called. In the callback - * you can use the methods on the connection to send data. You can also add - * `connection.on('data',function() { ... })` to listen for received data - * - * @param {any} callback - A `function(connection)` that will be called when a connection is made - * @returns {any} Returns a new Server Object - * @url http://www.espruino.com/Reference#l_net_createServer - */ - createServer(callback: any): Server; - - /** - * Create a TCP socket connection - * - * @param {any} options - An object containing host,port fields - * @param {any} callback - A `function(sckt)` that will be called with the socket when a connection is made. You can then call `sckt.write(...)` to send data, and `sckt.on('data', function(data) { ... })` and `sckt.on('close', function() { ... })` to deal with the response. - * @returns {any} Returns a new net.Socket object - * @url http://www.espruino.com/Reference#l_net_connect - */ - connect(options: any, callback: any): Socket; - } + function readLog(): void; /** - * This library allows you to create UDP/DATAGRAM servers and clients - * In order to use this, you will need an extra module to get network connectivity. - * This is designed to be a cut-down version of the [node.js - * library](http://nodejs.org/api/dgram.html). Please see the [Internet](/Internet) - * page for more information on how to use it. - * @url http://www.espruino.com/Reference#dgram + * Dumps info about all sockets to the log. This is for troubleshooting the socket + * implementation. + * @url http://www.espruino.com/Reference#l_ESP8266_dumpSocketInfo */ - dgram: { - /** - * Create a UDP socket - * - * @param {any} type - Socket type to create e.g. 'udp4'. Or options object { type: 'udp4', reuseAddr: true, recvBufferSize: 1024 } - * @param {any} callback - A `function(sckt)` that will be called with the socket when a connection is made. You can then call `sckt.send(...)` to send data, and `sckt.on('message', function(data) { ... })` and `sckt.on('close', function() { ... })` to deal with the response. - * @returns {any} Returns a new dgram.Socket object - * @url http://www.espruino.com/Reference#l_dgram_createSocket - */ - createSocket(type: any, callback: any): dgramSocket; - } + function dumpSocketInfo(): void; /** - * This library allows you to create TCPIP servers and clients using TLS encryption - * In order to use this, you will need an extra module to get network connectivity. - * This is designed to be a cut-down version of the [node.js - * library](http://nodejs.org/api/tls.html). Please see the [Internet](/Internet) - * page for more information on how to use it. - * @url http://www.espruino.com/Reference#tls + * **Note:** This is deprecated. Use `E.setClock(80/160)` **Note:** Set the + * operating frequency of the ESP8266 processor. The default is 160Mhz. + * **Warning**: changing the cpu frequency affects the timing of some I/O + * operations, notably of software SPI and I2C, so things may be a bit slower at + * 80Mhz. + * + * @param {any} freq - Desired frequency - either 80 or 160. + * @url http://www.espruino.com/Reference#l_ESP8266_setCPUFreq */ - tls: { - /** - * Create a socket connection using TLS - * Options can have `ca`, `key` and `cert` fields, which should be the decoded - * content of the certificate. - * ``` - * var options = url.parse("localhost:1234"); - * options.key = atob("MIIJKQ ... OZs08C"); - * options.cert = atob("MIIFi ... Uf93rN+"); - * options.ca = atob("MIIFgDCC ... GosQML4sc="); - * require("tls").connect(options, ... ); - * ``` - * If you have the certificates as `.pem` files, you need to load these files, take - * the information between the lines beginning with `----`, remove the newlines - * from it so you have raw base64, and then feed it into `atob` as above. - * You can also: - * * Just specify the filename (<=100 characters) and it will be loaded and parsed - * if you have an SD card connected. For instance `options.key = "key.pem";` - * * Specify a function, which will be called to retrieve the data. For instance - * `options.key = function() { eeprom.load_my_info(); }; - * For more information about generating and using certificates, see: - * https://engineering.circle.com/https-authorized-certs-with-node-js/ - * (You'll need to use 2048 bit certificates as opposed to 4096 bit shown above) - * - * @param {any} options - An object containing host,port fields - * @param {any} callback - A function(res) that will be called when a connection is made. You can then call `res.on('data', function(data) { ... })` and `res.on('close', function() { ... })` to deal with the response. - * @returns {any} Returns a new net.Socket object - * @url http://www.espruino.com/Reference#l_tls_connect - */ - connect(options: any, callback: any): Socket; - } + function setCPUFreq(freq: any): void; /** - * @url http://www.espruino.com/Reference#CC3000 + * Returns an object that contains details about the state of the ESP8266 with the + * following fields: + * * `sdkVersion` - Version of the SDK. + * * `cpuFrequency` - CPU operating frequency in Mhz. + * * `freeHeap` - Amount of free heap in bytes. + * * `maxCon` - Maximum number of concurrent connections. + * * `flashMap` - Configured flash size&map: '512KB:256/256' .. '4MB:512/512' + * * `flashKB` - Configured flash size in KB as integer + * * `flashChip` - Type of flash chip as string with manufacturer & chip, ex: '0xEF + * 0x4016` + * @returns {any} The state of the ESP8266 + * @url http://www.espruino.com/Reference#l_ESP8266_getState */ - CC3000: { - /** - * Initialise the CC3000 and return a WLAN object - * - * @param {any} spi - Device to use for SPI (or undefined to use the default). SPI should be 1,000,000 baud, and set to 'mode 1' - * @param {Pin} cs - The pin to use for Chip Select - * @param {Pin} en - The pin to use for Enable - * @param {Pin} irq - The pin to use for Interrupts - * @returns {any} A WLAN Object - * @url http://www.espruino.com/Reference#l_CC3000_connect - */ - connect(spi: any, cs: Pin, en: Pin, irq: Pin): WLAN; - } + function getState(): any; /** - * Library for communication with the WIZnet Ethernet module - * @url http://www.espruino.com/Reference#WIZnet + * **Note:** This is deprecated. Use `require("Flash").getFree()` + * @returns {any} Array of objects with `addr` and `length` properties describing the free flash areas available + * @url http://www.espruino.com/Reference#l_ESP8266_getFreeFlash */ - WIZnet: { - /** - * Initialise the WIZnet module and return an Ethernet object - * - * @param {any} spi - Device to use for SPI (or undefined to use the default) - * @param {Pin} cs - The pin to use for Chip Select - * @returns {any} An Ethernet Object - * @url http://www.espruino.com/Reference#l_WIZnet_connect - */ - connect(spi: any, cs: Pin): Ethernet; - } + function getFreeFlash(): any; /** - * The Wifi library is designed to control the Wifi interface. It supports - * functionality such as connecting to wifi networks, getting network information, - * starting an access point, etc. - * It is available on these devices: - * * [Espruino WiFi](http://www.espruino.com/WiFi#using-wifi) - * * [ESP8266](http://www.espruino.com/EspruinoESP8266) - * * [ESP32](http://www.espruino.com/ESP32) - * **Certain features may or may not be implemented on your device** however we - * have documented what is available and what isn't. - * If you're not using one of the devices above, a separate WiFi library is - * provided. For instance: - * * An [ESP8266 connected to an Espruino - * board](http://www.espruino.com/ESP8266#software) - * * An [CC3000 WiFi Module](http://www.espruino.com/CC3000) - * [Other ways of connecting to the - * net](http://www.espruino.com/Internet#related-pages) such as GSM, Ethernet and - * LTE have their own libraries. - * You can use the WiFi library as follows: - * ``` - * var wifi = require("Wifi"); - * wifi.connect("my-ssid", {password:"my-pwd"}, function(ap){ console.log("connected:", ap); }); - * ``` - * On ESP32/ESP8266 if you want the connection to happen automatically at boot, add - * `wifi.save();`. On other platforms, place `wifi.connect` in a function called - * `onInit`. - * @url http://www.espruino.com/Reference#Wifi + * + * @param {any} arrayOfData - Array of data to CRC + * @returns {any} 32-bit CRC + * @url http://www.espruino.com/Reference#l_ESP8266_crc32 */ - Wifi: { - /** - * The 'associated' event is called when an association with an access point has - * succeeded, i.e., a connection to the AP's network has been established. - * On ESP32/ESP8266 there is a `details` parameter which includes: - * * ssid - The SSID of the access point to which the association was established - * * mac - The BSSID/mac address of the access point - * * channel - The wifi channel used (an integer, typ 1..14) - * @param {string} event - The event to listen to. - * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `details` An object with event details - * @url http://www.espruino.com/Reference#l_Wifi_associated - */ - on(event: "associated", callback: (details: any) => void): void; - - /** - * The 'disconnected' event is called when an association with an access point has - * been lost. - * On ESP32/ESP8266 there is a `details` parameter which includes: - * * ssid - The SSID of the access point from which the association was lost - * * mac - The BSSID/mac address of the access point - * * reason - The reason for the disconnection (string) - * @param {string} event - The event to listen to. - * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `details` An object with event details - * @url http://www.espruino.com/Reference#l_Wifi_disconnected - */ - on(event: "disconnected", callback: (details: any) => void): void; - - /** - * The 'auth_change' event is called when the authentication mode with the - * associated access point changes. The details include: - * * oldMode - The old auth mode (string: open, wep, wpa, wpa2, wpa_wpa2) - * * newMode - The new auth mode (string: open, wep, wpa, wpa2, wpa_wpa2) - * @param {string} event - The event to listen to. - * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `details` An object with event details - * @url http://www.espruino.com/Reference#l_Wifi_auth_change - */ - on(event: "auth_change", callback: (details: any) => void): void; - - /** - * The 'dhcp_timeout' event is called when a DHCP request to the connected access - * point fails and thus no IP address could be acquired (or renewed). - * @param {string} event - The event to listen to. - * @param {() => void} callback - A function that is executed when the event occurs. - * @url http://www.espruino.com/Reference#l_Wifi_dhcp_timeout - */ - on(event: "dhcp_timeout", callback: () => void): void; - - /** - * The 'connected' event is called when the connection with an access point is - * ready for traffic. In the case of a dynamic IP address configuration this is - * when an IP address is obtained, in the case of static IP address allocation this - * happens when an association is formed (in that case the 'associated' and - * 'connected' events are fired in rapid succession). - * On ESP32/ESP8266 there is a `details` parameter which includes: - * * ip - The IP address obtained as string - * * netmask - The network's IP range mask as string - * * gw - The network's default gateway as string - * @param {string} event - The event to listen to. - * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `details` An object with event details - * @url http://www.espruino.com/Reference#l_Wifi_connected - */ - on(event: "connected", callback: (details: any) => void): void; - - /** - * The 'sta_joined' event is called when a station establishes an association (i.e. - * connects) with the esp8266's access point. The details include: - * * mac - The MAC address of the station in string format (00:00:00:00:00:00) - * @param {string} event - The event to listen to. - * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `details` An object with event details - * @url http://www.espruino.com/Reference#l_Wifi_sta_joined - */ - on(event: "sta_joined", callback: (details: any) => void): void; - - /** - * The 'sta_left' event is called when a station disconnects from the esp8266's - * access point (or its association times out?). The details include: - * * mac - The MAC address of the station in string format (00:00:00:00:00:00) - * @param {string} event - The event to listen to. - * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `details` An object with event details - * @url http://www.espruino.com/Reference#l_Wifi_sta_left - */ - on(event: "sta_left", callback: (details: any) => void): void; - - /** - * The 'probe_recv' event is called when a probe request is received from some - * station by the esp8266's access point. The details include: - * * mac - The MAC address of the station in string format (00:00:00:00:00:00) - * * rssi - The signal strength in dB of the probe request - * @param {string} event - The event to listen to. - * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: - * * `details` An object with event details - * @url http://www.espruino.com/Reference#l_Wifi_probe_recv - */ - on(event: "probe_recv", callback: (details: any) => void): void; - - /** - * Disconnect the wifi station from an access point and disable the station mode. - * It is OK to call `disconnect` to turn off station mode even if no connection - * exists (for example, connection attempts may be failing). Station mode can be - * re-enabled by calling `connect` or `scan`. - * - * @param {any} callback - An optional `callback()` function to be called back on disconnection. The callback function receives no argument. - * @url http://www.espruino.com/Reference#l_Wifi_disconnect - */ - disconnect(callback: any): void; - - /** - * Stop being an access point and disable the AP operation mode. AP mode can be - * re-enabled by calling `startAP`. - * - * @param {any} callback - An optional `callback()` function to be called back on successful stop. The callback function receives no argument. - * @url http://www.espruino.com/Reference#l_Wifi_stopAP - */ - stopAP(callback: any): void; - - /** - * Connect to an access point as a station. If there is an existing connection to - * an AP it is first disconnected if the SSID or password are different from those - * passed as parameters. Put differently, if the passed SSID and password are - * identical to the currently connected AP then nothing is changed. When the - * connection attempt completes the callback function is invoked with one `err` - * parameter, which is NULL if there is no error and a string message if there is - * an error. If DHCP is enabled the callback occurs once an IP addres has been - * obtained, if a static IP is set the callback occurs once the AP's network has - * been joined. The callback is also invoked if a connection already exists and - * does not need to be changed. - * The options properties may contain: - * * `password` - Password string to be used to access the network. - * * `dnsServers` (array of String) - An array of up to two DNS servers in dotted - * decimal format string. - * * `channel` - Wifi channel of the access point (integer, typ 0..14, 0 means any - * channel), only on ESP8266. - * * `bssid` - Mac address of the access point (string, type "00:00:00:00:00:00"), - * only on ESP8266. - * Notes: - * * the options should include the ability to set a static IP and associated - * netmask and gateway, this is a future enhancement. - * * the only error reported in the callback is "Bad password", all other errors - * (such as access point not found or DHCP timeout) just cause connection - * retries. If the reporting of such temporary errors is desired, the caller must - * use its own timeout and the `getDetails().status` field. - * * the `connect` call automatically enabled station mode, it can be disabled - * again by calling `disconnect`. - * - * @param {any} ssid - The access point network id. - * @param {any} options - Connection options (optional). - * @param {any} callback - A `callback(err)` function to be called back on completion. `err` is null on success, or contains an error string on failure. - * @url http://www.espruino.com/Reference#l_Wifi_connect - */ - connect(ssid: any, options: any, callback: any): void; - - /** - * Perform a scan for access points. This will enable the station mode if it is not - * currently enabled. Once the scan is complete the callback function is called - * with an array of APs found, each AP is an object with: - * * `ssid`: SSID string. - * * `mac`: access point MAC address in 00:00:00:00:00:00 format. - * * `authMode`: `open`, `wep`, `wpa`, `wpa2`, or `wpa_wpa2`. - * * `channel`: wifi channel 1..13. - * * `hidden`: true if the SSID is hidden (ESP32/ESP8266 only) - * * `rssi`: signal strength in dB in the range -110..0. - * Notes: - * * in order to perform the scan the station mode is turned on and remains on, use - * Wifi.disconnect() to turn it off again, if desired. - * * only one scan can be in progress at a time. - * - * @param {any} callback - A `callback(err, ap_list)` function to be called back on completion. `err==null` and `ap_list` is an array on success, or `err` is an error string and `ap_list` is undefined on failure. - * @url http://www.espruino.com/Reference#l_Wifi_scan - */ - scan(callback: any): void; - - /** - * Create a WiFi access point allowing stations to connect. If the password is NULL - * or an empty string the access point is open, otherwise it is encrypted. The - * callback function is invoked once the access point is set-up and receives one - * `err` argument, which is NULL on success and contains an error message string - * otherwise. - * The `options` object can contain the following properties. - * * `authMode` - The authentication mode to use. Can be one of "open", "wpa2", - * "wpa", "wpa_wpa2". The default is open (but open access points are not - * recommended). - * * `password` - The password for connecting stations if authMode is not open. - * * `channel` - The channel to be used for the access point in the range 1..13. If - * the device is also connected to an access point as a station then that access - * point determines the channel. - * * `hidden` - The flag if visible or not (0:visible, 1:hidden), default is - * visible. - * Notes: - * * the options should include the ability to set the AP IP and associated - * netmask, this is a future enhancement. - * * the `startAP` call automatically enables AP mode. It can be disabled again by - * calling `stopAP`. - * - * @param {any} ssid - The network id. - * @param {any} options - Configuration options (optional). - * @param {any} callback - Optional `callback(err)` function to be called when the AP is successfully started. `err==null` on success, or an error string on failure. - * @url http://www.espruino.com/Reference#l_Wifi_startAP - */ - startAP(ssid: any, options: any, callback: any): void; - - /** - * Retrieve the current overall WiFi configuration. This call provides general - * information that pertains to both station and access point modes. The getDetails - * and getAPDetails calls provide more in-depth information about the station and - * access point configurations, respectively. The status object has the following - * properties: - * * `station` - Status of the wifi station: `off`, `connecting`, ... - * * `ap` - Status of the wifi access point: `disabled`, `enabled`. - * * `mode` - The current operation mode: `off`, `sta`, `ap`, `sta+ap`. - * * `phy` - Modulation standard configured: `11b`, `11g`, `11n` (the esp8266 docs - * are not very clear, but it is assumed that 11n means b/g/n). This setting - * limits the modulations that the radio will use, it does not indicate the - * current modulation used with a specific access point. - * * `powersave` - Power saving mode: `none` (radio is on all the time), `ps-poll` - * (radio is off between beacons as determined by the access point's DTIM - * setting). Note that in 'ap' and 'sta+ap' modes the radio is always on, i.e., - * no power saving is possible. - * * `savedMode` - The saved operation mode which will be applied at boot time: - * `off`, `sta`, `ap`, `sta+ap`. - * - * @param {any} callback - Optional `callback(status)` function to be called back with the current Wifi status, i.e. the same object as returned directly. - * @returns {any} An object representing the current WiFi status, if available immediately. - * @url http://www.espruino.com/Reference#l_Wifi_getStatus - */ - getStatus(callback: any): any; - - /** - * Sets a number of global wifi configuration settings. All parameters are optional - * and which are passed determines which settings are updated. The settings - * available are: - * * `phy` - Modulation standard to allow: `11b`, `11g`, `11n` (the esp8266 docs - * are not very clear, but it is assumed that 11n means b/g/n). - * * `powersave` - Power saving mode: `none` (radio is on all the time), `ps-poll` - * (radio is off between beacons as determined by the access point's DTIM - * setting). Note that in 'ap' and 'sta+ap' modes the radio is always on, i.e., - * no power saving is possible. - * Note: esp8266 SDK programmers may be missing an "opmode" option to set the - * sta/ap/sta+ap operation mode. Please use connect/scan/disconnect/startAP/stopAP, - * which all set the esp8266 opmode indirectly. - * - * @param {any} settings - An object with the configuration settings to change. - * @url http://www.espruino.com/Reference#l_Wifi_setConfig - */ - setConfig(settings: any): void; - - /** - * Retrieve the wifi station configuration and status details. The details object - * has the following properties: - * * `status` - Details about the wifi station connection, one of `off`, - * `connecting`, `wrong_password`, `no_ap_found`, `connect_fail`, or `connected`. - * The off, bad_password and connected states are stable, the other states are - * transient. The connecting state will either result in connected or one of the - * error states (bad_password, no_ap_found, connect_fail) and the no_ap_found and - * connect_fail states will result in a reconnection attempt after some interval. - * * `rssi` - signal strength of the connected access point in dB, typically in the - * range -110 to 0, with anything greater than -30 being an excessively strong - * signal. - * * `ssid` - SSID of the access point. - * * `password` - the password used to connect to the access point. - * * `authMode` - the authentication used: `open`, `wpa`, `wpa2`, `wpa_wpa2` (not - * currently supported). - * * `savedSsid` - the SSID to connect to automatically at boot time, null if none. - * - * @param {any} callback - An optional `callback(details)` function to be called back with the wifi details, i.e. the same object as returned directly. - * @returns {any} An object representing the wifi station details, if available immediately. - * @url http://www.espruino.com/Reference#l_Wifi_getDetails - */ - getDetails(callback: any): any; - - /** - * Retrieve the current access point configuration and status. The details object - * has the following properties: - * * `status` - Current access point status: `enabled` or `disabled` - * * `stations` - an array of the stations connected to the access point. This - * array may be empty. Each entry in the array is an object describing the - * station which, at a minimum contains `ip` being the IP address of the station. - * * `ssid` - SSID to broadcast. - * * `password` - Password for authentication. - * * `authMode` - the authentication required of stations: `open`, `wpa`, `wpa2`, - * `wpa_wpa2`. - * * `hidden` - True if the SSID is hidden, false otherwise. - * * `maxConn` - Max number of station connections supported. - * * `savedSsid` - the SSID to broadcast automatically at boot time, null if the - * access point is to be disabled at boot. - * - * @param {any} callback - An optional `callback(details)` function to be called back with the current access point details, i.e. the same object as returned directly. - * @returns {any} An object representing the current access point details, if available immediately. - * @url http://www.espruino.com/Reference#l_Wifi_getAPDetails - */ - getAPDetails(callback: any): any; - - /** - * On boards where this is not available, just issue the `connect` commands you - * need to run at startup from an `onInit` function. - * Save the current wifi configuration (station and access point) to flash and - * automatically apply this configuration at boot time, unless `what=="clear"`, in - * which case the saved configuration is cleared such that wifi remains disabled at - * boot. The saved configuration includes: - * * mode (off/sta/ap/sta+ap) - * * SSIDs & passwords - * * phy (11b/g/n) - * * powersave setting - * * DHCP hostname - * - * @param {any} what - An optional parameter to specify what to save, on the esp8266 the two supported values are `clear` and `sta+ap`. The default is `sta+ap` - * @url http://www.espruino.com/Reference#l_Wifi_save - */ - save(what: any): void; - - /** - * Restores the saved Wifi configuration from flash. See `Wifi.save()`. - * @url http://www.espruino.com/Reference#l_Wifi_restore - */ - restore(): void; - - /** - * Return the station IP information in an object as follows: - * * ip - IP address as string (e.g. "192.168.1.5") - * * netmask - The interface netmask as string (ESP8266/ESP32 only) - * * gw - The network gateway as string (ESP8266/ESP32 only) - * * mac - The MAC address as string of the form 00:00:00:00:00:00 - * Note that the `ip`, `netmask`, and `gw` fields are omitted if no connection is established: - * - * @param {any} callback - An optional `callback(err, ipinfo)` function to be called back with the IP information. - * @returns {any} An object representing the station IP information, if available immediately (**ONLY** on ESP8266/ESP32). - * @url http://www.espruino.com/Reference#l_Wifi_getIP - */ - getIP(callback: any): any; - - /** - * Return the access point IP information in an object which contains: - * * ip - IP address as string (typ "192.168.4.1") - * * netmask - The interface netmask as string - * * gw - The network gateway as string - * * mac - The MAC address as string of the form 00:00:00:00:00:00 - * - * @param {any} callback - An optional `callback(err, ipinfo)` function to be called back with the the IP information. - * @returns {any} An object representing the esp8266's Access Point IP information, if available immediately (**ONLY** on ESP8266/ESP32). - * @url http://www.espruino.com/Reference#l_Wifi_getAPIP - */ - getAPIP(callback: any): any; - - /** - * Lookup the hostname and invoke a callback with the IP address as integer - * argument. If the lookup fails, the callback is invoked with a null argument. - * **Note:** only a single hostname lookup can be made at a time, concurrent - * lookups are not supported. - * - * @param {any} hostname - The hostname to lookup. - * @param {any} callback - The `callback(ip)` to invoke when the IP is returned. `ip==null` on failure. - * @url http://www.espruino.com/Reference#l_Wifi_getHostByName - */ - getHostByName(hostname: any, callback: any): void; - - /** - * Returns the hostname announced to the DHCP server and broadcast via mDNS when - * connecting to an access point. - * - * @param {any} callback - An optional `callback(hostname)` function to be called back with the hostname. - * @returns {any} The currently configured hostname, if available immediately. - * @url http://www.espruino.com/Reference#l_Wifi_getHostname - */ - getHostname(callback: any): any; - - /** - * Set the hostname. Depending on implemenation, the hostname is sent with every - * DHCP request and is broadcast via mDNS. The DHCP hostname may be visible in the - * access point and may be forwarded into DNS as hostname.local. If a DHCP lease - * currently exists changing the hostname will cause a disconnect and reconnect in - * order to transmit the change to the DHCP server. The mDNS announcement also - * includes an announcement for the "espruino" service. - * - * @param {any} hostname - The new hostname. - * @param {any} callback - An optional `callback()` function to be called back when the hostname is set - * @url http://www.espruino.com/Reference#l_Wifi_setHostname - */ - setHostname(hostname: any, callback: any): void; - - /** - * Starts the SNTP (Simple Network Time Protocol) service to keep the clock - * synchronized with the specified server. Note that the time zone is really just - * an offset to UTC and doesn't handle daylight savings time. The interval - * determines how often the time server is queried and Espruino's time is - * synchronized. The initial synchronization occurs asynchronously after setSNTP - * returns. - * - * @param {any} server - The NTP server to query, for example, `us.pool.ntp.org` - * @param {any} tz_offset - Local time zone offset in the range -11..13. - * @url http://www.espruino.com/Reference#l_Wifi_setSNTP - */ - setSNTP(server: any, tz_offset: any): void; - - /** - * The `settings` object must contain the following properties. - * * `ip` IP address as string (e.g. "192.168.5.100") - * * `gw` The network gateway as string (e.g. "192.168.5.1") - * * `netmask` The interface netmask as string (e.g. "255.255.255.0") - * - * @param {any} settings - Configuration settings - * @param {any} callback - A `callback(err)` function to invoke when ip is set. `err==null` on success, or a string on failure. - * @url http://www.espruino.com/Reference#l_Wifi_setIP - */ - setIP(settings: any, callback: any): void; - - /** - * The `settings` object must contain the following properties. - * * `ip` IP address as string (e.g. "192.168.5.100") - * * `gw` The network gateway as string (e.g. "192.168.5.1") - * * `netmask` The interface netmask as string (e.g. "255.255.255.0") - * - * @param {any} settings - Configuration settings - * @param {any} callback - A `callback(err)` function to invoke when ip is set. `err==null` on success, or a string on failure. - * @url http://www.espruino.com/Reference#l_Wifi_setAPIP - */ - setAPIP(settings: any, callback: any): void; - - /** - * Issues a ping to the given host, and calls a callback with the time when the - * ping is received. - * - * @param {any} hostname - The host to ping - * @param {any} callback - A `callback(time)` function to invoke when a ping is received - * @url http://www.espruino.com/Reference#l_Wifi_ping - */ - ping(hostname: any, callback: any): void; - - /** - * Switch to using a higher communication speed with the WiFi module. - * * `true` = 921600 baud - * * `false` = 115200 - * * `1843200` (or any number) = use a specific baud rate. * eg. - * `wifi.turbo(true,callback)` or `wifi.turbo(1843200,callback)` - * - * @param {any} enable - true (or a baud rate as a number) to enable, false to disable - * @param {any} callback - A `callback()` function to invoke when turbo mode has been set - * @url http://www.espruino.com/Reference#l_Wifi_turbo - */ - turbo(enable: any, callback: any): void; - } + function crc32(arrayOfData: any): any; /** - * This library allows you to create http servers and make http requests - * In order to use this, you will need an extra module to get network connectivity - * such as the [TI CC3000](/CC3000) or [WIZnet W5500](/WIZnet). - * This is designed to be a cut-down version of the [node.js - * library](http://nodejs.org/api/http.html). Please see the [Internet](/Internet) - * page for more information on how to use it. - * @url http://www.espruino.com/Reference#http + * **This function is deprecated.** Please use `require("neopixel").write(pin, + * data)` instead + * + * @param {Pin} pin - Pin for output signal. + * @param {any} arrayOfData - Array of LED data. + * @url http://www.espruino.com/Reference#l_ESP8266_neopixelWrite */ - http: { - /** - * Create an HTTP Server - * When a request to the server is made, the callback is called. In the callback - * you can use the methods on the response (`httpSRs`) to send data. You can also - * add `request.on('data',function() { ... })` to listen for POSTed data - * - * @param {any} callback - A function(request,response) that will be called when a connection is made - * @returns {any} Returns a new httpSrv object - * @url http://www.espruino.com/Reference#l_http_createServer - */ - createServer(callback: any): httpSrv; - - /** - * Create an HTTP Request - `end()` must be called on it to complete the operation. - * `options` is of the form: - * ``` - * var options = { - * host: 'example.com', // host name - * port: 80, // (optional) port, defaults to 80 - * path: '/', // path sent to server - * method: 'GET', // HTTP command sent to server (must be uppercase 'GET', 'POST', etc) - * protocol: 'http:', // optional protocol - https: or http: - * headers: { key : value, key : value } // (optional) HTTP headers - * }; - * var req = require("http").request(options, function(res) { - * res.on('data', function(data) { - * console.log("HTTP> "+data); - * }); - * res.on('close', function(data) { - * console.log("Connection closed"); - * }); - * }); - * // You can req.write(...) here if your request requires data to be sent. - * req.end(); // called to finish the HTTP request and get the response - * ``` - * You can easily pre-populate `options` from a URL using `var options = - * url.parse("http://www.example.com/foo.html")` - * There's an example of using [`http.request` for HTTP POST - * here](/Internet#http-post) - * **Note:** if TLS/HTTPS is enabled, options can have `ca`, `key` and `cert` - * fields. See `tls.connect` for more information about these and how to use them. - * - * @param {any} options - An object containing host,port,path,method,headers fields (and also ca,key,cert if HTTPS is enabled) - * @param {any} callback - A function(res) that will be called when a connection is made. You can then call `res.on('data', function(data) { ... })` and `res.on('close', function() { ... })` to deal with the response. - * @returns {any} Returns a new httpCRq object - * @url http://www.espruino.com/Reference#l_http_request - */ - request(options: any, callback: any): httpCRq; - - /** - * Request a webpage over HTTP - a convenience function for `http.request()` that - * makes sure the HTTP command is 'GET', and that calls `end` automatically. - * ``` - * require("http").get("http://pur3.co.uk/hello.txt", function(res) { - * res.on('data', function(data) { - * console.log("HTTP> "+data); - * }); - * res.on('close', function(data) { - * console.log("Connection closed"); - * }); - * }); - * ``` - * See `http.request()` and [the Internet page](/Internet) and ` for more usage - * examples. - * - * @param {any} options - A simple URL, or an object containing host,port,path,method fields - * @param {any} callback - A function(res) that will be called when a connection is made. You can then call `res.on('data', function(data) { ... })` and `res.on('close', function() { ... })` to deal with the response. - * @returns {any} Returns a new httpCRq object - * @url http://www.espruino.com/Reference#l_http_get - */ - get(options: any, callback: any): httpCRq; - } + function neopixelWrite(pin: Pin, arrayOfData: any): void; /** - * This library provides TV out capability on the Espruino and Espruino Pico. - * See the [Television](/Television) page for more information. - * @url http://www.espruino.com/Reference#tv + * Put the ESP8266 into 'deep sleep' for the given number of microseconds, reducing + * power consumption drastically. + * meaning of option values: + * 0 - the 108th Byte of init parameter decides whether RF calibration will be + * performed or not. + * 1 - run RF calibration after waking up. Power consumption is high. + * 2 - no RF calibration after waking up. Power consumption is low. + * 4 - no RF after waking up. Power consumption is the lowest. + * **Note:** unlike normal Espruino boards' 'deep sleep' mode, ESP8266 deep sleep + * actually turns off the processor. After the given number of microseconds have + * elapsed, the ESP8266 will restart as if power had been turned off and then back + * on. *All contents of RAM will be lost*. Connect GPIO 16 to RST to enable wakeup. + * **Special:** 0 microseconds cause sleep forever until external wakeup RST pull + * down occurs. + * + * @param {any} micros - Number of microseconds to sleep. + * @param {any} option - posible values are 0, 1, 2 or 4 + * @url http://www.espruino.com/Reference#l_ESP8266_deepSleep */ - tv: { - /** - * This initialises the TV output. Options for PAL are as follows: - * ``` - * var g = require('tv').setup({ type : "pal", - * video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1) - * sync : A6, // Pin - Timer pin to use for video sync - * width : 384, - * height : 270, // max 270 - * }); - * ``` - * and for VGA: - * ``` - * var g = require('tv').setup({ type : "vga", - * video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1) - * hsync : A6, // Pin - Timer pin to use for video sync - * vsync : A5, // Pin - pin to use for video sync - * width : 220, - * height : 240, - * repeat : 2, // amount of times to repeat each line - * }); - * ``` - * or - * ``` - * var g = require('tv').setup({ type : "vga", - * video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1) - * hsync : A6, // Pin - Timer pin to use for video sync - * vsync : A5, // Pin - pin to use for video sync - * width : 220, - * height : 480, - * repeat : 1, // amount of times to repeat each line - * }); - * ``` - * See the [Television](/Television) page for more information. - * - * @param {any} options - Various options for the TV output - * @param {number} width - * @returns {any} A graphics object - * @url http://www.espruino.com/Reference#l_tv_setup - */ - setup(options: any, width: number): any; - } + function deepSleep(micros: any, option: any): void; /** - * Simple library for compression/decompression using - * [heatshrink](https://github.com/atomicobject/heatshrink), an - * [LZSS](https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Storer%E2%80%93Szymanski) - * compression tool. - * Espruino uses heatshrink internally to compress RAM down to fit in Flash memory - * when `save()` is used. This just exposes that functionality. - * Functions here take and return buffers of data. There is no support for - * streaming, so both the compressed and decompressed data must be able to fit in - * memory at the same time. - * @url http://www.espruino.com/Reference#heatshrink + * **DEPRECATED** - please use `Wifi.ping` instead. + * Perform a network ping request. The parameter can be either a String or a + * numeric IP address. + * + * @param {any} ipAddr - A string representation of an IP address. + * @param {any} pingCallback - Optional callback function. + * @url http://www.espruino.com/Reference#l_ESP8266_ping */ - heatshrink: { - /** - * - * @param {any} data - The data to compress - * @returns {any} Returns the result as an ArrayBuffer - * @url http://www.espruino.com/Reference#l_heatshrink_compress - */ - compress(data: any): ArrayBuffer; - - /** - * - * @param {any} data - The data to decompress - * @returns {any} Returns the result as an ArrayBuffer - * @url http://www.espruino.com/Reference#l_heatshrink_decompress - */ - decompress(data: any): ArrayBuffer; - } - - /** - * This library allows you to write to Neopixel/WS281x/APA10x/SK6812 LED strips - * These use a high speed single-wire protocol which needs platform-specific - * implementation on some devices - hence this library to simplify things. - * @url http://www.espruino.com/Reference#neopixel - */ - neopixel: { - /** - * Write to a strip of NeoPixel/WS281x/APA104/APA106/SK6812-style LEDs attached to - * the given pin. - * ``` - * // set just one pixel, red, green, blue - * require("neopixel").write(B15, [255,0,0]); - * ``` - * ``` - * // Produce an animated rainbow over 25 LEDs - * var rgb = new Uint8ClampedArray(25*3); - * var pos = 0; - * function getPattern() { - * pos++; - * for (var i=0;i void} callback - A function that is executed when the event occurs. Its arguments are: + * * `details` An object with event details + * @url http://www.espruino.com/Reference#l_Wifi_associated + */ + function on(event: "associated", callback: (details: any) => void): void; + + /** + * The 'disconnected' event is called when an association with an access point has + * been lost. + * On ESP32/ESP8266 there is a `details` parameter which includes: + * * ssid - The SSID of the access point from which the association was lost + * * mac - The BSSID/mac address of the access point + * * reason - The reason for the disconnection (string) + * @param {string} event - The event to listen to. + * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `details` An object with event details + * @url http://www.espruino.com/Reference#l_Wifi_disconnected + */ + function on(event: "disconnected", callback: (details: any) => void): void; + + /** + * The 'auth_change' event is called when the authentication mode with the + * associated access point changes. The details include: + * * oldMode - The old auth mode (string: open, wep, wpa, wpa2, wpa_wpa2) + * * newMode - The new auth mode (string: open, wep, wpa, wpa2, wpa_wpa2) + * @param {string} event - The event to listen to. + * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `details` An object with event details + * @url http://www.espruino.com/Reference#l_Wifi_auth_change + */ + function on(event: "auth_change", callback: (details: any) => void): void; + + /** + * The 'dhcp_timeout' event is called when a DHCP request to the connected access + * point fails and thus no IP address could be acquired (or renewed). + * @param {string} event - The event to listen to. + * @param {() => void} callback - A function that is executed when the event occurs. + * @url http://www.espruino.com/Reference#l_Wifi_dhcp_timeout + */ + function on(event: "dhcp_timeout", callback: () => void): void; + + /** + * The 'connected' event is called when the connection with an access point is + * ready for traffic. In the case of a dynamic IP address configuration this is + * when an IP address is obtained, in the case of static IP address allocation this + * happens when an association is formed (in that case the 'associated' and + * 'connected' events are fired in rapid succession). + * On ESP32/ESP8266 there is a `details` parameter which includes: + * * ip - The IP address obtained as string + * * netmask - The network's IP range mask as string + * * gw - The network's default gateway as string + * @param {string} event - The event to listen to. + * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `details` An object with event details + * @url http://www.espruino.com/Reference#l_Wifi_connected + */ + function on(event: "connected", callback: (details: any) => void): void; + + /** + * The 'sta_joined' event is called when a station establishes an association (i.e. + * connects) with the esp8266's access point. The details include: + * * mac - The MAC address of the station in string format (00:00:00:00:00:00) + * @param {string} event - The event to listen to. + * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `details` An object with event details + * @url http://www.espruino.com/Reference#l_Wifi_sta_joined + */ + function on(event: "sta_joined", callback: (details: any) => void): void; + + /** + * The 'sta_left' event is called when a station disconnects from the esp8266's + * access point (or its association times out?). The details include: + * * mac - The MAC address of the station in string format (00:00:00:00:00:00) + * @param {string} event - The event to listen to. + * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `details` An object with event details + * @url http://www.espruino.com/Reference#l_Wifi_sta_left + */ + function on(event: "sta_left", callback: (details: any) => void): void; + + /** + * The 'probe_recv' event is called when a probe request is received from some + * station by the esp8266's access point. The details include: + * * mac - The MAC address of the station in string format (00:00:00:00:00:00) + * * rssi - The signal strength in dB of the probe request + * @param {string} event - The event to listen to. + * @param {(details: any) => void} callback - A function that is executed when the event occurs. Its arguments are: + * * `details` An object with event details + * @url http://www.espruino.com/Reference#l_Wifi_probe_recv + */ + function on(event: "probe_recv", callback: (details: any) => void): void; + + /** + * Disconnect the wifi station from an access point and disable the station mode. + * It is OK to call `disconnect` to turn off station mode even if no connection + * exists (for example, connection attempts may be failing). Station mode can be + * re-enabled by calling `connect` or `scan`. + * + * @param {any} [callback] - [optional] An `callback()` function to be called back on disconnection. The callback function receives no argument. + * @url http://www.espruino.com/Reference#l_Wifi_disconnect + */ + function disconnect(callback?: any): void; + + /** + * Stop being an access point and disable the AP operation mode. AP mode can be + * re-enabled by calling `startAP`. + * + * @param {any} [callback] - [optional] An `callback()` function to be called back on successful stop. The callback function receives no argument. + * @url http://www.espruino.com/Reference#l_Wifi_stopAP + */ + function stopAP(callback?: any): void; + + /** + * Connect to an access point as a station. If there is an existing connection to + * an AP it is first disconnected if the SSID or password are different from those + * passed as parameters. Put differently, if the passed SSID and password are + * identical to the currently connected AP then nothing is changed. When the + * connection attempt completes the callback function is invoked with one `err` + * parameter, which is NULL if there is no error and a string message if there is + * an error. If DHCP is enabled the callback occurs once an IP address has been + * obtained, if a static IP is set the callback occurs once the AP's network has + * been joined. The callback is also invoked if a connection already exists and + * does not need to be changed. + * The options properties may contain: + * * `password` - Password string to be used to access the network. + * * `dnsServers` (array of String) - An array of up to two DNS servers in dotted + * decimal format string. + * * `channel` - Wifi channel of the access point (integer, typ 0..14, 0 means any + * channel), only on ESP8266. + * * `bssid` - Mac address of the access point (string, type "00:00:00:00:00:00"), + * only on ESP8266. + * Notes: + * * the options should include the ability to set a static IP and associated + * netmask and gateway, this is a future enhancement. + * * the only error reported in the callback is "Bad password", all other errors + * (such as access point not found or DHCP timeout) just cause connection + * retries. If the reporting of such temporary errors is desired, the caller must + * use its own timeout and the `getDetails().status` field. + * * the `connect` call automatically enabled station mode, it can be disabled + * again by calling `disconnect`. + * + * @param {any} ssid - The access point network id. + * @param {any} [options] - [optional] Connection options. + * @param {any} callback - A `callback(err)` function to be called back on completion. `err` is null on success, or contains an error string on failure. + * @url http://www.espruino.com/Reference#l_Wifi_connect + */ + function connect(ssid: string, options?: { password?: string, dnsServers?: string[], authMode?: string, channel?: number, bssid?: string }, callback?: (err: string | null) => void): void; + + /** + * Perform a scan for access points. This will enable the station mode if it is not + * currently enabled. Once the scan is complete the callback function is called + * with an array of APs found, each AP is an object with: + * * `ssid`: SSID string. + * * `mac`: access point MAC address in 00:00:00:00:00:00 format. + * * `authMode`: `open`, `wep`, `wpa`, `wpa2`, or `wpa_wpa2`. + * * `channel`: wifi channel 1..13. + * * `hidden`: true if the SSID is hidden (ESP32/ESP8266 only) + * * `rssi`: signal strength in dB in the range -110..0. + * Notes: + * * in order to perform the scan the station mode is turned on and remains on, use + * Wifi.disconnect() to turn it off again, if desired. + * * only one scan can be in progress at a time. + * + * @param {any} callback - A `callback(err, ap_list)` function to be called back on completion. `err==null` and `ap_list` is an array on success, or `err` is an error string and `ap_list` is undefined on failure. + * @url http://www.espruino.com/Reference#l_Wifi_scan + */ + function scan(callback: any): void; + + /** + * Create a WiFi access point allowing stations to connect. If the password is NULL + * or an empty string the access point is open, otherwise it is encrypted. The + * callback function is invoked once the access point is set-up and receives one + * `err` argument, which is NULL on success and contains an error message string + * otherwise. + * The `options` object can contain the following properties. + * * `authMode` - The authentication mode to use. Can be one of "open", "wpa2", + * "wpa", "wpa_wpa2". The default is open (but open access points are not + * recommended). + * * `password` - The password for connecting stations if authMode is not open. + * * `channel` - The channel to be used for the access point in the range 1..13. If + * the device is also connected to an access point as a station then that access + * point determines the channel. + * * `hidden` - The flag if visible or not (0:visible, 1:hidden), default is + * visible. + * Notes: + * * the options should include the ability to set the AP IP and associated + * netmask, this is a future enhancement. + * * the `startAP` call automatically enables AP mode. It can be disabled again by + * calling `stopAP`. + * + * @param {any} ssid - The network id. + * @param {any} [options] - [optional] Configuration options. + * @param {any} callback - Optional `callback(err)` function to be called when the AP is successfully started. `err==null` on success, or an error string on failure. + * @url http://www.espruino.com/Reference#l_Wifi_startAP + */ + function startAP(ssid: string, options?: { password?: string, authMode?: "open" | "wpa2" | "wpa" | "wpa_wpa2", channel?: number, hidden?: boolean }, callback?: (err: string | null) => void): void; + + /** + * Retrieve the current overall WiFi configuration. This call provides general + * information that pertains to both station and access point modes. The getDetails + * and getAPDetails calls provide more in-depth information about the station and + * access point configurations, respectively. The status object has the following + * properties: + * * `station` - Status of the wifi station: `off`, `connecting`, ... + * * `ap` - Status of the wifi access point: `disabled`, `enabled`. + * * `mode` - The current operation mode: `off`, `sta`, `ap`, `sta+ap`. + * * `phy` - Modulation standard configured: `11b`, `11g`, `11n` (the esp8266 docs + * are not very clear, but it is assumed that 11n means b/g/n). This setting + * limits the modulations that the radio will use, it does not indicate the + * current modulation used with a specific access point. + * * `powersave` - Power saving mode: `none` (radio is on all the time), `ps-poll` + * (radio is off between beacons as determined by the access point's DTIM + * setting). Note that in 'ap' and 'sta+ap' modes the radio is always on, i.e., + * no power saving is possible. + * * `savedMode` - The saved operation mode which will be applied at boot time: + * `off`, `sta`, `ap`, `sta+ap`. + * + * @param {any} callback - Optional `callback(status)` function to be called back with the current Wifi status, i.e. the same object as returned directly. + * @returns {any} An object representing the current WiFi status, if available immediately. + * @url http://www.espruino.com/Reference#l_Wifi_getStatus + */ + function getStatus(callback: any): any; + + /** + * Sets a number of global wifi configuration settings. All parameters are optional + * and which are passed determines which settings are updated. The settings + * available are: + * * `phy` - Modulation standard to allow: `11b`, `11g`, `11n` (the esp8266 docs + * are not very clear, but it is assumed that 11n means b/g/n). + * * `powersave` - Power saving mode: `none` (radio is on all the time), `ps-poll` + * (radio is off between beacons as determined by the access point's DTIM + * setting). Note that in 'ap' and 'sta+ap' modes the radio is always on, i.e., + * no power saving is possible. + * Note: esp8266 SDK programmers may be missing an "opmode" option to set the + * sta/ap/sta+ap operation mode. Please use connect/scan/disconnect/startAP/stopAP, + * which all set the esp8266 opmode indirectly. + * + * @param {any} settings - An object with the configuration settings to change. + * @url http://www.espruino.com/Reference#l_Wifi_setConfig + */ + function setConfig(settings: any): void; + + /** + * Retrieve the wifi station configuration and status details. The details object + * has the following properties: + * * `status` - Details about the wifi station connection, one of `off`, + * `connecting`, `wrong_password`, `no_ap_found`, `connect_fail`, or `connected`. + * The off, bad_password and connected states are stable, the other states are + * transient. The connecting state will either result in connected or one of the + * error states (bad_password, no_ap_found, connect_fail) and the no_ap_found and + * connect_fail states will result in a reconnection attempt after some interval. + * * `rssi` - signal strength of the connected access point in dB, typically in the + * range -110 to 0, with anything greater than -30 being an excessively strong + * signal. + * * `ssid` - SSID of the access point. + * * `password` - the password used to connect to the access point. + * * `authMode` - the authentication used: `open`, `wpa`, `wpa2`, `wpa_wpa2` (not + * currently supported). + * * `savedSsid` - the SSID to connect to automatically at boot time, null if none. + * + * @param {any} [callback] - [optional] An `callback(details)` function to be called back with the wifi details, i.e. the same object as returned directly. + * @returns {any} An object representing the wifi station details, if available immediately. + * @url http://www.espruino.com/Reference#l_Wifi_getDetails + */ + function getDetails(callback?: any): any; + + /** + * Retrieve the current access point configuration and status. The details object + * has the following properties: + * * `status` - Current access point status: `enabled` or `disabled` + * * `stations` - an array of the stations connected to the access point. This + * array may be empty. Each entry in the array is an object describing the + * station which, at a minimum contains `ip` being the IP address of the station. + * * `ssid` - SSID to broadcast. + * * `password` - Password for authentication. + * * `authMode` - the authentication required of stations: `open`, `wpa`, `wpa2`, + * `wpa_wpa2`. + * * `hidden` - True if the SSID is hidden, false otherwise. + * * `maxConn` - Max number of station connections supported. + * * `savedSsid` - the SSID to broadcast automatically at boot time, null if the + * access point is to be disabled at boot. + * + * @param {any} [callback] - [optional] A `callback(details)` function to be called back with the current access point details, i.e. the same object as returned directly. + * @returns {any} An object representing the current access point details, if available immediately. + * @url http://www.espruino.com/Reference#l_Wifi_getAPDetails + */ + function getAPDetails(callback?: any): any; + + /** + * On boards where this is not available, just issue the `connect` commands you + * need to run at startup from an `onInit` function. + * Save the current wifi configuration (station and access point) to flash and + * automatically apply this configuration at boot time, unless `what=="clear"`, in + * which case the saved configuration is cleared such that wifi remains disabled at + * boot. The saved configuration includes: + * * mode (off/sta/ap/sta+ap) + * * SSIDs & passwords + * * phy (11b/g/n) + * * powersave setting + * * DHCP hostname + * + * @param {any} what - An optional parameter to specify what to save, on the esp8266 the two supported values are `clear` and `sta+ap`. The default is `sta+ap` + * @url http://www.espruino.com/Reference#l_Wifi_save + */ + function save(what: any): void; + + /** + * Restores the saved Wifi configuration from flash. See `Wifi.save()`. + * @url http://www.espruino.com/Reference#l_Wifi_restore + */ + function restore(): void; + + /** + * Return the station IP information in an object as follows: + * * ip - IP address as string (e.g. "192.168.1.5") + * * netmask - The interface netmask as string (ESP8266/ESP32 only) + * * gw - The network gateway as string (ESP8266/ESP32 only) + * * mac - The MAC address as string of the form 00:00:00:00:00:00 + * Note that the `ip`, `netmask`, and `gw` fields are omitted if no connection is established: + * + * @param {any} [callback] - [optional] A `callback(err, ipinfo)` function to be called back with the IP information. + * @returns {any} An object representing the station IP information, if available immediately (**ONLY** on ESP8266/ESP32). + * @url http://www.espruino.com/Reference#l_Wifi_getIP + */ + function getIP(callback?: any): any; + + /** + * Return the access point IP information in an object which contains: + * * ip - IP address as string (typ "192.168.4.1") + * * netmask - The interface netmask as string + * * gw - The network gateway as string + * * mac - The MAC address as string of the form 00:00:00:00:00:00 + * + * @param {any} [callback] - [optional] A `callback(err, ipinfo)` function to be called back with the the IP information. + * @returns {any} An object representing the esp8266's Access Point IP information, if available immediately (**ONLY** on ESP8266/ESP32). + * @url http://www.espruino.com/Reference#l_Wifi_getAPIP + */ + function getAPIP(callback?: any): any; + + /** + * Lookup the hostname and invoke a callback with the IP address as integer + * argument. If the lookup fails, the callback is invoked with a null argument. + * **Note:** only a single hostname lookup can be made at a time, concurrent + * lookups are not supported. + * + * @param {any} hostname - The hostname to lookup. + * @param {any} callback - The `callback(ip)` to invoke when the IP is returned. `ip==null` on failure. + * @url http://www.espruino.com/Reference#l_Wifi_getHostByName + */ + function getHostByName(hostname: any, callback: any): void; + + /** + * Returns the hostname announced to the DHCP server and broadcast via mDNS when + * connecting to an access point. + * + * @param {any} [callback] - [optional] A `callback(hostname)` function to be called back with the hostname. + * @returns {any} The currently configured hostname, if available immediately. + * @url http://www.espruino.com/Reference#l_Wifi_getHostname + */ + function getHostname(callback?: any): any; + + /** + * Set the hostname. Depending on implementation, the hostname is sent with every + * DHCP request and is broadcast via mDNS. The DHCP hostname may be visible in the + * access point and may be forwarded into DNS as hostname.local. If a DHCP lease + * currently exists changing the hostname will cause a disconnect and reconnect in + * order to transmit the change to the DHCP server. The mDNS announcement also + * includes an announcement for the "espruino" service. + * + * @param {any} hostname - The new hostname. + * @param {any} [callback] - [optional] A `callback()` function to be called back when the hostname is set + * @url http://www.espruino.com/Reference#l_Wifi_setHostname + */ + function setHostname(hostname: any, callback?: any): void; + + /** + * Starts the SNTP (Simple Network Time Protocol) service to keep the clock + * synchronized with the specified server. Note that the time zone is really just + * an offset to UTC and doesn't handle daylight savings time. The interval + * determines how often the time server is queried and Espruino's time is + * synchronized. The initial synchronization occurs asynchronously after setSNTP + * returns. + * + * @param {any} server - The NTP server to query, for example, `us.pool.ntp.org` + * @param {any} tz_offset - Local time zone offset in the range -11..13. + * @url http://www.espruino.com/Reference#l_Wifi_setSNTP + */ + function setSNTP(server: any, tz_offset: any): void; + + /** + * The `settings` object must contain the following properties. + * * `ip` IP address as string (e.g. "192.168.5.100") + * * `gw` The network gateway as string (e.g. "192.168.5.1") + * * `netmask` The interface netmask as string (e.g. "255.255.255.0") + * + * @param {any} settings - Configuration settings + * @param {any} callback - A `callback(err)` function to invoke when ip is set. `err==null` on success, or a string on failure. + * @url http://www.espruino.com/Reference#l_Wifi_setIP + */ + function setIP(settings: any, callback: any): void; + + /** + * The `settings` object must contain the following properties. + * * `ip` IP address as string (e.g. "192.168.5.100") + * * `gw` The network gateway as string (e.g. "192.168.5.1") + * * `netmask` The interface netmask as string (e.g. "255.255.255.0") + * + * @param {any} settings - Configuration settings + * @param {any} callback - A `callback(err)` function to invoke when ip is set. `err==null` on success, or a string on failure. + * @url http://www.espruino.com/Reference#l_Wifi_setAPIP + */ + function setAPIP(settings: any, callback: any): void; + + /** + * Issues a ping to the given host, and calls a callback with the time when the + * ping is received. + * + * @param {any} hostname - The host to ping + * @param {any} callback - A `callback(time)` function to invoke when a ping is received + * @url http://www.espruino.com/Reference#l_Wifi_ping + */ + function ping(hostname: any, callback: any): void; + + /** + * Switch to using a higher communication speed with the WiFi module. + * * `true` = 921600 baud + * * `false` = 115200 + * * `1843200` (or any number) = use a specific baud rate. * e.g. + * `wifi.turbo(true,callback)` or `wifi.turbo(1843200,callback)` + * + * @param {any} enable - true (or a baud rate as a number) to enable, false to disable + * @param {any} callback - A `callback()` function to invoke when turbo mode has been set + * @url http://www.espruino.com/Reference#l_Wifi_turbo + */ + function turbo(enable: any, callback: any): void; +} + +/** + * Library that initialises a network device that calls into JavaScript + * @url http://www.espruino.com/Reference#NetworkJS + */ +declare module "NetworkJS" { + /** + * Initialise the network using the callbacks given and return the first argument. + * For instance: + * ``` + * require("NetworkJS").create({ + * create : function(host, port, socketType, options) { + * // Create a socket and return its index, host is a string, port is an integer. + * // If host isn't defined, create a server socket + * console.log("Create",host,port); + * return 1; + * }, + * close : function(sckt) { + * // Close the socket. returns nothing + * }, + * accept : function(sckt) { + * // Accept the connection on the server socket. Returns socket number or -1 if no connection + * return -1; + * }, + * recv : function(sckt, maxLen, socketType) { + * // Receive data. Returns a string (even if empty). + * // If non-string returned, socket is then closed + * return null;//or ""; + * }, + * send : function(sckt, data, socketType) { + * // Send data (as string). Returns the number of bytes sent - 0 is ok. + * // Less than 0 + * return data.length; + * } + * }); + * ``` + * `socketType` is an integer - 2 for UDP, or see SocketType in + * https://github.com/espruino/Espruino/blob/master/libs/network/network.h for more + * information. + * + * @param {any} obj - An object containing functions to access the network device + * @returns {any} The object passed in + * @url http://www.espruino.com/Reference#l_NetworkJS_create + */ + function create(obj: any): any; +} + +/** + * This library allows you to create http servers and make http requests + * In order to use this, you will need an extra module to get network connectivity + * such as the [TI CC3000](/CC3000) or [WIZnet W5500](/WIZnet). + * This is designed to be a cut-down version of the [node.js + * library](http://nodejs.org/api/http.html). Please see the [Internet](/Internet) + * page for more information on how to use it. + * @url http://www.espruino.com/Reference#http + */ +declare module "http" { + /** + * Create an HTTP Server + * When a request to the server is made, the callback is called. In the callback + * you can use the methods on the response (`httpSRs`) to send data. You can also + * add `request.on('data',function() { ... })` to listen for POSTed data + * + * @param {any} callback - A function(request,response) that will be called when a connection is made + * @returns {any} Returns a new httpSrv object + * @url http://www.espruino.com/Reference#l_http_createServer + */ + function createServer(callback: any): httpSrv; + + /** + * Create an HTTP Request - `end()` must be called on it to complete the operation. + * `options` is of the form: + * ``` + * var options = { + * host: 'example.com', // host name + * port: 80, // (optional) port, defaults to 80 + * path: '/', // path sent to server + * method: 'GET', // HTTP command sent to server (must be uppercase 'GET', 'POST', etc) + * protocol: 'http:', // optional protocol - https: or http: + * headers: { key : value, key : value } // (optional) HTTP headers + * }; + * var req = require("http").request(options, function(res) { + * res.on('data', function(data) { + * console.log("HTTP> "+data); + * }); + * res.on('close', function(data) { + * console.log("Connection closed"); + * }); + * }); + * // You can req.write(...) here if your request requires data to be sent. + * req.end(); // called to finish the HTTP request and get the response + * ``` + * You can easily pre-populate `options` from a URL using `var options = + * url.parse("http://www.example.com/foo.html")` + * There's an example of using [`http.request` for HTTP POST + * here](/Internet#http-post) + * **Note:** if TLS/HTTPS is enabled, options can have `ca`, `key` and `cert` + * fields. See `tls.connect` for more information about these and how to use them. + * + * @param {any} options - An object containing host,port,path,method,headers fields (and also ca,key,cert if HTTPS is enabled) + * @param {any} callback - A function(res) that will be called when a connection is made. You can then call `res.on('data', function(data) { ... })` and `res.on('close', function() { ... })` to deal with the response. + * @returns {any} Returns a new httpCRq object + * @url http://www.espruino.com/Reference#l_http_request + */ + function request(options: any, callback: any): httpCRq; + + /** + * Request a webpage over HTTP - a convenience function for `http.request()` that + * makes sure the HTTP command is 'GET', and that calls `end` automatically. + * ``` + * require("http").get("http://pur3.co.uk/hello.txt", function(res) { + * res.on('data', function(data) { + * console.log("HTTP> "+data); + * }); + * res.on('close', function(data) { + * console.log("Connection closed"); + * }); + * }); + * ``` + * See `http.request()` and [the Internet page](/Internet) and ` for more usage + * examples. + * + * @param {any} options - A simple URL, or an object containing host,port,path,method fields + * @param {any} callback - A function(res) that will be called when a connection is made. You can then call `res.on('data', function(data) { ... })` and `res.on('close', function() { ... })` to deal with the response. + * @returns {any} Returns a new httpCRq object + * @url http://www.espruino.com/Reference#l_http_get + */ + function get(options: any, callback: any): httpCRq; +} + +/** + * Library for communication with the WIZnet Ethernet module + * @url http://www.espruino.com/Reference#WIZnet + */ +declare module "WIZnet" { + /** + * Initialise the WIZnet module and return an Ethernet object + * + * @param {any} spi - Device to use for SPI (or undefined to use the default) + * @param {Pin} cs - The pin to use for Chip Select + * @returns {any} An Ethernet Object + * @url http://www.espruino.com/Reference#l_WIZnet_connect + */ + function connect(spi: any, cs: Pin): Ethernet; +} + +/** + * @url http://www.espruino.com/Reference#CC3000 + */ +declare module "CC3000" { + /** + * Initialise the CC3000 and return a WLAN object + * + * @param {any} spi - Device to use for SPI (or undefined to use the default). SPI should be 1,000,000 baud, and set to 'mode 1' + * @param {Pin} cs - The pin to use for Chip Select + * @param {Pin} en - The pin to use for Enable + * @param {Pin} irq - The pin to use for Interrupts + * @returns {any} A WLAN Object + * @url http://www.espruino.com/Reference#l_CC3000_connect + */ + function connect(spi: any, cs: Pin, en: Pin, irq: Pin): WLAN; +} + +/** + * This library implements a telnet console for the Espruino interpreter. It + * requires a network connection, e.g. Wifi, and **currently only functions on the + * ESP8266 and on Linux **. It uses port 23 on the ESP8266 and port 2323 on Linux. + * **Note:** To enable on Linux, run `./espruino --telnet` + * @url http://www.espruino.com/Reference#TelnetServer + */ +declare module "TelnetServer" { + /** + * + * @param {any} options - Options controlling the telnet console server `{ mode : 'on|off'}` + * @url http://www.espruino.com/Reference#l_TelnetServer_setOptions + */ + function setOptions(options: any): void; +} + +/** + * This library handles interfacing with a FAT32 filesystem on an SD card. The API + * is designed to be similar to node.js's - However Espruino does not currently + * support asynchronous file IO, so the functions behave like node.js's xxxxSync + * functions. Versions of the functions with 'Sync' after them are also provided + * for compatibility. + * To use this, you must type ```var fs = require('fs')``` to get access to the + * library + * See [the page on File IO](http://www.espruino.com/File+IO) for more information, + * and for examples on wiring up an SD card if your device doesn't come with one. + * **Note:** If you want to remove an SD card after you have started using it, you + * *must* call `E.unmountSD()` or you may cause damage to the card. + * @url http://www.espruino.com/Reference#fs + */ +declare module "fs" { + /** + * List all files in the supplied directory, returning them as an array of strings. + * NOTE: Espruino does not yet support Async file IO, so this function behaves like + * the 'Sync' version. + * + * @param {any} path - The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory + * @returns {any} An array of filename strings (or undefined if the directory couldn't be listed) + * @url http://www.espruino.com/Reference#l_fs_readdir + */ + function readdir(path: any): any; + + /** + * List all files in the supplied directory, returning them as an array of strings. + * + * @param {any} path - The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory + * @returns {any} An array of filename strings (or undefined if the directory couldn't be listed) + * @url http://www.espruino.com/Reference#l_fs_readdirSync + */ + function readdirSync(path: any): any; + + /** + * Write the data to the given file + * NOTE: Espruino does not yet support Async file IO, so this function behaves like + * the 'Sync' version. + * + * @param {any} path - The path of the file to write + * @param {any} data - The data to write to the file + * @returns {boolean} True on success, false on failure + * @url http://www.espruino.com/Reference#l_fs_writeFile + */ + function writeFile(path: any, data: any): boolean; + + /** + * Write the data to the given file + * + * @param {any} path - The path of the file to write + * @param {any} data - The data to write to the file + * @returns {boolean} True on success, false on failure + * @url http://www.espruino.com/Reference#l_fs_writeFileSync + */ + function writeFileSync(path: any, data: any): boolean; + + /** + * Append the data to the given file, created a new file if it doesn't exist + * NOTE: Espruino does not yet support Async file IO, so this function behaves like + * the 'Sync' version. + * + * @param {any} path - The path of the file to write + * @param {any} data - The data to write to the file + * @returns {boolean} True on success, false on failure + * @url http://www.espruino.com/Reference#l_fs_appendFile + */ + function appendFile(path: any, data: any): boolean; + + /** + * Append the data to the given file, created a new file if it doesn't exist + * + * @param {any} path - The path of the file to write + * @param {any} data - The data to write to the file + * @returns {boolean} True on success, false on failure + * @url http://www.espruino.com/Reference#l_fs_appendFileSync + */ + function appendFileSync(path: any, data: any): boolean; + + /** + * Read all data from a file and return as a string + * NOTE: Espruino does not yet support Async file IO, so this function behaves like + * the 'Sync' version. + * + * @param {any} path - The path of the file to read + * @returns {any} A string containing the contents of the file (or undefined if the file doesn't exist) + * @url http://www.espruino.com/Reference#l_fs_readFile + */ + function readFile(path: any): any; + + /** + * Read all data from a file and return as a string. + * **Note:** The size of files you can load using this method is limited by the + * amount of available RAM. To read files a bit at a time, see the `File` class. + * + * @param {any} path - The path of the file to read + * @returns {any} A string containing the contents of the file (or undefined if the file doesn't exist) + * @url http://www.espruino.com/Reference#l_fs_readFileSync + */ + function readFileSync(path: any): any; + + /** + * Delete the given file + * NOTE: Espruino does not yet support Async file IO, so this function behaves like + * the 'Sync' version. + * + * @param {any} path - The path of the file to delete + * @returns {boolean} True on success, or false on failure + * @url http://www.espruino.com/Reference#l_fs_unlink + */ + function unlink(path: any): boolean; + + /** + * Delete the given file + * + * @param {any} path - The path of the file to delete + * @returns {boolean} True on success, or false on failure + * @url http://www.espruino.com/Reference#l_fs_unlinkSync + */ + function unlinkSync(path: any): boolean; + + /** + * Return information on the given file. This returns an object with the following + * fields: + * size: size in bytes dir: a boolean specifying if the file is a directory or not + * mtime: A Date structure specifying the time the file was last modified + * + * @param {any} path - The path of the file to get information on + * @returns {any} An object describing the file, or undefined on failure + * @url http://www.espruino.com/Reference#l_fs_statSync + */ + function statSync(path: any): any; + + /** + * Create the directory + * NOTE: Espruino does not yet support Async file IO, so this function behaves like + * the 'Sync' version. + * + * @param {any} path - The name of the directory to create + * @returns {boolean} True on success, or false on failure + * @url http://www.espruino.com/Reference#l_fs_mkdir + */ + function mkdir(path: any): boolean; + + /** + * Create the directory + * + * @param {any} path - The name of the directory to create + * @returns {boolean} True on success, or false on failure + * @url http://www.espruino.com/Reference#l_fs_mkdirSync + */ + function mkdirSync(path: any): boolean; + + /** + * + * @param {any} source - The source file/stream that will send content. + * @param {any} destination - The destination file/stream that will receive content from the source. + * @param {any} [options] + * [optional] An object `{ chunkSize : int=64, end : bool=true, complete : function }` + * chunkSize : The amount of data to pipe from source to destination at a time + * complete : a function to call when the pipe activity is complete + * end : call the 'end' function on the destination when the source is finished + * @url http://www.espruino.com/Reference#l_fs_pipe + */ + function pipe(source: any, destination: any, options?: any): void; +} + +/** + * This library provides TV out capability on the Espruino and Espruino Pico. + * See the [Television](/Television) page for more information. + * @url http://www.espruino.com/Reference#tv + */ +declare module "tv" { + /** + * This initialises the TV output. Options for PAL are as follows: + * ``` + * var g = require('tv').setup({ type : "pal", + * video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1) + * sync : A6, // Pin - Timer pin to use for video sync + * width : 384, + * height : 270, // max 270 + * }); + * ``` + * and for VGA: + * ``` + * var g = require('tv').setup({ type : "vga", + * video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1) + * hsync : A6, // Pin - Timer pin to use for video sync + * vsync : A5, // Pin - pin to use for video sync + * width : 220, + * height : 240, + * repeat : 2, // amount of times to repeat each line + * }); + * ``` + * or + * ``` + * var g = require('tv').setup({ type : "vga", + * video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1) + * hsync : A6, // Pin - Timer pin to use for video sync + * vsync : A5, // Pin - pin to use for video sync + * width : 220, + * height : 480, + * repeat : 1, // amount of times to repeat each line + * }); + * ``` + * See the [Television](/Television) page for more information. + * + * @param {any} options - Various options for the TV output + * @param {number} width + * @returns {any} A graphics object + * @url http://www.espruino.com/Reference#l_tv_setup + */ + function setup(options: any, width: number): any; +} + +/** + * @url http://www.espruino.com/Reference#tensorflow + */ +declare module "tensorflow" { + /** + * + * @param {number} arenaSize - The TensorFlow Arena size + * @param {any} model - The model to use - this should be a flat array/string + * @returns {any} A tensorflow instance + * @url http://www.espruino.com/Reference#l_tensorflow_create + */ + function create(arenaSize: number, model: any): TFMicroInterpreter; +} + +/** + * Simple library for compression/decompression using + * [heatshrink](https://github.com/atomicobject/heatshrink), an + * [LZSS](https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Storer%E2%80%93Szymanski) + * compression tool. + * Espruino uses heatshrink internally to compress RAM down to fit in Flash memory + * when `save()` is used. This just exposes that functionality. + * Functions here take and return buffers of data. There is no support for + * streaming, so both the compressed and decompressed data must be able to fit in + * memory at the same time. + * @url http://www.espruino.com/Reference#heatshrink + */ +declare module "heatshrink" { + /** + * + * @param {any} data - The data to compress + * @returns {any} Returns the result as an ArrayBuffer + * @url http://www.espruino.com/Reference#l_heatshrink_compress + */ + function compress(data: any): ArrayBuffer; + + /** + * + * @param {any} data - The data to decompress + * @returns {any} Returns the result as an ArrayBuffer + * @url http://www.espruino.com/Reference#l_heatshrink_decompress + */ + function decompress(data: any): ArrayBuffer; +} + +/** + * This module allows you to read and write the nonvolatile flash memory of your + * device. + * Also see the `Storage` library, which provides a safer file-like interface to + * nonvolatile storage. + * It should be used with extreme caution, as it is easy to overwrite parts of + * Flash memory belonging to Espruino or even its bootloader. If you damage the + * bootloader then you may need external hardware such as a USB-TTL converter to + * restore it. For more information on restoring the bootloader see `Advanced + * Reflashing` in your board's reference pages. + * To see which areas of memory you can and can't overwrite, look at the values + * reported by `process.memory()`. + * **Note:** On Nordic platforms there are checks in place to help you avoid + * 'bricking' your device be damaging the bootloader. You can disable these with + * `E.setFlags({unsafeFlash:1})` + * @url http://www.espruino.com/Reference#Flash + */ +declare module "Flash" { + /** + * Returns the start and length of the flash page containing the given address. + * + * @param {number} addr - An address in memory + * @returns {any} An object of the form `{ addr : #, length : #}`, where `addr` is the start address of the page, and `length` is the length of it (in bytes). Returns undefined if no page at address + * @url http://www.espruino.com/Reference#l_Flash_getPage + */ + function getPage(addr: number): any; + + /** + * This method returns an array of objects of the form `{addr : #, length : #}`, + * representing contiguous areas of flash memory in the chip that are not used for + * anything. + * The memory areas returned are on page boundaries. This means that you can safely + * erase the page containing any address here, and you won't risk deleting part of + * the Espruino firmware. + * @returns {any} Array of objects with `addr` and `length` properties + * @url http://www.espruino.com/Reference#l_Flash_getFree + */ + function getFree(): any; + + /** + * Erase a page of flash memory + * + * @param {any} addr - An address in the page that is to be erased + * @url http://www.espruino.com/Reference#l_Flash_erasePage + */ + function erasePage(addr: any): void; + + /** + * Write data into memory at the given address + * In flash memory you may only turn bits that are 1 into bits that are 0. If + * you're writing data into an area that you have already written (so `read` + * doesn't return all `0xFF`) you'll need to call `erasePage` to clear the entire + * page. + * + * @param {any} data - The data to write + * @param {number} addr - The address to start writing from + * @url http://www.espruino.com/Reference#l_Flash_write + */ + function write(data: any, addr: number): void; + + /** + * Read flash memory from the given address + * + * @param {number} length - The amount of data to read (in bytes) + * @param {number} addr - The address to start reading from + * @returns {any} A Uint8Array of data + * @url http://www.espruino.com/Reference#l_Flash_read + */ + function read(length: number, addr: number): any; +} + +/** + * This module allows you to read and write part of the nonvolatile flash memory of + * your device using a filesystem-like API. + * Also see the `Flash` library, which provides a low level, more dangerous way to + * access all parts of your flash memory. + * The `Storage` library provides two distinct types of file: + * * `require("Storage").write(...)`/`require("Storage").read(...)`/etc create + * simple contiguous files of fixed length. This is the recommended file type. + * * `require("Storage").open(...)` creates a `StorageFile`, which stores the file + * in numbered chunks (`"filename\1"`/`"filename\2"`/etc). It allows data to be + * appended and for the file to be read line by line. + * You must read a file using the same method you used to write it - e.g. you can't + * create a file with `require("Storage").open(...)` and then read it with + * `require("Storage").read(...)`. + * **Note:** In firmware 2v05 and later, the maximum length for filenames is 28 + * characters. However in 2v04 and earlier the max length is 8. + * @url http://www.espruino.com/Reference#Storage + */ +declare module "Storage" { + /** + * Erase the flash storage area. This will remove all files created with + * `require("Storage").write(...)` as well as any code saved with `save()` or + * `E.setBootCode()`. + * @url http://www.espruino.com/Reference#l_Storage_eraseAll + */ + function eraseAll(): void; + + /** + * Erase a single file from the flash storage area. + * **Note:** This function should be used with normal files, and not `StorageFile`s + * created with `require("Storage").open(filename, ...)` + * + * @param {any} name - The filename - max 28 characters (case sensitive) + * @url http://www.espruino.com/Reference#l_Storage_erase + */ + function erase(name: string): void; + + /** + * Read a file from the flash storage area that has been written with + * `require("Storage").write(...)`. + * This function returns a memory-mapped String that points to the actual memory + * area in read-only memory, so it won't use up RAM. + * As such you can check if a file exists efficiently using + * `require("Storage").read(filename)!==undefined`. + * If you evaluate this string with `eval`, any functions contained in the String + * will keep their code stored in flash memory. + * **Note:** This function should be used with normal files, and not `StorageFile`s + * created with `require("Storage").open(filename, ...)` + * + * @param {any} name - The filename - max 28 characters (case sensitive) + * @param {number} [offset] - [optional] The offset in bytes to start from + * @param {number} [length] - [optional] The length to read in bytes (if <=0, the entire file is read) + * @returns {any} A string of data, or `undefined` if the file is not found + * @url http://www.espruino.com/Reference#l_Storage_read + */ + function read(name: string, offset?: number, length?: number): string | undefined; + + /** + * Read a file from the flash storage area that has been written with + * `require("Storage").write(...)`, and parse JSON in it into a JavaScript object. + * This is identical to `JSON.parse(require("Storage").read(...))`. It will throw + * an exception if the data in the file is not valid JSON. + * **Note:** This function should be used with normal files, and not `StorageFile`s + * created with `require("Storage").open(filename, ...)` + * + * @param {any} name - The filename - max 28 characters (case sensitive) + * @param {boolean} noExceptions - If true and the JSON is not valid, just return `undefined` - otherwise an `Exception` is thrown + * @returns {any} An object containing parsed JSON from the file, or undefined + * @url http://www.espruino.com/Reference#l_Storage_readJSON + */ + function readJSON(name: string, noExceptions: boolean): any; + + /** + * Read a file from the flash storage area that has been written with + * `require("Storage").write(...)`, and return the raw binary data as an + * ArrayBuffer. + * This can be used: + * * In a `DataView` with `new DataView(require("Storage").readArrayBuffer("x"))` + * * In a `Uint8Array/Float32Array/etc` with `new + * Uint8Array(require("Storage").readArrayBuffer("x"))` + * **Note:** This function should be used with normal files, and not `StorageFile`s + * created with `require("Storage").open(filename, ...)` + * + * @param {any} name - The filename - max 28 characters (case sensitive) + * @returns {any} An ArrayBuffer containing data from the file, or undefined + * @url http://www.espruino.com/Reference#l_Storage_readArrayBuffer + */ + function readArrayBuffer(name: string): ArrayBuffer | undefined; + + /** + * Write/create a file in the flash storage area. This is nonvolatile and will not + * disappear when the device resets or power is lost. + * Simply write `require("Storage").write("MyFile", "Some data")` to write a new + * file, and `require("Storage").read("MyFile")` to read it. + * If you supply: + * * A String, it will be written as-is + * * An array, will be written as a byte array (but read back as a String) + * * An object, it will automatically be converted to a JSON string before being + * written. + * **Note:** If an array is supplied it will not be converted to JSON. To be + * explicit about the conversion you can use `Storage.writeJSON` + * You may also create a file and then populate data later **as long as you don't + * try and overwrite data that already exists**. For instance: + * ``` + * var f = require("Storage"); + * f.write("a","Hello",0,14); + * f.write("a"," ",5); + * f.write("a","World!!!",6); + * print(f.read("a")); // "Hello World!!!" + * f.write("a"," ",0); // Writing to location 0 again will cause the file to be re-written + * print(f.read("a")); // " " + * ``` + * This can be useful if you've got more data to write than you have RAM + * available - for instance the Web IDE uses this method to write large files into + * onboard storage. + * **Note:** This function should be used with normal files, and not `StorageFile`s + * created with `require("Storage").open(filename, ...)` + * + * @param {any} name - The filename - max 28 characters (case sensitive) + * @param {any} data - The data to write + * @param {number} [offset] - [optional] The offset within the file to write + * @param {number} [size] - [optional] The size of the file (if a file is to be created that is bigger than the data) + * @returns {boolean} True on success, false on failure + * @url http://www.espruino.com/Reference#l_Storage_write + */ + function write(name: string | ArrayBuffer | ArrayBufferView | number[] | object, data: any, offset?: number, size?: number): boolean; + + /** + * Write/create a file in the flash storage area. This is nonvolatile and will not + * disappear when the device resets or power is lost. + * Simply write `require("Storage").writeJSON("MyFile", [1,2,3])` to write a new + * file, and `require("Storage").readJSON("MyFile")` to read it. + * This is equivalent to: `require("Storage").write(name, JSON.stringify(data))` + * **Note:** This function should be used with normal files, and not `StorageFile`s + * created with `require("Storage").open(filename, ...)` + * + * @param {any} name - The filename - max 28 characters (case sensitive) + * @param {any} data - The JSON data to write + * @returns {boolean} True on success, false on failure + * @url http://www.espruino.com/Reference#l_Storage_writeJSON + */ + function writeJSON(name: string, data: any): boolean; + + /** + * List all files in the flash storage area. An array of Strings is returned. + * By default this lists files created by `StorageFile` (`require("Storage").open`) + * which have a file number (`"\1"`/`"\2"`/etc) appended to them. + * ``` + * // All files + * require("Storage").list() + * // Files ending in '.js' + * require("Storage").list(/\.js$/) + * // All Storage Files + * require("Storage").list(undefined, {sf:true}) + * // All normal files (e.g. created with Storage.write) + * require("Storage").list(undefined, {sf:false}) + * ``` + * **Note:** This will output system files (e.g. saved code) as well as files that + * you may have written. + * + * @param {any} [regex] - [optional] If supplied, filenames are checked against this regular expression (with `String.match(regexp)`) to see if they match before being returned + * @param {any} [filter] - [optional] If supplied, File Types are filtered based on this: `{sf:true}` or `{sf:false}` for whether to show StorageFile + * @returns {any} An array of filenames + * @url http://www.espruino.com/Reference#l_Storage_list + */ + function list(regex?: RegExp, filter?: { sf: boolean }): string[]; + + /** + * List all files in the flash storage area matching the specified regex (ignores + * StorageFiles), and then hash their filenames *and* file locations. + * Identical files may have different hashes (e.g. if Storage is compacted and the + * file moves) but the changes of different files having the same hash are + * extremely small. + * ``` + * // Hash files + * require("Storage").hash() + * // Files ending in '.boot.js' + * require("Storage").hash(/\.boot\.js$/) + * ``` + * **Note:** This function is used by Bangle.js as a way to cache files. For + * instance the bootloader will add all `.boot.js` files together into a single + * `.boot0` file, but it needs to know quickly whether anything has changed. + * + * @param {any} [regex] - [optional] If supplied, filenames are checked against this regular expression (with `String.match(regexp)`) to see if they match before being hashed + * @returns {number} A hash of the files matching + * @url http://www.espruino.com/Reference#l_Storage_hash + */ + function hash(regex: RegExp): number; + + /** + * The Flash Storage system is journaling. To make the most of the limited write + * cycles of Flash memory, Espruino marks deleted/replaced files as garbage and + * moves on to a fresh part of flash memory. Espruino only fully erases those files + * when it is running low on flash, or when `compact` is called. + * `compact` may fail if there isn't enough RAM free on the stack to use as swap + * space, however in this case it will not lose data. + * **Note:** `compact` rearranges the contents of memory. If code is referencing + * that memory (e.g. functions that have their code stored in flash) then they may + * become garbled when compaction happens. To avoid this, call `eraseFiles` before + * uploading data that you intend to reference to ensure that uploaded files are + * right at the start of flash and cannot be compacted further. + * @url http://www.espruino.com/Reference#l_Storage_compact + */ + function compact(): void; + + /** + * This writes information about all blocks in flash memory to the console - and is + * only useful for debugging flash storage. + * @url http://www.espruino.com/Reference#l_Storage_debug + */ + function debug(): void; + + /** + * Return the amount of free bytes available in Storage. Due to fragmentation there + * may be more bytes available, but this represents the maximum size of file that + * can be written. + * @returns {number} The amount of free bytes + * @url http://www.espruino.com/Reference#l_Storage_getFree + */ + function getFree(): number; + + /** + * Returns: + * ``` + * { + * totalBytes // Amount of bytes in filesystem + * freeBytes // How many bytes are left at the end of storage? + * fileBytes // How many bytes of allocated files do we have? + * fileCount // How many allocated files do we have? + * trashBytes // How many bytes of trash files do we have? + * trashCount // How many trash files do we have? + * } + * ``` + * @returns {any} An object containing info about the current Storage system + * @url http://www.espruino.com/Reference#l_Storage_getStats + */ + function getStats(): any; + + /** + * Writes a lookup table for files into Bangle.js's storage. This allows any file + * stored up to that point to be accessed quickly. + * @url http://www.espruino.com/Reference#l_Storage_optimise + */ + function optimise(): void; + + /** + * Open a file in the Storage area. This can be used for appending data + * (normal read/write operations only write the entire file). + * Please see `StorageFile` for more information (and examples). + * **Note:** These files write through immediately - they do not need closing. + * + * @param {any} name - The filename - max **27** characters (case sensitive) + * @param {any} mode - The open mode - must be either `'r'` for read,`'w'` for write , or `'a'` for append + * @returns {any} An object containing {read,write,erase} + * @url http://www.espruino.com/Reference#l_Storage_open + */ + function open(name: string, mode: "r" | "w" | "a"): StorageFile; +} \ No newline at end of file