-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
843 lines (692 loc) · 23.8 KB
/
main.ts
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
/**
*/
// % color=#333300 weight=100 icon="\uf21b"
// block="SEEK"
const enum SEEKType{
TEST = 0,
GMETER =1,
ECTOSCOPE = 2,
SPIRIT_SIGN = 3,
TELEGRAPH = 4
}
const enum UWBType{
ANCHOR = 0,
COORDINATE,
}
namespace digitalghosthunt {
// Last anchor reading
// When the board loses sight of an anchor it returns the last known
// we need to filter for these readings
let lastDistance:number=0;
/* ************************************************
Story classes
*/
/** A point of spooky interaction
This could be a source of ghostly waves
or part of an ectoscope
Can be a point or a circle
*/
export class SpookyPoint{
//ID of point,
id:number;
// if anchor
addr:number;
// Coordinates if AR point
x:number;
y:number;
z:number;
trail_id:number; //If point is part of a trail
radius:number; // 0 if point
// An anchor or a software point in AR space
type:number;
// Which device can detect this point
device:number;
// Optional variables to make these active in particular scenes
// or acts
act:number;
scene:number;
constructor(id:number,addr:number,x:number,y:number,z:number,radius:number,type:number,trail_id:number,device:number) {
this.id = id;
this.addr = addr;
this.x = x;
this.y = y;
this.z = z;
this.radius = radius;
this.type = type;
this.device = device;
this.trail_id = trail_id;
this.act = -1;
this.scene = -1;
}
}
export class VisiblePoint{
point:SpookyPoint;
distance:number;
constructor(point:SpookyPoint,distance:number){
this.point = point;
this.distance = distance;
}
}
/** A single contiguous ecto trail
NOTE: Must be constructed node by node
e.g A-B-C to define shape
*/
export class EctoTrail {
//ID of trail
id:number;
//The width of the ectoplasmic line we're drawing
// uniform on the whole trail for sanity
width:number;
points: SpookyPoint[];
constructor(id:number, points: SpookyPoint[],width:number) {
this.id=id;
this.points = points;
this.width = width;
}
}
/** One UWB-rigged 'room' in a story, really a single UWB network
This will contain all UWB interaction points
Each room is identified by the id of the initator anchor
*/
export class Room {
// This is the id of the initiator
public id:number;
public points: SpookyPoint[];
// Numeric ids of anchors in room for identification
public anchorIDs: Number[];
constructor(id:number,points: SpookyPoint[],anchorIDs: Number[]){
this.id = id;
this.points = points;
this.anchorIDs = anchorIDs;
}
}
/** Get a room by its anchor id
Used for finding current room device is in
*/
function roomById(id:number, rooms:Room[]):Room{
for (let x:number = 0;x<rooms.length;x++){
if (id == rooms[x].id){
return rooms[x];
}
}
return null;
}
class Anchor {
addr:number;
distance:number;
constructor(addr:number,distance:number) {
this.addr=addr;
this.distance=distance;
}
}
/*
Device configuration settings
*/
/* Radio settings, TBD */
const enum RadioMessages {
STORY = "S",
GHOST = "G",
}
const RadioSeparator:string = "::";
const SEEKGroup:number = 99;
/* SEEK presets and variable, by device */
//GMeter and Ectoscope
let gmeterRange = 5000; //in mm
let ectoScopeRange = 1000; //in mm
let scan_result = 0;
//telegraph
const alphabet: string[] = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
const morse: string[] = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----"];
/*
Toggle test version so students can use it without UWB and for testing
0 = normal mode
1 = simulation ready testing
2 = functional testing (for testing stories)
*/
export let test_mode:number = 0;
let sep: string = ";;";
// Their translations, by index
export let msgs = ['A', 'M', 'UNDER', 'OVER', 'THIEF', 'YES', 'NO', 'WAIT', 'DANGER', 'THANK YOU']
// Sprit sign
let selected = [[0, -1]];
let x: number = 2;
let y: number = 2;
// Spirit signs
export let signs = [
images.createImage(`
# . . . #
. . . # #
. . . . .
. . . . .
# . . . #
`),
images.createImage(`
# . . . #
. . . . .
. . . . .
. . # . .
# # # # #
`),
images.createImage(`
# . . . #
. . . . .
# . . . #
# . . . #
# . . . #
`),
images.createImage(`
# . . . #
. . . . .
. . # . .
. . . . .
# . . . #
`),
images.createImage(`
# # . . .
# . . . .
. . . . .
. . . . #
. . . # #
`),
images.createImage(`
# . . . #
. . . . #
. . # # #
. . . . .
# . . . #
`),
images.createImage(`
# # . # #
# . . . .
. . . . .
. . . . .
# . . . #
`),
images.createImage(`
. . . . .
. . . . .
# # . # #
. . . . .
. . . . .
`),
images.createImage(`
# . . . #
. . # . .
. . # . .
. . # . .
# . . . #
`),
images.createImage(`
# . . . #
# . . . #
# # # # #
. . . . .
. . . . .
`),
];
/* ****************************************************************
Startup Blocks and events
*/
/**
The Main SEEK startup function
This function:
- Connects to UWB by changing pins to 0,1
- Setup the radio group and event
*/
//% block
export function startUp() {
// Set UART pins to 0,1 for DWM
connectUWB();
setupRadio();
}
/** Setup the radio events and channels
*/
function setupRadio(){
radio.setGroup(SEEKGroup);
radio.onReceivedString(function (receivedString: string) {
if (receivedString.length > 0){
let message:string[] = receivedString.split(RadioSeparator);
if (message.length > 1){
/*if (message[0].indexOf(RadioMessages.GHOST)>=0) {
// Used in the finale when the ghost 'speaks' through detectors
basic.showString(message[1]);
}*/
}
}
});
}
/**
Tell the Micro:bit something has changed in the story
such as what act/scene we are in
*/
function updateStory(message:string) {
//
}
/* ****************************************************************
SEEK functions
Main functions for each type of SEEK detector
*/
/**
G Meter
v2.0 now uses UWB functions below
if nearest point is in range,
// return as a number 0-10 as a percentage of device range
*/
//% block
export function gMeter(rooms:Room[]): number {
let visiblePoints:VisiblePoint[]= scan(currentPos_x(),currentPos_y(), SEEKType.GMETER, rooms);
if (visiblePoints != null && visiblePoints.length > 0){
if (visiblePoints[0].distance <= gmeterRange && lastDistance != visiblePoints[0].distance){
lastDistance = visiblePoints[0].distance;
return Math.round((gmeterRange-visiblePoints[0].distance)/gmeterRange*10);
}
}
return 0;
}
// Adapted from: https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment
function sqr(x:number) { return x * x }
function dist2(vx:number,vy:number, wx:number,wy:number) { return sqr(vx - wx) + sqr(vy - wy) }
function distToSegmentSquared(p_x:number,p_y:number, v:SpookyPoint, w:SpookyPoint) {
let l2 = dist2(v.x,v.y,w.x,w.y);
if (l2 == 0) return dist2(p_x,p_y,v.x,v.y);
let t = ((p_x - v.x) * (w.x - v.x) + (p_y - v.y) * (w.y - v.y)) / l2;
t = Math.max(0, Math.min(1, t));
return dist2(p_x,p_y,(v.x + t * (w.x - v.x)),(v.y + t * (w.y - v.y)) );
}
export function distToSegment(p_x:number,p_y:number, v:SpookyPoint, w:SpookyPoint) { return Math.sqrt(distToSegmentSquared(p_x,p_y, v, w)); }
/**
Ectoscope
Take visible points and find the nearest trail, and its distance
v2.0 now uses UWB functions below
*/
//% block
export function ectoScan(rooms:Room[],trails:EctoTrail[]): number {
let x:number = 0;
let visiblePoints:VisiblePoint[]= scan(currentPos_x(),currentPos_y(), SEEKType.ECTOSCOPE, rooms);
if (visiblePoints != null && visiblePoints.length > 0){
// Get the trail the nearest point belongs to
if (visiblePoints[0].point.trail_id >0){
let trail:EctoTrail = null;
if (trails != null && trails.length > 0){
for (x=0;x<trails.length;x++){
if (trails[x].id == visiblePoints[0].point.trail_id){
trail = trails[x];
break;
}
}
}
if (trail !=null){
//Test the part of the trail next to and behind
// the node to find the shortest distance
let distances:number[] = [visiblePoints[0].distance];
let d:number = 0;
for (x=0;x<trail.points.length;x++){
if (trail.points[x].id == visiblePoints[0].point.id){
// In front
if (x+1<trail.points.length){
d = distToSegment(currentPos_x(),currentPos_y(),trail.points[x],trail.points[x+1])
distances.push(d);
}
// Behind
if (x-1>=0){
d = distToSegment(currentPos_x(),currentPos_y(),trail.points[x],trail.points[x-1])
distances.push(d);
}
}
}
if (distances !=null && distances.length >0){
distances = distances.sort((n1,n2) => n1 - n2);
/* for (let o:number=0;o<distances.length;o++){
basic.showNumber(Math.round(distances[o]));
basic.pause(100);
}*/
let result = Math.round((ectoScopeRange-(distances[0]-trail.width))/ectoScopeRange*10);
if (result<=0){
return 0;
} else{
return result;
}
}
}
}
}
return 0;
}
/** Find spooky objects nearby.
A scan is done in the following steps:
1. Get all visible anchors
2. find what Room we're in using anchor ids
3. Find all visible points (filtered by device type) in that room, sorted by distance
4. return visible points
TODO: Refactor to make more general
@param device - which SEEK Device type is scanning
@param rooms - rooms in the story where we might be scanning
@return distance to nearest object
*/
function scan(pos_x:number, pos_y:number, device:number, rooms:Room[]): VisiblePoint[] {
let result = 0;
let x =0;
let visiblePoints:VisiblePoint[] = null;
if (test_mode == 1) {
// Return a random number so they can test
result = Math.randomRange(0, 10);
} else {
// 1. Get all visible anchors
let visibleAnchors:Anchor[] = getAnchors();
// 2. find what Room we're in using anchor ids
if (visibleAnchors!=null && visibleAnchors.length >0 && rooms !=null && rooms.length >0){
let room = null;
for (let v:number = 0;v<visibleAnchors.length;v++){
for (x = 0;x<rooms.length;x++){
for (let p:number = 0;p<rooms[x].anchorIDs.length;p++){
if (rooms[x].anchorIDs[p] == visibleAnchors[v].addr){
room = rooms[x];
break;
}
}
}
}
/*
for (let m:number=0;m<visiblePoints.length;m++){
basic.showNumber(Math.round(visiblePoints[m].distance));
basic.pause(300);
}
*/
if (room !=null){
// 3. Find all visible points (filtered by device type) in that room
let d:number = 0;
let vp:VisiblePoint = null;
for (x = 0;x<room.points.length;x++){
if (room.points[x].device == device){
if (room.points[x].type == UWBType.ANCHOR){
// Get the anchor's distance, if it's visible
for (let a:number =0; a< visibleAnchors.length;a++){
if (room.points[x].addr == visibleAnchors[a].addr){
d = visibleAnchors[a].distance;
}
}
} else{
//distToSegment(p_x:number,p_y:number, v:SpookyPoint, w:SpookyPoint) { return Math.sqrt(distToSegmentSquared(p_x,p_y, v, w)); }
//distToSegment(p_x:number,p_y:number, v:SpookyPoint, w:SpookyPoint
d = Math.round(distance(pos_x, pos_y, room.points[x].x, room.points[x].y));
}
//TODO find the rogue zero
if (d>0){
// Subtract the radius
if (room.points[x].radius > 0){
d -= room.points[x].radius;
if (d<0){
//Minimum zero
d=0;
}
}
vp = new VisiblePoint(room.points[x],d)
if (visiblePoints == null){
visiblePoints = [vp]
}
visiblePoints.push(vp);
}
}
}
}
}
}
if (visiblePoints !=null){
visiblePoints = visiblePoints.sort(
function (a, b) {
return a.distance - b.distance;
});
}
return visiblePoints;
}
//% block="transmit|message %msg"
export function transmit(msg: string): string {
basic.showLeds(`
. . # . .
. . # . .
. . # . .
. . # . .
. . # . .
`);
basic.pause(300);
basic.showLeds(`
# . # . #
. # # # .
# . # . #
. . # . .
. . # . .
`)
basic.pause(300);
basic.showLeds(`
. . # . .
. . # . .
. . # . .
. . # . .
. . # . .
`);
if (msg == 'TEST') {
return "TEST"
} else {
//sendtopi(msg)
for (let m = 0; m < morse.length; m++) {
if (msg == morse[m]) {
return alphabet[m];
}
}
}
return ""
}
//% block="getLean"
export function getLean(): string {
let z:number = input.rotation(Rotation.Pitch);
let a:number = input.rotation(Rotation.Roll);
let lean:string = "";
if (z >= 15) {
lean = "D";
} else if (z <= -15) {
lean = "U";
} else if (a >= 15) {
lean = "R";
} else if (a <= -15) {
lean = "L";
}
return lean;
}
//%block
export function select() {
selected.push([x, y]);
}
//%block="Move Up"
export function moveup() {
if (notselected(x, y) == true) {
led.unplot(x, y);
}
if (y > 0) {
y += -1;
}
led.plot(x, y);
}
//%block="Move Down"
export function moveDown() {
if (notselected(x, y) == true) {
led.unplot(x, y);
}
if (y < 4) {
y += 1;
}
led.plot(x, y);
}
//%block="Move Left"
export function moveLeft() {
if (notselected(x, y) == true) {
led.unplot(x, y);
}
if (x > 0) {
x += -1;
}
led.plot(x, y);
}
function notselected(x: number, y: number): boolean {
let toggle = true;
for (let s = 0; s < selected.length; s++) {
if (x == selected[s][0] && y == selected[s][1]) {
toggle = false;
break;
}
}
return toggle;
}
//%block="Move Right"
export function moveRight() {
if (notselected(x, y) == true) {
led.unplot(x, y);
}
if (x < 4) {
x += 1;
}
led.plot(x, y);
}
//% block="decode|sign %sign"
export function decode(): string {
//Serialise the screen image into a string
//let screen: Image = led.screenshot();
let msg: string = "?"
let matches: boolean = true
for (let t = 0; t < signs.length; t++) {
matches = true
for (let b = 0; b < 5; b++) {
for (let c = 0; c < 5; c++) {
if (led.point(b, c)) {
if (!signs[t].pixel(b, c)) {
matches = false;
}
} else if (!led.point(b, c)) {
if (signs[t].pixel(b, c)) {
matches = false;
}
}
}
}
if (matches) {
msg = msgs[t]
break;
}
}
selected = [];
x = 2;
y = 2;
return msg;
}
/* ****************************************************************
UWB functions
*/
//% shim=digitalghosthunt::getCurrentNumAnchors
export function getCurrentNumAnchors(): number {
return 0;
}
//% shim=digitalghosthunt::currentAnchorIDAt
function currentAnchorIDAt(index:number):number{
return 0;
}
//% shim=digitalghosthunt::currentAnchorDistanceAt
function currentAnchorDistanceAt(index:number):number{
return 0;
}
//% shim=digitalghosthunt::AnchorDistanceByAddr
function AnchorDistanceByAddr(addr:number){
return -1;
}
//% shim=digitalghosthunt::currentLoc
export function currentLoc():number {
return 0;
}
//% shim=digitalghosthunt::currentPos_x
export function currentPos_x(){
return 0;
}
//% shim=digitalghosthunt::currentPos_y
export function currentPos_y(){
return 0;
}
//% shim=digitalghosthunt::currentPos_z
export function currentPos_z(){
return 0;
}
//% shim=digitalghosthunt::distance
export function distance(ax:number, ay:number, bx:number, by:number):number{
return -1;
}
/**
Nearest anchor this device can see
Distance will be in mm
@return nearest anchor that is visible
*/
export function nearestAnchor(): Anchor{
let anchors:Anchor[] = getAnchors();
if (anchors.length > 0){
return anchors[0];
} else{
return new Anchor(0,0);
}
}
/**
Get all anchors from hardware
*/
function getAnchors(): Anchor[]{
let anchors = [];
let numAnchors = getCurrentNumAnchors();
if (numAnchors > 0){
for (let x=0;x<numAnchors;x++){
anchors[x] = new Anchor(currentAnchorIDAt(x),currentAnchorDistanceAt(x));
}
}
// Sort by distance
if (anchors.length > 0){
anchors.sort(function (a, b) {
return a.distance - b.distance;
});
}
return anchors;
}
/* ***************************************
Pi functions (Deprecated)
Kept for backwards compatibility with Mk 1 SEEK
*/
/*
function sendtopi(code: string) {
serial.writeLine(code);
}
function picommand(command_string: string) {
let command: string = command_string.substr(0, command_string.indexOf("::"));
let value: string = command_string.substr(command_string.indexOf("::") + 2);
switch (command) {
case 'reset':
control.reset()
break;
case 'text':
basic.showString(value)
break;
}
}
// Commands from pi to microbit
serial.onDataReceived("$", function () {
let msg2: string = serial.readUntil("$");
if (msg2.length > 0) {
picommand(msg2);
}
})
*/
// Scan results (done as a listener to avoid timeout)
/* serial.onDataReceived("}", function () {
let msg: string = serial.readUntil("}");
if (msg.length > 0) {
scan_result = parseInt(msg);
}
})*/
/*function getpimessages() {
let msg: string = serial.readLine();
if (msg.length > 0) {
picommand(msg);
}
}*/
}