Debian Codegraph @

online/static/blocks/allApis.js

raw symbols SCIP
1 var audioReadyCallback = ()=>{};
2
3 var startRecord = function(callback){
4 audioReadyCallback = callback;
5 if(typeof JSBridge != 'undefined'){
6 if(!JSBridge.isAudioAvailable()){
7 console.log('record permission not granted. wait.');
8 JSBridge.getAudioPermission();
9 return;
10 }
11 }
12 audioReadyCallback();
13 }
14
15
16
17 var storageReadyCallback = ()=>{};
18
19 var startStorage = function(callback){
20 storageReadyCallback = callback;
21 if(typeof JSBridge != 'undefined'){
22 if(!JSBridge.isStorageAvailable()){
23 console.log('storage permission not granted. wait.');
24 JSBridge.getStoragePermission();
25 return;
26 }
27 }
28 storageReadyCallback();
29 }
30
31 //Kuttypy.js
32
33 var textElements={};
34 var txt;
35 // ----------DOM MANIPULATION
36 const SVG_NS = "http://www.w3.org/2000/svg";
37 // an object to define the properties and text content of the text element
38
39 // a function to create a text element
40 function drawText(parent, props, textcontent) {
41 // create a new text element
42 let text = document.createElementNS(SVG_NS, "text");
43 //set the attributes for the text
44 for (var name in props) {
45 if (props.hasOwnProperty(name)) {
46 text.setAttributeNS(null, name, props[name]);
47 }
48 }
49 text.textContent = textcontent;
50 parent.appendChild(text);
51 return text;
52 }
53
54 // FLOT
55
56
57 var colors = ['red','orange','yellow','olive','green','teal','blue','violet','purple','pink','brown','grey','black'];
58 var recentcolor=0;
59
60 var mydata = {};
61 var startTime = new Date();
62 var activePlot=null;
63 var myplots = {}
64 var options = {}
65 var plotdatastack = {};
66
67 var clearPlot = function(){
68 plotdatastack = {};
69 resultplots.empty();
70 myplots = {};
71 options = {};
72 }
73
74 function createPlots(latestCode){
75 mydata = {}; startTime = new Date();
76 if(latestCode.indexOf('plot_radar(')>=0)
77 addPolarPlot();
78 }
79
80
81 var polarPositions = [];
82
83 var addPolarPlot = function(){
84 polarPositions = [];
85
86 resultplots.append(`
87 <div id="polarplot" style="min-width:300px;width:100%;height:100%;position:relative;">
88 <!-- Grey circle -->
89 <svg viewBox="0 0 200 200" class="circle" style="position:absolute;">
90 <circle cx="100" cy="100" r="100" fill="#9cb" />
91 </svg>
92
93 <!-- Pie -->
94 <svg class="polar" viewBox="-1 -1 2 2" style="transform: rotate(-90deg);position: absolute;">
95 </svg>
96
97 <!-- Slice borders -->
98 <svg viewBox="0 0 200 200" style="transform: rotate(0deg);position:absolute;" xmlns="http://www.w3.org/2000/svg">
99 <line x1="0" y1="300" x2="0" y2="0" stroke-width="1" stroke="#ffffff33" transform="translate(100, 0)">
100 </svg>
101
102 <svg viewBox="0 0 200 200" style="transform: rotate(60deg);position:absolute;" xmlns="http://www.w3.org/2000/svg">
103 <line x1="0" y1="300" x2="0" y2="0" stroke-width="1" stroke="#ffffff33" transform="translate(100, 0)">
104 </svg>
105
106 <svg viewBox="0 0 200 200" style="transform: rotate(-60deg);position:absolute;" xmlns="http://www.w3.org/2000/svg">
107 <line x1="0" y1="300" x2="0" y2="0" stroke-width="1" stroke="#ffffff33" transform="translate(100, 0)">
108 </svg>
109
110 <svg viewBox="0 0 200 200" style="transform: rotate(30deg);position:absolute;" xmlns="http://www.w3.org/2000/svg">
111 <line x1="0" y1="300" x2="0" y2="0" stroke-width="1" stroke="#ffffff33" transform="translate(100, 0)">
112 </svg>
113
114 <svg viewBox="0 0 200 200" style="transform: rotate(-30deg);position:absolute;" xmlns="http://www.w3.org/2000/svg">
115 <line x1="0" y1="300" x2="0" y2="0" stroke-width="1" stroke="#ffffff33" transform="translate(100, 0)">
116 </svg>
117
118 <svg viewBox="0 0 200 200" style="transform: rotate(90deg);position:absolute;" xmlns="http://www.w3.org/2000/svg">
119 <line x1="0" y1="300" x2="0" y2="0" stroke-width="1" stroke="#ffffff33" transform="translate(100, 0)">
120 </svg>
121
122
123 <!-- Concentric circles -->
124 <svg viewBox="0 0 200 200" class="polar circle" style="position:absolute;">
125 <circle cx="100" cy="100" r="100" fill="none" stroke="white" stroke-width="1" stroke-opacity=".5" />
126 <circle cx="100" cy="100" r="80" fill="none" stroke="white" stroke-width="1" stroke-opacity=".5"/>
127 <circle cx="100" cy="100" r="60" fill="none" stroke="white" stroke-width="1" stroke-opacity=".5"/>
128 <circle cx="100" cy="100" r="40" fill="none" stroke="white" stroke-width="1" stroke-opacity=".5"/>
129 <circle cx="100" cy="100" r="20" fill="none" stroke="white" stroke-width="1" stroke-opacity=".5"/>
130 </svg>
131
132
133 </div>
134 `);
135
136
137
138 plt = document.querySelector('.polar.circle');
139
140 for(var i=0;i<361;i++){
141 dot = document.createElementNS("http://www.w3.org/2000/svg", "circle");
142 dot.setAttribute('cx',100);
143 dot.setAttribute('cy',100);
144 dot.setAttribute('r',2);
145 dot.setAttribute('stroke','lightgreen');
146 dot.setAttribute('fill','green');
147 polarPositions.push(dot);
148 plt.appendChild(dot);
149 }
150
151 }
152
153 var makePlotIfUnavailable = function(plotname){
154 if(!(plotname in myplots)){
155 mydata[plotname] = [];
156 var w = resultplots.width()<300?300:resultplots.width();
157 var h = resultplots.height()<300 ? 300:resultplots.height();
158 if(h>400)h=400;
159 startTime = new Date();
160 resultplots.append($('<span style="color:red" onclick="savePlotData(\''+plotname+'\');">'+plotname+' [Touch to Save Data]</span><hr color="red">'));
161 resultplots.append($('<div id="cs_'+plotname+'">').width(w).height(h));
162 myplots[plotname] = 0;
163 options[plotname] = {
164 series: {
165 lines: {
166 show: true,
167 lineWidth: 2
168 },
169 points: {
170 radius: 2,
171 show: true,
172 symbol: "cross"
173 }
174 },
175 xaxis: {
176 gridLines: true,
177 autoScaleMargin : 0.1,
178 autoScale: 'exact',
179 growOnly : true
180 },
181 yaxis: {
182 gridLines: true,
183 autoScaleMargin : 0.1,
184 autoScale: 'exact',
185 growOnly : true
186 },
187
188 legend: {
189 show: true,
190 noColumns: 1,
191 labelFormatter: null, // fn: string -> string
192 container: null, // container (as jQuery object) to put legend in, null means default on top of graph
193 position: 'ne', // position of default legend container within plot
194 margin: 5, // distance from grid edge to default legend container within plot
195 sorted: null // default to no legend sorting
196 }
197 };
198
199 }
200 }
201
202
203 var addDataPoint = function(plotname, x){
204 makePlotIfUnavailable(plotname);
205 if(myplots[plotname]==0){
206 startTime = new Date();
207 mydata[plotname].push([0,x]);
208 }else{
209 mydata[plotname].push([(new Date() - startTime)/1000.,x]);
210 }
211 myplots[plotname] ++;
212 //if(myplots[plotname]>20)options[plotname].series.points.show = false;
213 //else options[plotname].series.points.show = true;
214 options[plotname].series.lines.show = false;
215
216 options[plotname].xaxes = [{ position: 'bottom', axisLabel: 'Time (S)', show: true }];
217 $.plot("#cs_"+plotname, [{color: "red", lines: {show: true, lineWidth: 2}, data: mydata[plotname], label: "Y data"}], options[plotname]);
218 }
219
220
221 var addDataPoints = function(plotname, x){ // X is an Array of points
222 x = myInterpreter.pseudoToNative(x); // Convert to native array
223 makePlotIfUnavailable(plotname);
224 var t=0;
225 if(myplots[plotname]==0){
226 startTime = new Date();
227 for(var i=0;i<x.length;i++){
228 mydata[plotname].push({ lines: {show: true, lineWidth: 1}, data: [] ,label:'Y'+(i+1) } ); //, label: params[i]
229 }
230 }else{
231 t = (new Date() - startTime)/1000.;
232 }
233 // Push points in
234 try{
235 for(var i=0;i<x.length;i++){
236 mydata[plotname][i].data.push([t,x[i]]);
237 if(myplots[plotname]==20)mydata[plotname][i].points = {show:false};
238 }
239
240 myplots[plotname] ++;
241 //if(myplots[plotname]>20)options[plotname].series.points.show = false;
242 //else options[plotname].series.points.show = true;
243 options[plotname].series.lines.show = false;
244
245 options[plotname].xaxes = [{ position: 'bottom', axisLabel: 'Time (S)', show: true }];
246 $.plot("#cs_"+plotname, mydata[plotname], options[plotname]);
247 }catch(e){
248 console.log('Plot Err:'+e);
249 }
250 }
251
252
253 var addDataPointXY = function(plotname, x,y){
254 makePlotIfUnavailable(plotname);
255 mydata[plotname].push([x,y]);
256 myplots[plotname] ++;
257 //if(myplots[plotname]>200)options[plotname].series.points.show = false;
258 //else options[plotname].series.points.show = true;
259 options[plotname].series.lines.show = false;
260 $.plot("#cs_"+plotname, [ mydata[plotname] ], options[plotname]);
261 }
262
263
264 var plotArraysXYStack = function(plotname,X,Y, state){
265 makePlotIfUnavailable(plotname);
266 options[plotname].series.points.show = false;
267 if(!(plotname in plotdatastack))plotdatastack[plotname] = [];
268
269 if(state)plotdatastack[plotname] = [ {color: colors[plotdatastack[plotname].length % colors.length], lines: {show: true, lineWidth: 2}, data: [], label: "Chan "+plotdatastack[plotname].length} ];
270 else plotdatastack[plotname].push( {color: colors[plotdatastack[plotname].length % colors.length], lines: {show: true, lineWidth: 2}, data: [], label: "Chan "+plotdatastack[plotname].length} );
271
272 nx = myInterpreter.pseudoToNative(X); // Convert to native array
273 ny = myInterpreter.pseudoToNative(Y); // Convert to native array
274 //nx = Object.values(X.a)
275 //ny = Object.values(Y.a)
276 dat = plotdatastack[plotname][plotdatastack[plotname].length - 1];
277 for (i=0;i<nx.length;i++){
278 dat.data.push([nx[i],ny[i]]);
279 }
280
281 $.plot("#cs_"+plotname, plotdatastack[plotname], options[plotname]);
282
283 }
284
285 var plotArraysXY = function(plotname,X,Y){
286 makePlotIfUnavailable(plotname);
287 options[plotname].series.points.show = false;
288 mydata[plotname] = [
289 {color: "red", lines: {show: true, lineWidth: 2}, data: [], label: "Chan 1"},
290 ];
291 nx = Object.values(X.a)
292 ny = Object.values(Y.a)
293 for (i=0;i<nx.length;i++){
294 mydata[plotname][0].data.push([nx[i],ny[i]]);
295 }
296
297 $.plot("#cs_"+plotname, mydata[plotname], options[plotname]);
298
299 }
300
301
302 var plotArraysXYY = function(plotname, X,Y1, Y2){
303 makePlotIfUnavailable(plotname);
304 options[plotname].series.points.show = false;
305 mydata[plotname] = [
306 {color: "red", lines: {show: true, lineWidth: 2}, data: [], label: "Chan 1"},
307 {color: "blue", lines: {show: true, lineWidth: 2}, data: [], label: "Chan 2"},
308 ];
309
310 nx = Object.values(X.a)
311 ny1 = Object.values(Y1.a)
312 ny2 = Object.values(Y2.a)
313 for (i=0;i<nx.length;i++){
314 mydata[plotname][0].data.push([nx[i],ny1[i]]);
315 mydata[plotname][1].data.push([nx[i],ny2[i]]);
316 }
317
318 $.plot("#cs_"+plotname, mydata[plotname] , options[plotname]);
319
320 }
321
322 var plotArraysXYYY = function(plotname, X,Y1, Y2, Y3){
323 makePlotIfUnavailable(plotname);
324 options[plotname].series.points.show = false;
325 mydata[plotname] = [
326 {color: "red", lines: {show: true, lineWidth: 2}, data: [], label: "Chan 1"},
327 {color: "blue", lines: {show: true, lineWidth: 2}, data: [], label: "Chan 2"},
328 {color: "forestgreen", lines: {show: true, lineWidth: 2}, data: [], label: "Chan 3"},
329 ];
330
331 nx = Object.values(X.a)
332 ny1 = Object.values(Y1.a)
333 ny2 = Object.values(Y2.a)
334 ny3 = Object.values(Y3.a)
335 for (i=0;i<nx.length;i++){
336 mydata[plotname][0].data.push([nx[i],ny1[i]]);
337 mydata[plotname][1].data.push([nx[i],ny2[i]]);
338 mydata[plotname][2].data.push([nx[i],ny3[i]]);
339 }
340
341 $.plot("#cs_"+plotname, mydata[plotname] , options[plotname]);
342
343 }
344
345 var savePlotData = function(plotname){
346 if(mydata[plotname].length == 0)return;
347 if(mydata[plotname][0].constructor == Array){
348 x=[];
349 y=[];
350 for (var i=0;i<mydata[plotname].length;i++){
351 x.push(parseFloat(mydata[plotname][i][0]));
352 y.push(parseFloat(mydata[plotname][i][1]));
353 }
354 JSBridge.save_lists(plotname+".csv",JSON.stringify(x),JSON.stringify(y),"[]","[]");
355 alert("Saved to KuttyPy directory :"+plotname+".csv");
356
357 }
358 else if(mydata[plotname][0].constructor == Object){ // plot_xyyarray, xyyyarray etc store dicts.
359 msg = ''
360 for (var dset=0;dset<mydata[plotname].length;dset++){
361 x=[];
362 y=[];
363 for (var i=0;i<mydata[plotname][dset].data.length;i++){
364 x.push(parseFloat(mydata[plotname][dset].data[i][0]));
365 y.push(parseFloat(mydata[plotname][dset].data[i][1]));
366 }
367 JSBridge.save_lists(plotname+'_'+dset+'.csv',JSON.stringify(x),JSON.stringify(y),"[]","[]");
368 msg+=plotname+'_'+dset+'.csv ,';
369 }
370 alert("Saved to KuttyPy directory :"+msg);
371 }
372
373
374 }
375
376 var addDataPointPolar = function(angle, radius, maxrad){
377 angle = angle%360;
378 x = 100+100*radius*Math.cos(3.1415*angle/180)/maxrad;
379 y = 100-100*radius*Math.sin(3.1415*angle/180)/maxrad;
380 polarPositions[Math.round(angle)].setAttribute('cx',x)
381 polarPositions[Math.round(angle)].setAttribute('cy',y)
382
383 }
384
385
386 // GAME
387
388
389
390 /* --- Credit https://raw.githubusercontent.com/danba340/tiny-flappy-bird/master/index.html --*/
391
392 var birdX = score = bestScore = 0;
393 var birdSize = pipeWidth = topPipeBottomY = 24;
394 var interval = 40;
395 var birdY = pipeGap = 200;
396 var intervalID;
397
398 var context;
399 const bird = new Image();
400
401 var blit = function() {
402 context.fillStyle = "skyblue";
403 context.fillRect(0,0,canvasSize,canvasSize); // Draw sky
404 context.drawImage(bird, birdX, birdY, birdSize * (524/374), birdSize); // Draw bird
405 context.fillStyle = "green";
406 context.fillRect(pipeX, 0, pipeWidth, topPipeBottomY); // Draw top pipe
407 context.fillRect(pipeX, topPipeBottomY + pipeGap, pipeWidth, canvasSize); // Draw bottom pipe
408 context.fillStyle = "blue";
409 context.fillText(score++, 9, 25); // Increase and draw score
410 context.fillText(`Best: ${bestScore}`, 9, 50); // Draw best score
411 }
412
413 var updateBird = function() {
414 blit();
415 pipeX -= 4; // Move pipe
416 pipeX < -pipeWidth && // Pipe off screen?
417 ((pipeX = canvasSize), (topPipeBottomY = pipeGap * Math.random())); // Reset pipe and randomize gap.
418 bestScore = bestScore < score ? score : bestScore; // New best score?
419 if(((birdY < topPipeBottomY || birdY > topPipeBottomY + pipeGap) && pipeX < birdSize * (524/374)) ){// bird hit the pipe
420 context.fillStyle = "red";
421 context.fillRect(0,0,canvasSize,canvasSize); // Draw RED sky
422 birdY = 200;
423 pipeX = canvasSize;
424 score = 0; // Bird died
425 }
426 }
427
428 var addGame = function(){
429 canvasSize = pipeX = resultplots.width()<400?400:resultplots.width();
430 resplotarea.show();
431 resultplots.append(
432 `
433 <div style="height: 400px; background: #111; text-align: center;touch-action: manipulation;">
434 <canvas id="c" width="$(pipeX)" height="400"></canvas>
435 </div>
436 `
437 );
438 context = c.getContext("2d");
439
440
441 bird.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAOCAYAAADABlfOAAAA/0lEQVQ4y72TQWrDMBBF38gCqwtvC120YOgFegL3DrlFeppSanqc5iAlPUCgCy+kQOLJJkrkWE4TKBXMRuK/+fojwX8t773b1wzQXHnvn6b0ktt0ggIEe0v9+jU4W84rVBURIYRgnHN6qrcZpt69dxRs2J4cRyAQwX3OnElh+2I5r36NSERQ1dhEc041OkhFFCX12+rqmcgUNIXXbZeNYGAgicBe66JuuwgZzSKC7bGZDNwerp+4jE77RZltaJq1AqOWB+pj+5Odfr8oMc36bJx2KuOc4v4jYJoK/RynJs+b848foEjAD0kEaizfLzdjwfbIkwvno5f8xNzj/7O1A51fZ+BxD7C5AAAAAElFTkSuQmCC";
442
443
444 //c.onclick = () => (birdDY = 9) ;
445
446
447 intervalID = setInterval(updateBird, interval)
448
449
450 }
451
452
453 function setBirdY(val){ // 0-1000. scaled to 0-400
454 birdY = 400 - val/2.5;
455 blit();
456 }
457
458 function stopGame(){
459 if(intervalID != null)clearInterval(intervalID);
460 }
461
462 // PIANO
463
464
465
466 var note, hints;
467 var audios = {};
468 var mykeys = {};
469
470
471
472 var addPiano = function(){
473
474 registers.append(`
475 <section id="main" style="width:400px;">
476 <div class="nowplaying"></div>
477 <div class="keys">
478 <div class="key" data-note="C">
479 <span class="hints">C</span>
480 </div>
481 <div class="key sharp" data-note="C#">
482 <span class="hints">C#</span>
483 </div>
484 <div class="key" data-note="D">
485 <span class="hints">D</span>
486 </div>
487 <div class="key sharp" data-note="D#">
488 <span class="hints">D#</span>
489 </div>
490 <div class="key" data-note="E">
491 <span class="hints">E</span>
492 </div>
493 <div class="key" data-note="F">
494 <span class="hints">F</span>
495 </div>
496 <div class="key sharp" data-note="F#">
497 <span class="hints">F#</span>
498 </div>
499 <div class="key" data-note="G">
500 <span class="hints">G</span>
501 </div>
502 <div class="key sharp" data-note="G#">
503 <span class="hints">G#</span>
504 </div>
505 <div class="key" data-note="A">
506 <span class="hints">A</span>
507 </div>
508 <div class="key sharp" data-note="A#">
509 <span class="hints">A#</span>
510 </div>
511 <div class="key" data-note="B">
512 <span class="hints">B</span>
513 </div>
514 <div class="key" data-note="2C">
515 <span class="hints">2C</span>
516 </div>
517 <div class="key sharp" data-note="2C#">
518 <span class="hints">2C#</span>
519 </div>
520 <div class="key" data-note="2D">
521 <span class="hints">2D</span>
522 </div>
523 <div class="key sharp" data-note="2D#">
524 <span class="hints">2D#</span>
525 </div>
526 <div class="key" data-note="2E">
527 <span class="hints">2E</span>
528 </div>
529 </div>
530
531 <audio data-note="C" src="sounds/040.wav"></audio>
532 <audio data-note="C#" src="sounds/041.wav"></audio>
533 <audio data-note="D" src="sounds/042.wav"></audio>
534 <audio data-note="D#" src="sounds/043.wav"></audio>
535 <audio data-note="E" src="sounds/044.wav"></audio>
536 <audio data-note="F" src="sounds/045.wav"></audio>
537 <audio data-note="F#" src="sounds/046.wav"></audio>
538 <audio data-note="G" src="sounds/047.wav"></audio>
539 <audio data-note="G#" src="sounds/048.wav"></audio>
540 <audio data-note="A" src="sounds/049.wav"></audio>
541 <audio data-note="A#" src="sounds/050.wav"></audio>
542 <audio data-note="B" src="sounds/051.wav"></audio>
543 <audio data-note="2C" src="sounds/052.wav"></audio>
544 <audio data-note="2C#" src="sounds/053.wav"></audio>
545 <audio data-note="2D" src="sounds/054.wav"></audio>
546 <audio data-note="2D#" src="sounds/055.wav"></audio>
547 <audio data-note="2E" src="sounds/056.wav"></audio>
548 </section>
549 `);
550
551 const keys = document.querySelectorAll(".key");
552 note = document.querySelector(".nowplaying");
553
554 keys.forEach(key => key.addEventListener("transitionend", removeTransition));
555 keys.forEach(key => key.addEventListener("touchstart", clicked));
556 for(const x of ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B','2C','2C#','2D','2D#','2E' ]){
557 audios[x] = document.querySelector(`audio[data-note="${x}"]`);
558 mykeys[x] = document.querySelector(`.key[data-note="${x}"]`);
559 }
560
561 }
562
563
564 function clicked(e) {
565 playPiano(this.getAttribute("data-note"));
566 }
567
568
569 function playPiano(notename) {
570 const audio = audios[notename]; // document.querySelector(`audio[data-note="${notename}"]`),
571 key = mykeys[notename];//document.querySelector(`.key[data-note="${notename}"]`);
572 if (!key) return;
573 key.classList.add("playing");
574 note.innerHTML = notename;
575 audio.currentTime = 0;
576 audio.play();
577 }
578
579
580 function removeTransition(e) {
581 if (e.propertyName !== "transform") return;
582 this.classList.remove("playing");
583 }
584
585
586 var gauges = [];
587
588
589
590 function addGauge(id){
591 gaugearea.append(`
592 <div class="item">
593 <div id="${id}" class="gauge" style="
594 --gauge-bg: #088478;
595 --gauge-value:0;
596 --gauge-display-value:0;">
597
598 <div class="ticks">
599 <div class="tithe" style="--gauge-tithe-tick:1;"></div>
600 <div class="tithe" style="--gauge-tithe-tick:2;"></div>
601 <div class="tithe" style="--gauge-tithe-tick:3;"></div>
602 <div class="tithe" style="--gauge-tithe-tick:4;"></div>
603 <div class="tithe" style="--gauge-tithe-tick:6;"></div>
604 <div class="tithe" style="--gauge-tithe-tick:7;"></div>
605 <div class="tithe" style="--gauge-tithe-tick:8;"></div>
606 <div class="tithe" style="--gauge-tithe-tick:9;"></div>
607 <div class="min"></div>
608 <div class="mid"></div>
609 <div class="max"></div>
610 </div>
611 <div class="tick-circle"></div>
612
613 <div class="needle">
614 <div class="needle-head"></div>
615 </div>
616 <div class="labels">
617 <div class="value-label"></div>
618 </div>
619 </div>
620 </div>`);
621 return true;
622 }
623 // Gauge
624 function updateGauge(id, value, min, max) {
625 const newGaugeValue = Math.floor(((value - min) / (max - min)) * 100);
626 document.getElementById(id).style.setProperty('--gauge-display-value', Math.floor(value));
627 document.getElementById(id).style.setProperty('--gauge-value', newGaugeValue);
628 }
629
630
631 function savePNG(){
632 var scaleFactor = 1;
633 //Any modifications are executed on a deep copy of the element
634 var cp = Blockly.mainWorkspace.svgBlockCanvas_.cloneNode(true);
635 cp.removeAttribute("width");
636 cp.removeAttribute("height");
637 cp.removeAttribute("transform");
638
639 var styleElem = document.createElementNS("http://www.w3.org/2000/svg", "style");
640 //I've manually pasted codethemicrobit.com's CSS for blocks in here, but that can be removed as necessary
641 styleElem.textContent = ".blocklyToolboxDiv {background: rgba(0, 0, 0, 0.05);}.blocklyMainBackground {stroke:none !important;}.blocklyTreeLabel, .blocklyText, .blocklyHtmlInput {font-family:'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace !important;}.blocklyText { font-size:1rem !important;}.rtl .blocklyText {text-align:right;} .blocklyTreeLabel { font-size:1.25rem !important;} .blocklyCheckbox {fill: #ff3030 !important;text-shadow: 0px 0px 6px #f00;font-size: 17pt !important;}";
642 cp.insertBefore(styleElem, cp.firstChild);
643
644 //Creates a complete SVG document with the correct bounds (it is necessary to get the viewbox right, in the case of negative offsets)
645 var bbox = Blockly.mainWorkspace.svgBlockCanvas_.getBBox();
646 var xml = new XMLSerializer().serializeToString(cp);
647 xml = '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="'+bbox.width+'" height="'+bbox.height+'" viewBox="' + bbox.x + ' ' + bbox.y + ' ' + bbox.width + ' ' + bbox.height + '"><rect width="100%" height="100%" fill="white"></rect>'+xml+'</svg>';
648 //If you just want the SVG then do console.log(xml)
649 //Otherwise we render as an image and export to PNG
650 var svgBase64 = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(xml)));
651 var img = document.createElement('img');
652 img.src = svgBase64;
653
654 var canvas = document.createElement("canvas");
655 canvas.width = Math.ceil(bbox.width) * scaleFactor;
656 canvas.height = Math.ceil(bbox.height) * scaleFactor;
657 var ctx = canvas.getContext('2d');
658 ctx.scale(scaleFactor, scaleFactor);
659
660 ctx.drawImage(img, 0, 0);
661 //Opens the PNG image in a new tab for copying/saving
662 window.open(canvas.toDataURL(), '_blank');
663 }
664
665
666 // SENSORS
667
668 var I2CSelectionCallback;
669 function getSensorSelection(callback){
670 I2CSelectionCallback = callback;
671 var sensors = JSON.parse(HWBridge.scanI2C());
672 if(sensors.length>0){
673 var senslist = $('<div class="ui mini teal buttons i2clist"></div>');
674 sensors.forEach((s, i) => {
675 if(i>0) senslist.append('<div class="or"></div>');
676 if(s.search('/') != -1){ // 2 sensor options. more than that unsupported.
677 addr = s.split(']')[0].substring(1);
678 sensor1 = s.split(']')[1].split('/')[0];
679 sensor2 = s.split(']')[1].split('/')[1];
680 senslist.append(`<button class="ui button" onclick="var t = this.textContent; this.parentElement.remove(); I2CSelectionCallback(t);">[${addr}]${sensor1}</button>`);
681 senslist.append('<div class="or"></div>');
682 senslist.append(`<button class="ui button" onclick="var t = this.textContent; this.parentElement.remove(); I2CSelectionCallback(t);">[${addr}]${sensor2}</button>`);
683 }else{ // only one sensor
684 senslist.append(`<a class="ui button" onclick="var t = this.textContent; this.parentElement.remove(); I2CSelectionCallback(t);">${s}</a>`);
685 }
686
687
688 } );
689 results.append(senslist);
690 }else{
691 results.append('<span>No sensors found. default to voltmeter</span>');
692 callback('[0]ADCSENS'); // default to voltmeter
693 }
694 }
695
696 function getSensorList(){
697 fetch(`/get_reg/${channel}`)
698 .then(response => response.json())
699 .then(data => {
700 console.log('got following sensors',data);
701 allsensors = JSON.parse(data.sensors);
702 })
703 .catch(error => {
704 console.error('Error fetching sensors:', error);
705 });
706
707
708
709 }
710
711
712 //-------------------- API ------------------------
713
714 //ddone
715 function initApi(interpreter, scope) {
716 /*Patch it
717 * // Desperate attempt at infiltrating the sandbox. Didn't work
718 patchInterpreter(Interpreter);
719 InterfaceDictionary={'get_voltage':'JSBridge.get_voltage'};
720 interpreter.setProperty(scope, 'JSBridge', interpreter.createConnectedObject(JSBridge), interpreter.READONLY_DESCRIPTOR);
721 //interpreter.setProperty(scope,'JSBridge', JSBridge);
722 */
723
724
725 // Add an API for the wait block.
726 interpreter.setProperty(scope, 'waitForSeconds', interpreter.createAsyncFunction(
727 function(timeInSeconds, callback) {
728 // Delay the call to the callback.
729 setTimeout(callback, timeInSeconds * 1000);
730 }));
731 interpreter.setProperty(scope, 'sleep', interpreter.createAsyncFunction(
732 function(timeInSeconds, callback) {
733 // Delay the call to the callback.
734 setTimeout(callback, timeInSeconds * 1000);
735 }));
736
737 // Add an API function for highlighting blocks.
738 var wrapper = function(id) {
739 id = id ? id.toString() : '';
740 return interpreter.createPrimitive(highlightBlock(id));
741 };
742 interpreter.setProperty(scope, 'highlightBlock',
743 interpreter.createNativeFunction(wrapper));
744
745
746 // Add an API for the console.log call
747 interpreter.setProperty(scope, 'log', interpreter.createNativeFunction(
748 function( value) {
749 return console.log(value);
750 })
751 );
752
753 // Add an API for the JSON.parse call
754 interpreter.setProperty(scope, 'myparse', interpreter.createNativeFunction(
755 function( value) {
756 return JSON.parse(value);
757 })
758 );
759
760
761
762 // Add APIs for the average analysis calls. pass entire data to native java for processing.
763 interpreter.setProperty(scope, 'average', interpreter.createNativeFunction(
764 function(xin) {
765 x = myInterpreter.pseudoToNative(xin);
766 return x.reduce((a, b) => parseInt(a) + parseInt(b), 0) / x.length || 0;
767 })
768 );
769 interpreter.setProperty(scope, 'sum', interpreter.createNativeFunction(
770 function(xin) {
771 x = myInterpreter.pseudoToNative(xin);
772 return x.reduce((a, b) => parseInt(a) + parseInt(b), 0) ;
773 })
774 );
775 // Add APIs for the program starting block.
776 interpreter.setProperty(scope, 'programStarting', interpreter.createAsyncFunction(
777 function(callback) {
778 callback();
779 })
780 );
781
782 // Add APIs for the sine fit analysis calls. pass entire data to native java for processing.
783 interpreter.setProperty(scope, 'sine_fit_arrays', interpreter.createAsyncFunction(
784 async function(x,y,param, callback) {
785 val = await JSBridge.sine_fit_arrays(JSON.stringify(Object.values(x.a)),JSON.stringify(Object.values(y.a)),param);
786 callback( val.toFixed(3) );
787 })
788 );
789 interpreter.setProperty(scope, 'sine_fit_two_arrays', interpreter.createAsyncFunction(
790 async function(x,y,x2,y2,param,callback) {
791 val = await JSBridge.sine_fit_two_arrays(JSON.stringify(Object.values(x.a)),JSON.stringify(Object.values(y.a)),JSON.stringify(Object.values(x2.a)),JSON.stringify(Object.values(y2.a)),param);
792 callback(val.toFixed(3));
793 })
794 );
795 // Add an API for the FFT block. copied from wait_block. Async attempt
796 interpreter.setProperty(scope, 'fourier_transform', interpreter.createAsyncFunction(
797 function fourier_transform(x,y,callback) {
798 JSBridge.fourier_transform(JSON.stringify(Object.values(x.a)),JSON.stringify(Object.values(y.a)),callback);
799 })
800 );
801
802
803 // File writing calls
804 // Add an API for the writeToFile call
805 interpreter.setProperty(scope, 'write_to_file', interpreter.createAsyncFunction(
806 function(fname, txt, newline,callback) {
807 if(newline){txt+='\n';}
808 return JSBridge.writeToFile(fname,txt,callback);
809 })
810 );
811
812 interpreter.setProperty(scope, 'fileopen', interpreter.createAsyncFunction(
813 function(fname, callback) {
814 return JSBridge.fileopen(fname,callback);
815 })
816 );
817
818
819
820
821
822 }
823
824 //done
825 function initKuttyPy(interpreter, scope) {
826
827 // kuttypy API CALLS
828 interpreter.setProperty(scope, 'get_voltage', interpreter.createAsyncFunction(
829 function(channel, callback) {
830 fetch(`/get_voltage/${channel}`)
831 .then(response => response.json())
832 .then(data => {
833 callback(data.voltage);
834 })
835 .catch(error => {
836 console.error('Error fetching voltage:', error);
837 callback(0);
838 });
839 }
840 ));
841
842
843 var getRegWrapper = interpreter.createAsyncFunction(function(channel, callback) {
844 fetch(`/get_reg/${channel}`)
845 .then(response => response.json())
846 .then(data => {
847 showReg(channel,data.data);
848 callback(data.data); // Pass the register value to Blockly
849 })
850 .catch(error => {
851 showReg(channel,'err');
852 console.error('Error fetching register value:', error);
853 callback(0); // Return 0 if there's an error
854 });
855 });
856
857 interpreter.setProperty(scope, 'get_reg', getRegWrapper);
858 interpreter.setProperty(scope, 'getReg', getRegWrapper);
859
860 var setRegWrapper = interpreter.createAsyncFunction(function(channel, value, callback) {
861 fetch('/set_reg', {
862 method: 'POST',
863 headers: {
864 'Content-Type': 'application/json'
865 },
866 body: JSON.stringify({
867 reg: channel,
868 data: value
869 })
870 })
871 .then(response => response.json())
872 .then(data => {
873 showReg(channel,value);
874 callback(); // Just call the callback once the register is set
875 })
876 .catch(error => {
877 showReg(channel,'err');
878 console.error('Error setting register value:', error);
879 callback();
880 });
881 });
882
883 interpreter.setProperty(scope, 'set_reg', setRegWrapper);
884 interpreter.setProperty(scope, 'setReg', setRegWrapper);
885
886
887 // Add an API for stepper
888 var wrapper = interpreter.createAsyncFunction(
889 function(motor, callback) {
890 stepper_pos[motor] += 1;
891 cursteppos[motor] += 1;
892 if (cursteppos[motor] > 3) cursteppos[motor] = 0;
893
894 fetch('/set_reg', {
895 method: 'POST',
896 headers: {
897 'Content-Type': 'application/json'
898 },
899 body: JSON.stringify({
900 reg: 'PORTB',
901 data: step_positions[0][cursteppos[0]] + step_positions[1][cursteppos[1]]
902 })
903 })
904 .then(response => response.json())
905 .then(data => {
906 for (var i = 0; i < set_stepper_pos[motor].length; i++) {
907 set_stepper_pos[motor][i].set_stepper_display(stepper_pos[motor], stepper_pos[motor]);
908 }
909 callback(); // Call the callback after updating the display
910 })
911 .catch(error => {
912 callback();
913 });
914
915
916
917 }
918 );
919 interpreter.setProperty(scope, 'move_stepper_cw', wrapper);
920
921 var wrapper = interpreter.createAsyncFunction(
922 function(motor, callback) {
923 stepper_pos[motor] -= 1;
924 cursteppos[motor] -= 1;
925 if (cursteppos[motor] < 0) cursteppos[motor] = 3;
926
927 fetch('/set_reg', {
928 method: 'POST',
929 headers: {
930 'Content-Type': 'application/json'
931 },
932 body: JSON.stringify({
933 reg: 'PORTB',
934 data: step_positions[0][cursteppos[0]] + step_positions[1][cursteppos[1]]
935 })
936 })
937 .then(response => response.json())
938 .then(data => {
939 for (var i = 0; i < set_stepper_pos[motor].length; i++) {
940 set_stepper_pos[motor][i].set_stepper_display(stepper_pos[motor], stepper_pos[motor]);
941 }
942 callback(); // Call the callback after updating the display
943 })
944 .catch(error => {
945 callback();
946 });
947
948
949
950
951
952
953 }
954 );
955 interpreter.setProperty(scope, 'move_stepper_ccw', wrapper);
956
957 var wrapper = interpreter.createAsyncFunction( // Move based on direction.
958 function(steps1, steps2, msdelay, callback) {
959 var longer_distance = 1. * Math.max(Math.abs(steps1), Math.abs(steps2));
960 var d1 = steps1 / longer_distance, d2 = steps2 / longer_distance;
961
962 var moveSteps = (mystep) => {
963 //Motor1
964 stepper_pos[0] += d1;
965 cursteppos[0] += d1;
966 if (cursteppos[0] < 0) cursteppos[0] = 3;
967 if (cursteppos[0] > 3) cursteppos[0] = 0;
968
969 //Motor2
970 stepper_pos[1] += d2;
971 cursteppos[1] += d2;
972 if (cursteppos[1] < 0) cursteppos[1] = 3;
973 if (cursteppos[1] > 3) cursteppos[1] = 0;
974
975
976 fetch('/set_reg', {
977 method: 'POST',
978 headers: {
979 'Content-Type': 'application/json'
980 },
981 body: JSON.stringify({
982 reg: 'PORTB',
983 data: step_positions[0][parseInt(cursteppos[0])] + step_positions[1][parseInt(cursteppos[1])]
984 })
985 })
986 .then(response => response.json())
987 .then(data => {
988 for (var i = 0; i < set_stepper_pos[0].length; i++) {
989 set_stepper_pos[0][i].set_stepper_display(stepper_pos[0], stepper_pos[1]);
990 }
991 callback(); // Call the callback after updating the display
992 })
993 .catch(error => {
994 callback();
995 });
996
997 if (mystep < longer_distance - 1) {
998 setTimeout(() => moveSteps(mystep + 1), msdelay);
999 } else {
1000 callback(); // Call the callback after all steps are done
1001 }
1002
1003
1004
1005 };
1006
1007 moveSteps(0); // Start moving steps
1008 }
1009 );
1010 interpreter.setProperty(scope, 'move_stepper', wrapper);
1011
1012
1013 }
1014
1015 //done
1016 function initPlots(interpreter, scope) {
1017 // PLOT CALLS
1018 // Add an API for the plot call
1019 interpreter.setProperty(scope, 'plot', interpreter.createNativeFunction(
1020 function(plotname, value) {
1021 return addDataPoint(plotname, value);
1022 })
1023 );
1024
1025 // Add an API for the plot array call
1026 interpreter.setProperty(scope, 'plot_array', interpreter.createNativeFunction(
1027 function(plotname, values) {
1028 return addDataPoints(plotname, values);
1029 })
1030 );
1031
1032
1033
1034 // Add an API for the XY plot call
1035 interpreter.setProperty(scope, 'plot_scale', interpreter.createNativeFunction(
1036 function( plotname, axis, vmin,vmax, scale) {
1037 makePlotIfUnavailable(plotname);
1038 if(axis === 'x'){options[plotname].xaxis.min = vmin; options[plotname].xaxis.max = vmax; options[plotname].xaxis.autoScale=scale;}
1039 else if(axis === 'y'){options[plotname].yaxis.min = vmin; options[plotname].yaxis.max = vmax; options[plotname].yaxis.autoScale=scale;}
1040 })
1041 );
1042 // Add an API for the XY plot call
1043 interpreter.setProperty(scope, 'plot_xy', interpreter.createNativeFunction(
1044 function(plotname, vx,vy) {
1045 return addDataPointXY(plotname, vx,vy);
1046 })
1047 );
1048
1049
1050 // Add an API for the XY plot call
1051 interpreter.setProperty(scope, 'plot_xyarray', interpreter.createNativeFunction(
1052 function(plotname, X,Y, state) {
1053 if(typeof state == 'undefined')state = false;
1054 console.log(state);
1055 return plotArraysXYStack(plotname, X,Y, state);
1056 })
1057 );
1058
1059
1060 // Add an API for the XYY array plot call
1061 interpreter.setProperty(scope, 'plot_xyyarray', interpreter.createNativeFunction(
1062 function( plotname, x,y1, y2) {
1063 return plotArraysXYY(plotname, x,y1, y2);
1064 })
1065 );
1066
1067 // Add an API for the XYY array plot call
1068 interpreter.setProperty(scope, 'plot_xyyyarray', interpreter.createNativeFunction(
1069 function( plotname, x,y1, y2, y3) {
1070 return plotArraysXYYY(plotname, x,y1, y2, y3);
1071 })
1072 );
1073
1074 // Add an API for the Polar plot call
1075 interpreter.setProperty(scope, 'plot_radar', interpreter.createNativeFunction(
1076 function( angle,radius, maxrad) {
1077 return addDataPointPolar(angle,radius, maxrad);
1078 })
1079 );
1080
1081
1082
1083
1084
1085 }
1086
1087 function initGames(interpreter, scope) {
1088
1089 // Add an API for the Add Game call
1090 interpreter.setProperty(scope, 'addGame', interpreter.createNativeFunction(
1091 function() {
1092 return addGame();
1093 })
1094 );
1095 // Add an API for the Add Game call
1096 interpreter.setProperty(scope, 'stopGame', interpreter.createNativeFunction(
1097 function() {
1098 return stopGame();
1099 })
1100 );
1101 // Add an API for the Add Game call
1102 interpreter.setProperty(scope, 'setBirdY', interpreter.createNativeFunction(
1103 function(y) {
1104 return setBirdY(y);
1105 })
1106 );
1107
1108 // Add an API for the Add Piano call
1109 interpreter.setProperty(scope, 'addPiano', interpreter.createNativeFunction(
1110 function() {
1111 return addPiano();
1112 })
1113 );
1114 // Add an API for the Play Music call
1115 interpreter.setProperty(scope, 'playPiano', interpreter.createNativeFunction(
1116 function(mynote) {
1117 return playPiano(mynote);
1118 })
1119 );
1120
1121 }
1122
1123 function initIO(interpreter, scope) {
1124 gauges = [];
1125 gaugearea.empty();
1126
1127 // Add an API function for the (alert) print() block.
1128 var wrapper = function(text) {
1129 return results.html(results.html()+text+"<br>");
1130 //return document.getElementById("resulttext").innerHTML+=text+"<br>";
1131 };
1132 interpreter.setProperty(scope, 'alert',
1133 interpreter.createNativeFunction(wrapper));
1134 interpreter.setProperty(scope, 'print',
1135 interpreter.createNativeFunction(wrapper));
1136
1137 // Add an API function for the sticker() block.
1138 var wrapper = function(label, text) {
1139 return showReg(label, text);
1140 };
1141 interpreter.setProperty(scope, 'sticker',
1142 interpreter.createNativeFunction(wrapper));
1143
1144
1145 // Add an API function for the gauge() block.
1146 var wrapper = function(label, val, min, max) {
1147 if(!gauges.includes(label) ){
1148 addGauge(label, val, min, max);
1149 gauges.push(label);
1150 updateGauge(label, val, min, max);
1151 }else{
1152 updateGauge(label, val, min, max);
1153 }
1154 };
1155 interpreter.setProperty(scope, 'setGauge',
1156 interpreter.createNativeFunction(wrapper));
1157
1158 // Add an API function for the prompt() block.
1159 var wrapper = function(text) {
1160 text = text ? text.toString() : '';
1161 return interpreter.createPrimitive(prompt(text));
1162 };
1163
1164 interpreter.setProperty(scope, 'prompt',
1165 interpreter.createNativeFunction(wrapper));
1166
1167
1168 }
1169
1170 function initLists(interpreter, scope) {
1171
1172 interpreter.setProperty(scope, 'startStorage', interpreter.createAsyncFunction(
1173 function(callback) {
1174 startStorage(callback);
1175 })
1176 );
1177
1178 interpreter.setProperty(scope, 'subtract_lists', interpreter.createNativeFunction(
1179 function(x,y) {
1180 c = [];
1181 a = Object.values(x.a);
1182 b = Object.values(y.a);
1183 if(a.length == b.length){
1184 for(var i=0;i<a.length;i++)c.push(a[i]-b[i]);
1185 return interpreter.nativeToPseudo(c);
1186 }
1187 })
1188 );
1189
1190 // Add an API for the XYY array plot call
1191 interpreter.setProperty(scope, 'save_lists', interpreter.createNativeFunction(
1192 function( fname,x,y1, y2, y3) {
1193 return JSBridge.save_lists(fname,JSON.stringify(myInterpreter.pseudoToNative(x)),JSON.stringify(Object.values(y1.a)),JSON.stringify(Object.values(y2.a)),JSON.stringify(Object.values(y3.a)));
1194 })
1195 );
1196
1197 interpreter.setProperty(scope, 'initTime', interpreter.createNativeFunction(
1198 function() {
1199 return new Date();
1200 })
1201 );
1202 interpreter.setProperty(scope, 'getTime', interpreter.createNativeFunction(
1203 function( start_time) {
1204 return new Date() - start_time;
1205 })
1206 );
1207
1208
1209 }
1210
1211 function initSounds(interpreter, scope) {
1212 // Add an API for the set_voltage call
1213 interpreter.setProperty(scope, 'stop_phone_frequency', interpreter.createNativeFunction(
1214 function() {
1215 return JSBridge.stop_phone_frequency();
1216 })
1217 );
1218 interpreter.setProperty(scope, 'set_phone_frequency', interpreter.createNativeFunction(
1219 function(val) {
1220 return JSBridge.set_phone_frequency(val);
1221 })
1222 );
1223
1224 interpreter.setProperty(scope, 'set_phone_frequency_stereo', interpreter.createNativeFunction(
1225 function(val1, val2) {
1226 return JSBridge.set_phone_frequency(val1, val2);
1227 })
1228 );
1229
1230 }
1231
1232 //done
1233 function initSensors(interpreter, scope) {
1234
1235 fetch(`/get_all_sensors`)
1236 .then(response => response.json())
1237 .then(data => {
1238 allsensors = data.sensors;
1239 })
1240 .catch(error => {
1241 console.error('Error getting sensor list:', error);
1242 allsensors = ["[129]ADCSENS"];
1243 });
1244
1245
1246 // Add an API for the get_sensor call
1247 interpreter.setProperty(scope, 'get_sensor', interpreter.createAsyncFunction(
1248 function(sensor, param, callback) {
1249 fetch(`/get_sensor/${sensor}/${param}`)
1250 .then(response => response.json())
1251 .then(data => {
1252 callback(myInterpreter.nativeToPseudo(data.value)); // Assuming the value is returned as 'value'
1253 })
1254 .catch(error => {
1255 console.error('Error getting sensor value:', error);
1256 callback(null); // Call callback with null on error
1257 });
1258 })
1259 );
1260
1261 // Add an API for the get_generic_sensor call
1262 interpreter.setProperty(scope, 'get_generic_sensor', interpreter.createAsyncFunction(
1263 function(sensor, addr, callback) {
1264 fetch(`/get_generic_sensor/${sensor}/${addr}`)
1265 .then(response => response.json())
1266 .then(data => {
1267 console.log(data);
1268 callback(myInterpreter.nativeToPseudo(data.data)); // Adjust based on the response format
1269 })
1270 .catch(error => {
1271 console.error('Error getting generic sensor:', error);
1272 callback(null); // Call callback with null on error
1273 });
1274 })
1275 );
1276
1277 // Add an API for the parseAndReadSensor call
1278 interpreter.setProperty(scope, 'parseAndReadSensor', interpreter.createAsyncFunction(
1279 function(descriptor, param, callback) {
1280 const addr = descriptor.split(']')[0].substring(1);
1281 const sensor = descriptor.split(']')[1].split('/')[0];
1282 fetch(`/get_generic_sensor/${sensor}/${parseInt(addr)}`)
1283 .then(response => response.json())
1284 .then(data => {
1285 callback(myInterpreter.nativeToPseudo(data.data[param])); // Adjust based on the response format
1286 })
1287 .catch(error => {
1288 console.error('Error parsing and reading sensor:', error);
1289 callback(null); // Call callback with null on error
1290 });
1291 })
1292 );
1293
1294 // Add an API for the parseAndReadSensorVals call
1295 interpreter.setProperty(scope, 'parseAndReadSensorVals', interpreter.createAsyncFunction(
1296 function(descriptor, param, callback) {
1297 const addr = descriptor.split(']')[0].substring(1);
1298 const sensor = descriptor.split(']')[1].split('/')[0];
1299 fetch(`/get_generic_sensor/${sensor}/${parseInt(addr)}`)
1300 .then(response => response.json())
1301 .then(data => {
1302 callback(myInterpreter.nativeToPseudo(data.data)); // Adjust based on the response format
1303 })
1304 .catch(error => {
1305 console.error('Error parsing and reading sensor values:', error);
1306 callback(null); // Call callback with null on error
1307 });
1308 })
1309 );
1310
1311 // Add an API for the get_generic_sensor_param call
1312 interpreter.setProperty(scope, 'get_generic_sensor_param', interpreter.createAsyncFunction(
1313 function(sensor, addr, param, callback) {
1314 fetch(`/get_generic_sensor_param/${sensor}/${addr}/${param}`)
1315 .then(response => response.json())
1316 .then(data => {
1317 callback(myInterpreter.nativeToPseudo(data)); // Adjust based on the response format
1318 })
1319 .catch(error => {
1320 console.error('Error getting generic sensor parameter:', error);
1321 callback(null); // Call callback with null on error
1322 });
1323 })
1324 );
1325
1326 // Add an API for the scanI2C call
1327 interpreter.setProperty(scope, 'scanI2C', interpreter.createAsyncFunction(
1328 function(callback) {
1329 fetch('/scanI2C')
1330 .then(response => response.json())
1331 .then(data => {
1332 callback(myInterpreter.nativeToPseudo(data)); // Adjust based on the response format
1333 })
1334 .catch(error => {
1335 console.error('Error scanning I2C:', error);
1336 callback(null); // Call callback with null on error
1337 });
1338 })
1339 );
1340
1341 // Add an API for the scanI2CString call
1342 interpreter.setProperty(scope, 'scanI2CString', interpreter.createAsyncFunction(
1343 function(callback) {
1344 fetch('/scanI2CString')
1345 .then(response => response.json())
1346 .then(data => {
1347 callback(myInterpreter.nativeToPseudo(data)); // Adjust based on the response format
1348 })
1349 .catch(error => {
1350 console.error('Error scanning I2C string:', error);
1351 callback(null); // Call callback with null on error
1352 });
1353 })
1354 );
1355
1356
1357
1358 //WiFi RGB Controller
1359 interpreter.setProperty(scope, 'ws2812_rgb', interpreter.createNativeFunction(
1360 function( ip,R,G, B) {
1361 var packet ={ "body": JSON.stringify({"seg":{ "col":[[parseInt(R),parseInt(G),parseInt(B),"0"],[],[]],"pal":0}}) , "method": "POST", "mode": "cors" } ;
1362 fetch(ip+"/json/si", packet);
1363 })
1364 );
1365
1366 }
1367
1368
1369
1370 function initAllApis(interpreter, scope){
1371 initApi(interpreter, scope);
1372 initLists(interpreter, scope);
1373 initIO(interpreter, scope);
1374 initPlots(interpreter, scope);
1375 initGames(interpreter, scope);
1376 initKuttyPy(interpreter, scope);
1377 initSensors(interpreter, scope);
1378 initSounds(interpreter, scope);
1379 }
1380
1381