-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1539 lines (1251 loc) · 46.1 KB
/
script.js
File metadata and controls
1539 lines (1251 loc) · 46.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let rebootTimeoutId = undefined;
let saveConfigTimeOutId = undefined;
let peerTimeOutId = {};
const peerTimeoutMs = 10000;
let webSocket;
let webSocketConnected = false;
let onWebSocketConnectedOneTime = null;
let webSocketReconnect = undefined;
let config = {};
let onSphereUp = undefined;
let onSphereDown = undefined;
const maxWifiNetworks = -1;
let ssidList = [];
let statuscode = 0x80;
const frameRate = 20;
let warmth = 0;
let targetWarmth = 0;
const maxWarmth = 5.0;
let peakEnergy = 0;
const tuningState = {
running: false,
goodPeakFound: false,
timeOutId: undefined
}
// const minFilterFrequencyHz = 90;
// const maxFilterFrequencyHz = 250;
// const wideFilterFrequencyHz = (minFilterFrequencyHz + maxFilterFrequencyHz)/2;
// const wideFilterBandwidthHz = maxFilterFrequencyHz - minFilterFrequencyHz;
const narrowFilterBandwidthHz = 20;
let mic = {};
const numberOfHistogramBins = 8;
const histogram = Array(numberOfHistogramBins).fill(0);
let micMinFreq = undefined, micMaxFreq = undefined;
const tuneWindowMs = 3000;
const lowMicSampleRate = 1;
const highMicSampleRate = 5;
const minHistogramPeakValue = 1.0; //at highMicSampleRate (5 per second) and tuneWindowMs (3000)
let audioCtx = undefined;
//if(audioCtx === undefined) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
let onTouchOneTime = null;
let onMovedOneTime = null;
const peers = [];
let lastSplideIndex = -1;
const enableSwipe = true;
let deferredInstallPrompt = undefined;
let micPostLocked = true; // lock mic POST flag
// Request rate limiting
const requestQueue = {
pending: new Set(),
maxConcurrent: 3,
async execute(key, fn) {
// Skip if same request is already pending
if (this.pending.has(key)) {
console.log(`Skipping duplicate request: ${key}`);
return null;
}
// Wait if too many concurrent requests
while (this.pending.size >= this.maxConcurrent) {
await new Promise(resolve => setTimeout(resolve, 100));
}
this.pending.add(key);
try {
return await fn();
} finally {
this.pending.delete(key);
}
}
};
// unlock 5 seconds after page load
setTimeout(() => {
micPostLocked = false;
console.log("MIC POSTS UNLOCKED");
}, 5000);
async function init() {
document.querySelectorAll('img').forEach(img => {
img.addEventListener('error', function onError() {
setTimeout(() => {
const u = new URL(img.src, location.href);
u.searchParams.set('_retry', Date.now());
img.src = u.toString();
console.log('Retrying image load:', img.src);
}, 5000);
});
});
document.addEventListener("keydown", (event) => {
if(!event.repeat) onKeyPressed(event.key, true);
});
document.addEventListener("keyup", (event) => {
onKeyPressed(event.key, false);
});
initSphere()
}
function configureUIEvents() {
if(enableSwipe) {
//stop form interactions starting a swipe gesture
document.addEventListener('focusin', function(event) {
if(event.target?.closest && event.target.closest('.yo-yo-form')) {
allowSwipe(false);
}
}, true);
// focusout allows swipe again unless focus goes to another element inside the same form
document.addEventListener('focusout', function(event) {
const fromForm = event.target?.closest && event.target.closest('.yo-yo-form');
const toInsideSameForm = event.relatedTarget && event.relatedTarget.closest && event.relatedTarget.closest('.yo-yo-form') === event.target.closest('.yo-yo-form');
if(fromForm && !toInsideSameForm) {
allowSwipe(true);
}
}, true);
}
window.addEventListener('resize', debounce(() => {
positionSphereImage();
updateSlide();
}, 300));
const serverForm = document.getElementById('server_form');
serverForm.addEventListener('submit', function(event) {
event.preventDefault();
onServerSaveEvent(new FormData(serverForm));
});
const wifiForm = document.getElementById('wifi_form');
wifiForm.addEventListener('submit', function(event) {
console.log("wifiForm.addEventListener()");
event.preventDefault();
onWiFiSaveEvent(new FormData(wifiForm));
});
const determinationText = document.getElementById('determination_individual');
const determinationListener = debounce((event) => {
console.log('determinationListener');
const json = { server: { ...(config.server ?? {}) }};
json.server.room = { ...(json.server.room ?? {}) };
json.server.room.determination = event.target.value;
setConfiguration(json);
}, 2000);
determinationText.addEventListener('input', determinationListener);
splide.on('moved', (slideIndex) => {
if(onMovedOneTime) {
onMovedOneTime();
onMovedOneTime = undefined;
}
});
lastSplideIndex = splide.index;
splide.on('active', (slideElement) => {
//prevent splide.refresh() calls causing updateSlide() events:
if(lastSplideIndex !== splide.index) updateSlide(true);
if(sphereIsOnline()) lastSplideIndex = splide.index;
});
}
function hasConfiguration() {
return(typeof config === 'object' && Object.keys(config).length > 0);
}
async function initSphere() {
console.log('initSphere');
//registerServiceWorker();
splide = new Splide('#carousel', {
type: 'slide', //don't use loop it duplicates the content and screws up the forms
perPage: 1,
drag: false, //also swipe
}).mount();
showCarousel(false);
positionSphereImage();
allowInteraction(false);
console.log('configureUIEvents');
configureUIEvents();
console.log('configureUIEvents - done');
console.log('getConfiguration');
if(await getConfiguration()) {
console.log('getConfiguration - done');
document.getElementById('spherename').innerText = config?.captiveportal?.ssid ?? '';
document.getElementById('sphereversion').innerText = config?.version ?? '';
setInterval(() => { loop(); }, 1000/frameRate);
setInterval(() => { onTick(); }, 10000);
manageWebSocket(() => onStart());
updateSlide(true);
}
else {
console.log('getConfiguration - error');
const rows = getSlideByID(getSlideId()).querySelectorAll('.slide-content .row');
rows[0].innerHTML = 'error';
}
}
function onKeyPressed(key, on) {
if(getSlideId() === 'landing') {
const number = Number(event.key);
if (!isNaN(number)) {
onUserClicked({track: number}, on);
}
}
}
function positionSphereImage() {
const middleRow = document.querySelector('.middle-row');
const backgroundImage = document.querySelector('.background-image');
if (middleRow && backgroundImage) {
const middleRect = middleRow.getBoundingClientRect();
backgroundImage.style.top = `${middleRect.top + window.scrollY}px`;
backgroundImage.style.height = `${middleRect.height}px`;
}
}
function debounce(fn, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
function onTuningComplete() {
if(tuningState.running) {
console.log('stop tuning');
const peak = getGoodHistogramPeak(histogram, minHistogramPeakValue * (mic?.level ?? 1));
console.log('getGoodHistogramPeak ', peak);
if(peak.frequency > -1 && peakEnergy > 0) {
//Adjust microphone so the sphere will turn orange at this chanting volume
const micLevel = (mic?.level ?? 1) * (maxWarmth/(peakEnergy * 0.9));
setMic({frequency: peak.frequency, level: parseFloat(micLevel.toFixed(2))}, true);
tuningState.goodPeakFound = true;
updateSlide();
}
}
tuningState.timeOutId = undefined;
peakEnergy = 0;
if(tuningState.goodPeakFound) {
setTimeout(() => {
if(tuningState.timeOutId === undefined) showNextSlide();
}, tuneWindowMs);
}
}
function loop() {
const id = getSlideId();
if(id === 'tuning' && !tuningState.timeOutId && !isCold()) {
console.log('start tuning');
clearHistogram(histogram);
tuningState.timeOutId = setTimeout(() => {
onTuningComplete();
}, tuneWindowMs);
updateSlide();
}
draw();
}
function draw() {
if(sphereIsUp()) {
const dw = targetWarmth - warmth;
warmth = warmth + (dw * 0.1);
setBackgroundFromValue(Math.min(Math.max(warmth, 0.0), maxWarmth) * (255/maxWarmth));
}
else {
setBackgroundFromValue(0);
}
}
function onTick() {
getStatus();
}
async function fetchWithTimeout(endpoint, timeoutMs = 5000, options = {}) {
return requestQueue.execute(endpoint, async () => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(endpoint, { signal: controller.signal, ...options });
clearTimeout(timeout);
return response;
}
catch (err) {
clearTimeout(timeout);
if (err && err.name === 'AbortError') {
throw new Error(`Fetch timeout (${timeoutMs}ms): ${endpoint}`);
}
throw err;
}
});
}
async function getStatus() {
let s = statuscode & 0xfe; // offline - turn off least sign bit
try {
const response = await fetchWithTimeout('/yoyo/status', 3000);
if (response.ok) {
const json = await response.json();
s = Number(json.statuscode);
s = webSocketConnected ? s | 0x08 : s;
updateCount(json?.count ?? 0);
}
}
catch (e) {
}
// Update status if it changed
if (s !== statuscode) {
onStatus(s);
}
}
function sphereWillReboot() {
return rebootTimeoutId;
}
function reboot() {
const id = 'landing';
showSlideID(id);
const rows = getSlideByID(id).querySelectorAll('.slide-content .row');
const savedNetwork = config?.wifi?.ssid ?? '';
rows[0].innerHTML = 'Rebooting...';
rows[2].innerHTML = 'Now close this window. Then make sure this ' + getDeviceType() + ' is on ' + ((savedNetwork !== '') ? 'the ' + savedNetwork : 'that') + ' network too and scan the new QR code when the sphere has restarted.';
postJson('/yoyo/reboot', {}, 500);
}
function sphereIsOnline(s = statuscode) {
return (s & 0x01) == 0x01;
}
function sphereIsUp(s = statuscode) {
return (s & 0x02) == 0x02;
}
function captivePortalRunning(s = statuscode) {
return (s & 0x04) == 0x04;
}
function localConnected(s = statuscode) {
return (s & 0x08) == 0x08;
}
function remoteConnected(s = statuscode) {
return (s & 0x10) == 0x10;
}
function drawSphere(s) {
const sphereImage = document.querySelector('#sphereImage');
if(sphereIsUp(s)) sphereImage.src = 'img/sphere-up.png';
else sphereImage.src = 'img/sphere-down.png';
}
function onStatus(s) {
if(statuscode != s) {
const lastStatus = statuscode;
statuscode = s;
if(sphereIsUp(s)) {
if(onSphereUp && typeof onSphereUp === 'function') onSphereUp();
onSphereUp = undefined; //one time event
}
else {
if(onSphereDown && typeof onSphereDown === 'function') onSphereDown();
onSphereDown = undefined; //one time event
}
if(!sphereIsOnline(lastStatus) && sphereIsOnline()) onOnline();
if(sphereIsOnline(lastStatus) && !sphereIsOnline()) onOffline();
switch (getSlideId()) {
case 'landing': getSlideByID('landing').querySelectorAll('.slide-content .row')[2].querySelector("span").innerHTML = generateLandingText();
}
drawSphere(statuscode);
}
}
function onWebSocketConnected(v = true) {
if(webSocketConnected !== v) {
if(v) {
onStatus(statuscode | 0x01 | 0x08);
if(onWebSocketConnectedOneTime) {
onWebSocketConnectedOneTime();
onWebSocketConnectedOneTime = null;
}
}
else {
//if(tuningState.timeOutId) activateTuning(false);
}
allowInteraction(v);
webSocketConnected = v;
updateSlide();
}
}
async function onOnline() {
console.log("onOnline", config);
rebootTimeoutId = undefined;
document.querySelector('#sphereImage').style.filter = 'none';
//allowInteraction(true); //TODO: should wait for the web socket to reconnect
peers.push(...await fetchPeers());
//onPeersChanged();
makePeers(document.getElementById('room_container'), config.peers, true);
//return to last active page:
showSlideIndex(lastSplideIndex);
}
async function onOffline() {
console.log("onOffline");
onWebSocketConnected(false);
showSlideID('landing');
document.querySelector('#sphereImage').style.filter = 'invert(30%)';
allowInteraction(false);
targetWarmth = 0;
}
async function getConfiguration(timeoutMs = 5000, attempts = 5) {
for (let n = 0; n < attempts; n++) {
try {
const response = await fetchWithTimeout('/yoyo/config', timeoutMs);
if (response.ok) {
const json = await response.json();
if(json.statuscode) {
let s = Number(json.statuscode);
s = webSocketConnected ? s | 0x08 : s;
onStatus(s);
delete json.statuscode;
}
updateCount();
setConfiguration(json, false);
return true; //success - break out
}
else onStatus(0x00); // offline
}
catch (e) {
onStatus(0x00); // offline
}
await new Promise(res => setTimeout(res, 1000));
}
return false;
}
function isPlainObject(v) {
return v !== null && typeof v === 'object' && !Array.isArray(v);
}
function isEmptyObject(o) {
return isPlainObject(o) && Object.keys(o).length === 0;
}
async function setConfiguration(json, post = true, rebootDelayMs = -1) {
let success = false;
if (isPlainObject(config) && !isEmptyObject(json)) {
console.log("setConfiguration", json);
config = { ...config, ...json };
console.log(JSON.stringify(config));
if(post) {
success = postJson('/yoyo/config', config, 1000);
}
if(success) {
if(post && rebootDelayMs >= 0) {
onSphereDown = undefined;
rebootTimeoutId = setTimeout(function () {
if(sphereIsUp()) {
onSphereDown = function () {
drawSphere(statuscode);
reboot();
};
}
else reboot();
}, rebootDelayMs);
showSlideID('landing');
allowInteraction(false);
}
}
}
else {
success = false;
}
return success;
}
function onStart() {
console.log("onStart", config);
const f = function() { showCarousel(true); };
//allowInteraction(true);
if(!config?.server?.host) {
showSlideID('server', f);
}
else if(!config?.mic?.frequency) {
showSlideID('tuning', f);
}
else if(!config?.wifi?.ssid || captivePortalRunning()) {
showSlideID('wifi', f);
}
else showSlideID('landing', f);
}
async function onSlideMoved() {
console.log('onSlideMoved');
}
async function activateTuning(v = true) {
if (v && !tuningState.running) {
setMic({level: (mic?.level ?? 1), frequency: -1, bandwidth: -1, rate: highMicSampleRate}, false);
tuningState.timeOutId = undefined;
tuningState.goodPeakFound = false;
tuningState.running = true;
}
else if (!v && tuningState.running) {
if(tuningState.timeOutId !== undefined) {
clearTimeout(tuningState.timeOutId);
tuningState.timeOutId = undefined;
}
const f = tuningState.goodPeakFound ? mic.frequency : config?.mic?.frequency;
setMic({rate: -1, frequency: f, bandwidth: narrowFilterBandwidthHz}, true); //return to default rate
tuningState.goodPeakFound = false;
tuningState.running = false;
}
}
function drawEllipse(canvas, width, height) {
const ctx = canvas.getContext("2d");
//ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear previous drawings
// Draw a horizontal ellipse
ctx.beginPath();
ctx.ellipse(canvas.width / 2, canvas.height / 2, width / 2 , height / 2, 0, 0, 2 * Math.PI);
ctx.strokeStyle = "gray";
ctx.lineWidth = 2;
ctx.stroke();
}
function drawEllipseWithImages(canvas, width, height) {
const imgSrc = 'img/sphere-up.png';
const numImages = 3;
const ctx = canvas.getContext("2d");
//ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear previous drawings
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radiusX = width/2;
const radiusY = height/2;
const image = new Image();
image.src = imgSrc;
image.onload = function() {
const angleStep = (2 * Math.PI) / numImages; // Number of images to place along the ellipse
for (let i = 0; i < numImages; i++) {
const angle = i * angleStep;
const x = centerX + radiusX * Math.cos(angle);
const y = centerY + radiusY * Math.sin(angle);
// Draw the image centered at (x, y)
ctx.drawImage(image, x - 25, y - 25,50,50);
}
};
}
function makePeers(container, data, layout = false) {
if(container && data) {
const keys = Object.keys(data);
for (let i = 0; i < keys.length; i++) {
const id = keys[i];
if (!document.getElementById(id)) {
makePeer(id, data[id].user, container);
}
}
}
if(layout) layoutPeers(container);
}
function layoutPeers(container) {
if(container) {
const centerX = container.clientWidth / 2;
const centerY = container.clientHeight / 2;
const radiusX = container.clientWidth / 2;
const radiusY = container.clientHeight / 2;
const peers = Array.from(container.children);
for (let i = 0; i < peers.length; i++) {
const angle = (i * 2 * Math.PI) / peers.length;
const x = centerX + radiusX * Math.cos(angle);
const y = centerY + radiusY * Math.sin(angle);
let peer = peers[i];
if (peer) {
peer.style.left = `${x}px`;
peer.style.top = `${y}px`;
}
}
}
}
function makePeer(id, user, container) {
const template = document.getElementById("room_item_template");
let peer = template.content.cloneNode(true).firstElementChild;
peer.id = id;
if(user) peer.querySelector("span").textContent = user;
updatePeer(peer, false);
peer.addEventListener("mousedown", () => { onUserClicked({id: peer.id}); });
peer.addEventListener("mouseup", () => { onUserClicked({id: peer.id}, false); });
peer.addEventListener("touchstart", () => { onUserClicked({id: peer.id}); });
peer.addEventListener("touchend", () => { onUserClicked({id: peer.id}, false); });
if(container) container.appendChild(peer);
return peer;
}
function onUserClicked(json, active = true) {
json = {
...json,
amplitude: 0.5,
duration: active ? 10000 : 100,
fade: 100
};
console.log('onUserClicked', json);
postJson('/yoyo/tone', json, 500);
}
function updatePeer(peer, online) {
if(peer) {
if(peerTimeOutId[peer.id]) clearTimeout(peerTimeOutId[peer.id]);
const img = peer.querySelector("img");
if(online) {
img.src = 'img/sphere-up.png';
peerTimeOutId[peer.id] = setTimeout(() => {
updatePeer(peer, false);
}, peerTimeoutMs);
}
else img.src = 'img/sphere-down.png';
}
}
function isStandalone() {
return getDisplayMode() === 'standalone';
}
function getDisplayMode() {
const modes = ['fullscreen', 'standalone', 'minimal-ui', 'browser'];
for (const mode of modes) {
if (window.matchMedia(`(display-mode: ${mode})`).matches) {
return mode;
}
}
return 'unknown';
}
function getUserAgent() {
return(navigator.userAgent || navigator.vendor || window.opera);
}
function getDeviceType() {
const ua = getUserAgent();
const isPhone = /iPhone|Android.*Mobile|Windows Phone|BlackBerry|webOS/i.test(ua);
return isPhone ? "phone" : "computer";
}
function getOS() {
let os = "unknown";
const ua = getUserAgent();
if (/Android/i.test(ua)) os = "android";
else if (/Windows NT/i.test(ua)) os = "windows";
else if (/iPhone|iPad|iPod/i.test(ua)) os = "ios";
else if (/Macintosh|Mac OS X/i.test(ua)) os = "macos";
return os;
}
function getBrowser() {
let browser = "unknown";
const ua = getUserAgent();
if (/crios|chrome/i.test(ua)) browser = "chrome";
else if (/safari/i.test(ua)) browser = "safari";
return browser;
}
function generateLandingText() {
const savedNetwork = config?.wifi?.ssid ?? '';
let text = '';
if(sphereWillReboot()) {
if(sphereIsUp()) text += 'Turn the sphere over now and it ';
else text += 'The sphere';
text += ' will try to connect to the <span class=\'ssid\'>' + savedNetwork + '</span> WiFi network. ';
}
else {
if(sphereIsOnline()) {
if(captivePortalRunning()) {
text += 'Your sphere needs to be ' + (!(config?.mic?.frequency && config?.server?.host) ? 'configured and ' : '') + 'connected to a WiFi network';
if(savedNetwork !== '') text += ', it couldn\'t connect to <span class=\'ssid\'>' + savedNetwork + '</span>. ';
else text += '. ';
if(localConnected() && !sphereIsUp()) {
text += 'To get started, please turn the sphere over. ';
onSphereUp = function() { onStart() };
}
}
else {
text += 'Your sphere is connect' + (localConnected() ? 'ed' : 'ing') + ' to a WiFi network';
if(!localConnected()) {
text += '.<br>Please wait. ';
}
else if(!remoteConnected()) {
text += ' but not a Resound server. ';
}
else {
text += ' and a Resound server. ';
text += ' Everything looks good. ';
}
}
}
else {
text += 'Your sphere appears to be offline. ';
if(savedNetwork !== '') {
text += 'It was last connected to the <span class=\'ssid\'>' + savedNetwork + '</span> WiFi network. Is the sphere plugged in? Is this '+ getDeviceType() + ' on that network too?';
}
}
}
return text.trim();
}
function generateWiFiText(networksAvailable) {
const savedNetwork = config?.wifi?.ssid ?? '';
let text = 'Your sphere is ';
if(!captivePortalRunning() && sphereIsOnline()) {
text += 'connected to the <span class=\'ssid\'>' + savedNetwork + '</span> WiFi network (' + getHost() +'). ';
}
else {
text += 'not connected to a WiFi network';
if(savedNetwork !== '') text += ', it couldn\'t connect to <span class=\'ssid\'>' + savedNetwork + '</span>. ';
else text += '. ';
if(networksAvailable) text += 'Select a network, enter the password and press connect. ';
// else text += 'Unable to see any networks to connect to. ';
}
return text.trim();
}
function generateServerText() {
let text = 'Your sphere is ';
if(captivePortalRunning()) text += 'not connected to the Internet. ';
else {
if(remoteConnected()){
text += 'connected to a Resound server (' + (config?.server?.host ?? '') + '). ';
}
else {
text += 'not connected to a Resound server. ';
}
}
return text.trim();
}
function generateTuningText() {
let text = '';
const f = config?.mic?.frequency;
const isTuned = (f !== undefined);
if(!isTuned) {
text += 'Your sphere isn\'t tuned.<br>';
}
else {
text += 'Your sphere is tuned to a frequency of ' + f + 'Hz'
+ (getNoteName(f) ? ' (the note of ' + getNoteName(f) + ')' : '') + '.<br>';
}
if(sphereIsUp()) {
text += 'Chant NMRK to ' + (isTuned ? 're' : '') + 'tune it. ';
}
else {
text += 'To get started, please turn the sphere over. ';
}
return text.trim();
}
function allowInteraction(v) {
showCarouselControls(v);
allowSwipe(v);
}
function allowSwipe(v) {
console.log('allowSwipe', v, splide.options.drag, enableSwipe);
v = v && enableSwipe;
if(v !== splide.options.drag) {
const arrows = document.querySelector('.splide__arrows');
const pagination = document.querySelector('.splide__pagination');
const controlVisible = (arrows.style.display === 'block' && pagination.style.display === 'flex');
splide.options = { drag: v };
splide.refresh(); //will reset the visibility of the controls
showCarouselControls(controlVisible);
}
}
function showCarousel(v) {
var carousel = document.getElementById('carousel');
carousel.style.visibility = v ? 'visible' : 'hidden';
carousel.style['pointer-events'] = v ? 'auto' : 'none';
}
function showCarouselControls(v) {
const arrows = document.querySelector('.splide__arrows');
const pagination = document.querySelector('.splide__pagination');
if (arrows) arrows.style.display = v ? 'block' : 'none';
if (pagination) pagination.style.display = v ? 'flex' : 'none';
}
function updateCount(count = 0) {
const countElement = document.getElementById('count');
countElement.textContent = Math.max(config?.server?.room?.count ?? 0, count);
}
async function updateSlide(changed = false) {
console.log('updateSlide()', changed, lastSplideIndex, splide.index)
onSphereDown = undefined;
onSphereUp = undefined;
//onTouchOneTime = function() { showSlideID('volume'); };
const id = getSlideId();
if(id === 'tuning') activateTuning(sphereIsUp());
else activateTuning(false);
//only interactive once installed and the web socket is connected:
//allowInteraction((id === 'landing') ? isStandalone() : webSocketConnected);
const roomContainer = document.getElementById('room_container');
roomContainer.style.display = sphereIsOnline() ? 'block' : 'none';
if(changed) {
//postJson('/yoyo/volume', {mute: id !== 'landing'}, 500);
}
const lastRow = getSlideByID(id).querySelectorAll('.slide-content .row')[2];
switch (id) {
case 'landing':
layoutPeers(roomContainer);
if(lastRow) lastRow.querySelector('span').innerHTML = generateLandingText();
allowInteraction(webSocketConnected);
break;
case 'tuning':
onSphereDown = function() { updateSlide(); console.log('TODO: tuning - onSphereDown'); };
onSphereUp = function() { updateSlide(); console.log('TODO: tuning - onSphereUp'); };
if(lastRow) lastRow.querySelector('span').innerHTML = generateTuningText();
break;
case 'server':
const name = document.getElementById('server_name');
const host = document.getElementById('server_host');
const channel = document.getElementById('server_channel');
name.value = config?.server?.name ?? '';
host.value = config?.server?.host ?? '';
channel.value = config?.server?.room?.channel ?? '';
if(lastRow) lastRow.innerHTML = generateServerText();
break;
case 'wifi':
if(changed) {
fetchWiFiNetworks().then(ssidList => {
populateWiFiForm(config, ssidList);
if(lastRow) lastRow.innerHTML = generateWiFiText(ssidList.length > 0);
});
}
allowInteraction(webSocketConnected);
break;
case 'determination':
const determinationText = document.getElementById('determination_individual');
determinationText.value = config?.server?.room?.determination ?? '';
break;
case 'volume':
const vollevel = document.getElementById('vollevel');
vollevel.disabled = !sphereIsUp();
vollevel.onchange = function() {
onVolumeChanged(vollevel.value/100);
};
onVolumeChanged(config?.volume ?? 1.0, false);
onSphereDown = function() { updateSlide(); console.log('TODO: volume - onSphereDown'); };
onSphereUp = function() { updateSlide(); console.log('TODO: volume - onSphereUp'); };
if(lastRow) lastRow.querySelector('span').innerHTML = sphereIsUp()
? lastRow.querySelector(".sphere_up_text").innerHTML
: lastRow.querySelector(".sphere_down_text").innerHTML;
break;
default:
console.log("no rule for: " + id);
}
}
function getNoteName(f) {
let note = undefined;
if(f > 0) {
const A4 = 440;
const noteNames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
const semitoneOffset = Math.round(12 * Math.log2(f / A4));
const noteIndex = (semitoneOffset + 9 + 12) % 12; // +9 to shift from A to C, +12 to handle negatives
note = noteNames[noteIndex];
}
return note;
}
function mute(v = true) {
}
function onVolumeChanged(v, localChange = true) {
console.log('vollevel', v, localChange);
config.volume = v;
if(localChange) {
postJson('/yoyo/volume', {v:config.volume}, 500);
console.log('localchange vollevel', v);
if(saveConfigTimeOutId) clearTimeout(saveConfigTimeOutId);
saveConfigTimeOutId = setTimeout(function() {
postJson('/yoyo/config', {}, 500);