forked from scartier/blackout
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathblinklib.cpp
More file actions
1465 lines (911 loc) · 48.1 KB
/
blinklib.cpp
File metadata and controls
1465 lines (911 loc) · 48.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
/*
*
* This library lives in userland and acts as a shim to th blinkos layer
*
* This view tailored to be idiomatic Arduino-y. There are probably better views of the interface if you are not an Arduinohead.
*
* In this view, each tile has a "state" that is represented by a number between 1 and 127.
* This state value is continuously broadcast on all of its faces.
* Each tile also remembers the most recently received state value from he neighbor on each of its faces.
*
* You supply setup() and loop().
*
* While in loop(), the world is frozen. All changes you make to the pixels and to data on the faces
* is buffered until loop returns.
*
*/
#include <limits.h>
#include <stdint.h>
#include <avr/pgmspace.h> // PROGMEM for parity lookup table
#include <avr/interrupt.h> // cli() and sei() so we can get snapshots of multibyte variables
#include <avr/sleep.h> // sleep_cpu() so we can rest between interrupts.
#include <avr/wdt.h> // Used in randomize() to get some entropy from the skew between the WDT osicilator and the system clock.
#include <stddef.h>
#include <string.h>
#include "ArduinoTypes.h"
#include "blinklib.h"
// Here are our magic shared memory links to the BlinkBIOS running up in the bootloader area.
// These special sections are defined in a special linker script to make sure that the addresses
// are the same on both the foreground (this blinklib program) and the background (the BlinkBIOS project compiled to a HEX file)
// The actual memory for these blocks is allocated in main.cpp. Remember, it overlaps with the same blocks in BlinkBIOS code running in the bootloader!
#include "shared/blinkbios_shared_button.h"
#include "shared/blinkbios_shared_millis.h"
#include "shared/blinkbios_shared_pixel.h"
#include "shared/blinkbios_shared_irdata.h"
#include "shared/blinkbios_shared_functions.h" // Gets us ir_send_packet()
#define TX_PROBE_TIME_MS 150 // How often to do a blind send when no RX has happened recently to trigger ping pong
// Nice to have probe time shorter than expire time so you have to miss 2 messages
// before the face will expire
#define RX_EXPIRE_TIME_MS 200 // If we do not see a message in this long, then show that face as expired
#define VIRAL_BUTTON_PRESS_LOCKOUT_MS 2000 // Any viral button presses received from IR within this time period are ignored
// since insures that a single press can not circulate around indefinitely.
#define WARM_SLEEP_TIMEOUT_MS ( 10 * 60 * 1000UL ) // 10 mins
// We will warm sleep if we do not see a button press or remote button press
// in this long
// This is a special byte that signals that this is a long data packet
// Note that this is also a value value, but we can tell that it is a data by looking at the IR packet len. Datagrams are always >2 bytes.
// It must appear in the first byte of the data, and the final byte is an inverted checksum of all bytes including this header byte
#define DATAGRAM_SPECIAL_VALUE 0b00101010
// This is a special byte that triggers a warm sleep cycle when received
// It must appear in the first & second byte of data
// When we get it, we virally send out more warm sleep packets on all the faces
// and then we go to warm sleep.
#define TRIGGER_WARM_SLEEP_SPECIAL_VALUE 0b00010101
// This is a special byte that does nothing.
// It must appear in the first & second byte of data.
// We send it when we warm wake to warm wake our neighbors.
#define NOP_SPECIAL_VALUE 0b00110011
// We use bit 6 in the IR data to indicate that a button has been pressed so we should
// postpone sleeping. This spreads a button press to all connected tiles so
// they will stay awake if any tile in the group gets pressed.
// We use bit 7 in the IR data as ODD parity check. We do ODD to make sure at least 1 bit is always
// set (otherwise 0x00 would be 0x00 with parity).
// Assumes ( d < IR_DATA_VALUE_MAX )
#if IR_DATA_VALUE_MAX > 63
#warning The following code assumes that the top two bits of the header byte are available
#endif
// Returns true if odd number of bits set
// TODO: make asm
uint8_t oddParity( uint8_t d ) {
uint8_t bits=0;
while (d) {
if (d & 0b00000001 ) {
bits++;
}
d >>=1;
}
return bits & 0xb00000001;
}
static uint8_t irValueEncode( uint8_t d , uint8_t postponeSleepFlag ) {
if (postponeSleepFlag) {
d |= 0b01000000; // 6th bit button pressed flag
}
if ( !oddParity( d )) {
d |= 0b10000000; // Top bit ODD parity (including postpone sleep flag)
}
return d;
}
static uint8_t irValueCheckValid( uint8_t d ) {
return oddParity( d ); // Odd parity
}
// The actual data is hidden in the middle
static uint8_t irValueDecodeData( uint8_t d ) {
return (d & 0b00111111) ;
}
static uint8_t irValueDecodePostponeSleepFlag( uint8_t d ) {
return d & 0b01000000 ;
}
// TODO: These structs even better if they are padded to a power of 2 like https://stackoverflow.com/questions/1239855/pad-a-c-structure-to-a-power-of-two
#if IR_DATAGRAM_LEN > IR_RX_PACKET_SIZE
#error IR_DATAGRAM_LEN must not be bigger than IR_RX_PACKET_SIZE
#endif
// All semantics chosen to have sane startup 0 so we can
// keep this in bss section and have it zeroed out at startup.
struct face_t {
uint8_t inValue; // Last received value on this face, or 0 if no neighbor ever seen since startup
uint8_t outValue; // Value we send out on this face
millis_t expireTime; // When this face will be considered to be expired (no neighbor there)
millis_t sendTime; // Next time we will transmit on this face (set to 0 every time we get a good message so we ping-pong across the link)
uint8_t inDatagramLen; // 0= No datagram waiting to be read
#if 1
uint8_t inDatagramData[1];
#else
uint8_t inDatagramData[IR_DATAGRAM_LEN];
#endif
uint8_t outDatagramLen; // 0= No datagram waiting to be sent
#if 1
uint8_t outDatagramData[1];
#else
uint8_t outDatagramData[IR_DATAGRAM_LEN];
#endif
};
static face_t faces[FACE_COUNT];
uint8_t viralButtonPressSendOnFaceBitflags; // A 1 here means send the viral button press bit on the next IR packet on this face. Cleared when it gets sent.
Timer viralButtonPressLockoutTimer; // Set each time we send a viral button press to avoid sending getting into a circular loop
// Millis snapshot for this pass though loop
millis_t now;
// Capture time snapshot
// It is 4 bytes long so we cli() so it can not get updated in the middle of us grabbing it
void updateNow() {
cli();
now = blinkbios_millis_block.millis;
sei();
}
unsigned long millis() {
return now;
}
// Returns the inverted checksum of all bytes
uint8_t computePacketChecksum( volatile const uint8_t *buffer , uint8_t len ) {
uint8_t computedChecksum = 0;
for( uint8_t l=0; l < len ; l++ ) {
computedChecksum += *buffer++;
}
return computedChecksum ^ 0xff ;
}
#if ( ( IR_LONG_PACKET_MAX_LEN + 3 ) > IR_RX_PACKET_SIZE )
#error There has to be enough room in the blinkos packet buffer to hold the user packet plus 2 header bytes and one checksum byte
#endif
byte getDatagramLengthOnFace( uint8_t face ) {
return faces[face].inDatagramLen;
}
boolean isDatagramReadyOnFace( uint8_t face ) {
return getDatagramLengthOnFace(face) != 0;
}
const byte *getDatagramOnFace( uint8_t face ) {
return faces[face].inDatagramData;
}
void markDatagramReadOnFace( uint8_t face ) {
faces[face].inDatagramLen = 0;
}
// Jump to the send packet function all way up in the bootloader
uint8_t blinkbios_irdata_send_packet( uint8_t face, const uint8_t *data , uint8_t len ) {
// Call directly into the function in the bootloader. This symbol is resolved by the linker to a
// direct call to the target address.
return BLINKBIOS_IRDATA_SEND_PACKET_VECTOR(face,data,len);
}
#define SBI(x,b) (x|= (1<<b)) // Set bit
#define CBI(x,b) (x&=~(1<<b)) // Clear bit
#define TBI(x,b) (x&(1<<b)) // Test bit
void sendDatagramOnFace( const void *data, byte len , byte face ) {
if ( len > IR_DATAGRAM_LEN ) {
// Ignore request to send oversized packet
return;
}
face_t *f = &faces[face];
f->outDatagramLen = len;
memcpy( f->outDatagramData , data , len );
}
static void clear_packet_buffers() {
FOREACH_FACE(f) {
blinkbios_irdata_block.ir_rx_states[f].packetBufferReady = 0;
}
}
// Set the color and display it immediately
// for internal use where we do not want the loop buffering
static void setColorNow( Color newColor ) {
setColor( newColor );
BLINKBIOS_DISPLAY_PIXEL_BUFFER_VECTOR();
}
Color dim( Color color, byte brightness) {
return MAKECOLOR_5BIT_RGB(
(GET_5BIT_R(color)*brightness)/255,
(GET_5BIT_G(color)*brightness)/255,
(GET_5BIT_B(color)*brightness)/255
);
}
// When will we warm sleep due to inactivity
// reset by a button press or seeing a button press bit on
// an incoming packet
Timer warm_sleep_time;
void reset_warm_sleep_timer() {
warm_sleep_time.set( WARM_SLEEP_TIMEOUT_MS );
}
// Remembers if we have woken from either a BIOS sleep or
// a blinklib forced sleep.
uint8_t hasWarmWokenFlag =0;
// We need to save the pixel buffer when we warm sleep so we display our
// sleep and wake animations and then restore the original game pixels before restarting the game
pixelColor_t savedPixelBuffer[PIXEL_COUNT];
void savePixels() {
// Save game pixels
FOREACH_FACE(f) {
savedPixelBuffer[f] = blinkbios_pixel_block.pixelBuffer[f];
}
}
void restorePixels() {
// Save game pixels
FOREACH_FACE(f) {
blinkbios_pixel_block.pixelBuffer[f] = savedPixelBuffer[f];
}
}
#define SLEEP_ANIMATION_DURATION_MS 300
#define SLEEP_ANIMATION_MAX_BRIGHTNESS 200
// A special warm sleep trigger packet has len 2 and the two bytes are both the special cookie value
// Because it must be 2 long, this means that the cookie can still be a data value since that value would only have a 1 byte packet
static uint8_t force_sleep_packet[2] = { TRIGGER_WARM_SLEEP_SPECIAL_VALUE , TRIGGER_WARM_SLEEP_SPECIAL_VALUE};
// This packet does nothing except wake up our neighbors
static uint8_t nop_wake_packet[2] = { NOP_SPECIAL_VALUE , NOP_SPECIAL_VALUE};
#define SLEEP_PACKET_REPEAT_COUNT 5 // How many times do we send the sleep and wake packets for redunancy?
static void warm_sleep_cycle() {
BLINKBIOS_POSTPONE_SLEEP_VECTOR(); // Postpone cold sleep so we can warm sleep for a while
// The cold sleep will eventually kick in if we
// do not wake from warm sleep in time.
// Save the games pixels so we can restore them on waking
// we need to do this because the sleep and wake animations
// will overwrite whatever is there.
savePixels();
// Ok, now we are virally sending FORCE_SLEEP out on all faces to spread the word
// and the pixels are off so the user is happy and we are saving power.
// First send the force sleep packet out to all our neighbors
// We are indiscriminate, just splat it 5 times everywhere.
// This is a brute force approach to make sure we get though even with collisions
// and long packets in flight.
// We also show a little animation while transmitting the packets
// Figure out how much brightness to animate on each packet
const int animation_fade_step = SLEEP_ANIMATION_MAX_BRIGHTNESS / ( SLEEP_PACKET_REPEAT_COUNT * FACE_COUNT );
uint8_t fade_brightness;
// For the sleep animation we start bright and dim to 0 by the end
// This code picks a start near to SLEEP_ANIMATION_MAX_BRIGHTNESS that makes sure we end up at 0
fade_brightness = SLEEP_ANIMATION_MAX_BRIGHTNESS;
for( uint8_t n=0; n<SLEEP_PACKET_REPEAT_COUNT; n++ ) {
FOREACH_FACE(f) {
setColorNow( makeColorRGB(0, 0, fade_brightness ) );
fade_brightness -= animation_fade_step;
//while ( blinkbios_is_rx_in_progress( f ) ); // Wait to clear to send (no guarantee, but better than just blink sending)
blinkbios_irdata_send_packet( f , force_sleep_packet , sizeof( force_sleep_packet ) ); // Note that we can use sizeof() here becuase the arrayt is explicity uint8_t which is always a byte on AVR
}
}
// Ensure that we end up completely off
setColorNow( OFF );
// We need to save the time now because it will keep ticking while we are in pre-sleep (where were can get
// woken back up by a packet). If we did not save it and then restore it later, then all the user timers
// would be expired when we woke.
// Save the time now so we can go back in time when we wake up
cli();
millis_t save_time = blinkbios_millis_block.millis;
sei();
// OK we now appear asleep
// We are not sending IR so some power savings
// For the next 2 hours will will wait for a wake up signal
// TODO: Make this even more power efficient by sleeping between checks for incoming IR.
blinkbios_button_block.bitflags=0;
// Here is wuld be nice to idle the CPU for a bit of power savings, but there is a potential
// race where the BIOS could put us into deep sleep mode and then our idle would be deep sleep.
// you'd think we could turn of ints and set out mode right before entering idle, but
// we needs ints on to wake form idle on AVR.
clear_packet_buffers(); // Clear out any left over packets that were there when we started this sleep cycle and might trigger us to wake unapropriately
uint8_t saw_packet_flag =0;
// Wait in idle mode until we either see a non-force-sleep packet or a button press or woke.
// Why woke? Because eventually the BIOS will make us powerdown sleep inside this loop
// When that happens, it will take a button press to wake us
blinkbios_button_block.wokeFlag = 1; // // Set to 0 upon waking from sleep
while (!saw_packet_flag && !(blinkbios_button_block.bitflags & BUTTON_BITFLAG_PRESSED) && blinkbios_button_block.wokeFlag) {
// TODO: This sleep mode currently uses about 2mA. We can get that way down by...
// 1. Adding a supporess_display_flag to pixel_block to skip all of the display code when in this mode
// 2. Adding a new_pack_recieved_flag to ir_block so we only scan when there is a new packet
// UPDATE: Tried all that and it only saved like 0.1-0.2mA and added dozens of bytes of code so not worth it.
ir_rx_state_t *ir_rx_state = blinkbios_irdata_block.ir_rx_states;
FOREACH_FACE( f ) {
if (ir_rx_state->packetBufferReady) {
if (ir_rx_state->packetBuffer[1] != TRIGGER_WARM_SLEEP_SPECIAL_VALUE ) {
saw_packet_flag =1;
}
ir_rx_state->packetBufferReady=0;
}
ir_rx_state++;
}
}
cli();
blinkbios_millis_block.millis = save_time;
BLINKBIOS_POSTPONE_SLEEP_VECTOR(); // It is ok top call like this to reset the inactivity timer
sei();
hasWarmWokenFlag = 1; // Remember that we warm slept
reset_warm_sleep_timer();
// Forced sleep mode
// Really need button down detection in bios so we only wake on lift...
// BLINKBIOS_SLEEP_NOW_VECTOR();
// Clear out old packets (including any old FORCE_SLEEP packets so we don't go right back to bed)
clear_packet_buffers();
// Show smooth wake animation
// This loop empirically works out to be about the right delay.
// I know this hardcode is hackyish, but we need to save flash space
// For the wake animation we start off and dim to MAX by the end
// This code picks a start near to SLEEP_ANIMATION_MAX_BRIGHTNESS that makes sure we end up at 0
fade_brightness = 0;
for( uint8_t n=0; n<SLEEP_PACKET_REPEAT_COUNT; n++ ) {
FOREACH_FACE(f) {
// INcrement first - they are already seeing OFF when we start
fade_brightness += animation_fade_step;
setColorNow( makeColorRGB(fade_brightness, fade_brightness, fade_brightness) );
blinkbios_irdata_send_packet( f , nop_wake_packet , sizeof( nop_wake_packet ) ); // Note that we can use sizeof() here becuase the arrayt is explicity uint8_t which is always a byte on AVR
}
}
// restore game pixels
restorePixels();
}
// Called anytime a the button is pressed or anytime we get a viral button press form a neighbor over IR
// Note that we know that this can not become cyclical because of the lockout delay
void viralPostponeWarmSleep() {
if (viralButtonPressLockoutTimer.isExpired()) {
viralButtonPressLockoutTimer.set( VIRAL_BUTTON_PRESS_LOCKOUT_MS );
viralButtonPressSendOnFaceBitflags = IR_FACE_BITMASK;
// Prevent warm sleep
reset_warm_sleep_timer();
}
}
static void RX_IRFaces() {
// Use these pointers to step though the arrays
face_t *face = faces;
volatile ir_rx_state_t *ir_rx_state = blinkbios_irdata_block.ir_rx_states;
for( uint8_t f=0; f < FACE_COUNT ; f++ ) {
// Check for anything new coming in...
if ( ir_rx_state->packetBufferReady ) {
// Got something, so we know there is someone out there
// TODO: Should we require the received packet to pass error checks?
face->expireTime = now + RX_EXPIRE_TIME_MS;
// This is slightly ugly. To save a buffer, we get the full packet with the BlinkBIOS IR packet type byte.
volatile const uint8_t *packetData = (ir_rx_state->packetBuffer);
if ( *packetData++ == IR_USER_DATA_HEADER_BYTE ) { // We only process user data and ignore (and consume) anything else. This is ugly. Sorry.
uint8_t packetDataLen = (ir_rx_state->packetBufferLen)-1; // deduct the BlinkBIOS packet type byte
// blinkBIOS will only pass use packets with len >0
uint8_t irDataFirstByte = *packetData;
if (irValueCheckValid( irDataFirstByte )) {
// If we get here, then we know this is a valid packet
// Clear to send on this face immediately to ping-pong messages at max speed without collisions
face->sendTime = 0;
if (irValueDecodePostponeSleepFlag(irDataFirstByte )) {
// The blink on on the other side of this connection is telling us that a button was pressed recently
// Send the viral message to all neighbors.
viralPostponeWarmSleep();
// We also need to extend hardware sleep
// since we did not get a physical button press
BLINKBIOS_POSTPONE_SLEEP_VECTOR();
}
uint8_t decodedByte = irValueDecodeData( irDataFirstByte );
if ( packetDataLen == 1 ) { // normal user face value, One header byte + One data byte
// We got a face value! Save it!
face->inValue =decodedByte;
} else { // (packetDataLen>1)
if ( decodedByte == DATAGRAM_SPECIAL_VALUE) {
uint8_t datagramPayloadLen = packetDataLen-2; // We deduct 2 from he length to account for the header byte and the trailing checksum byte
const uint8_t *datagramPayloadData = packetData+1; // Skip the packet header byte
// Long packets are kind of a special case since we do not mark them read immediately
if ( computePacketChecksum( datagramPayloadData , datagramPayloadLen ) == datagramPayloadData[ datagramPayloadLen ] ) { // Run checksum on payload bytes after the header, compare that to the checksum at the end
// Ok this packet checks out folks!
if ( face->inDatagramLen == 0 && !(datagramPayloadLen > IR_DATAGRAM_LEN) ) { // Check if buffer free and datagram not too long
face->inDatagramLen = datagramPayloadLen;
memcpy( face->inDatagramData , datagramPayloadData , datagramPayloadLen); // Skip the header bytes
}
}
} else { // packetLen > 1 && decodedByte != LONG_DATA_SPECIAL_VALUE
// Here is look for a magic packet that has 2 bytes of data and both are the special sleep trigger cookie
if ( packetDataLen == 2 && decodedByte == TRIGGER_WARM_SLEEP_SPECIAL_VALUE && packetData[1] == TRIGGER_WARM_SLEEP_SPECIAL_VALUE ) {
warm_sleep_cycle();
blinkbios_button_block.bitflags = 0;
}
} // ( decodedByte == LONG_DATA_SPECIAL_VALUE)
} // (packetDataLen>1)
} else {
// Invalid packet received. No good way to show or log this. :/
//#warning
//setColorNow( RED );
}
}
// No matter what, mark buffer as read so we can get next packet
ir_rx_state->packetBufferReady=0;
} // if ( ir_data_buffer->ready_flag )
face++;
ir_rx_state++;
} // for( uint8_t f=0; f < FACE_COUNT ; f++ )
}
// Buffer to build each outgoing IR packet
// This is the easy way to do this, but uses RAM unnecessarily.
// TODO: Make a scatter version of this to save RAM & time
static uint8_t ir_send_packet_buffer[ IR_DATAGRAM_LEN + 2 ]; // header byte + Datagram payload + checksum byte
static void TX_IRFaces() {
// Use these pointers to step though the arrays
face_t *face = faces;
for( uint8_t f=0; f < FACE_COUNT ; f++ ) {
// Send one out too if it is time....
if ( face->sendTime <= now ) { // Time to send on this face?
// Note that we do not use the rx_fresh flag here because we want the timeout
// to do automatic retries to kickstart things when a new neighbor shows up or
// when an IR message gets missed
uint8_t outgoingPacketLen; // Total length of the outgoing packet in ir_send_packet_buffer
uint8_t outgoiungPacketHeaderValue; // Value to encode into first byte of outgoing IR packet before transmitting
// Ok, it is time to send something on this face
// Do we have a pending datagram? If so, datagrams get priority over face values
if (face->outDatagramLen) {
outgoiungPacketHeaderValue = DATAGRAM_SPECIAL_VALUE;
// Build a datagram into the outgoing buffer including checksum
uint8_t *d = ir_send_packet_buffer+1; // Data goes after the 1st byte header
const uint8_t *s = face->outDatagramData ; // Just to convert from void to uint8_t
uint8_t datagramPayloadLen = face->outDatagramLen;
memcpy( d, s , datagramPayloadLen );
// First header, then payload, when checksum
ir_send_packet_buffer[1+datagramPayloadLen] = computePacketChecksum( s , datagramPayloadLen );
outgoingPacketLen = 1 + datagramPayloadLen +1; // include header byte + payload + checksum (header added below)
// Note that the outgoing datagram buffer will be cleared below if the IR send succeeds
} else {
// Just send a normal face value
outgoiungPacketHeaderValue = face->outValue;
outgoingPacketLen=1;
}
// Encode the header byte with the parity and viral button flag
uint8_t encodedIrValue;
if ( TBI( viralButtonPressSendOnFaceBitflags , f )) {
// We need to send the viral button press on this face right now
encodedIrValue= irValueEncode( outgoiungPacketHeaderValue , 1 );
CBI( viralButtonPressSendOnFaceBitflags , f );
} else {
encodedIrValue= irValueEncode( outgoiungPacketHeaderValue , 0 );
}
ir_send_packet_buffer[0] = encodedIrValue; // store the encoded header into the outgoing buffer
if (blinkbios_irdata_send_packet( f , ir_send_packet_buffer , outgoingPacketLen ) ) {
// Here we set a timeout to keep periodically probing on this face, but
// if there is a neighbor, they will send back to us as soon as they get what we
// just transmitted, which will make us immediately send again. So the only case
// when this probe timeout will happen is if there is no neighbor there.
// If ir_send_userdata() returns 0, then we could not send becuase there was an RX in progress on this face.
// Because we do not reset the sentTime in that case, we will automatically try again next pass.
// We add the face index here to try to spread the sends out in time
// otherwise the degenerate case is that they can all happen repeatedly in the same
// pass thugh loop() every time when there are no neighbors.
face->sendTime = now + TX_PROBE_TIME_MS + f;
// Mark any pending datagram as sent
// safe to do this blindly because datagram always gets priority so it would have been
// what was just sent if there was one pending
face->outDatagramLen = 0;
}
} // if ( face->sendTime <= now )
face++;
} // for( uint8_t f=0; f < FACE_COUNT ; f++ )
}
// Returns the last received state on the indicated face
// Remember that getNeighborState() starts at 0 on powerup.
// so returns 0 if no neighbor ever seen on this face since power-up
// so best to only use after checking if face is not expired first.
// Note the a face expiring has no effect on the getNeighborState()
byte getLastValueReceivedOnFace( byte face ) {
return faces[face].inValue;
}
// Did the neighborState value on this face change since the
// last time we checked?
// Remember that getNeighborState starts at 0 on powerup.
// Note the a face expiring has no effect on the getNeighborState()
byte didValueOnFaceChange( byte face ) {
static byte prevState[FACE_COUNT];
byte curState = getLastValueReceivedOnFace(face);
if ( curState == prevState[face] ) {
return false;
}
prevState[face] = curState;
return true;
}
byte isValueReceivedOnFaceExpired( byte face ) {
return faces[face].expireTime < now;
}
// Returns false if their has been a neighbor seen recently on any face, true otherwise.
bool isAlone() {
FOREACH_FACE(f) {
if( !isValueReceivedOnFaceExpired(f) ) {
return false;
}
}
return true;
}
// Set our broadcasted state on all faces to newState.
// This state is repeatedly broadcast to any neighboring tiles.
// By default we power up in state 0.
void setValueSentOnAllFaces( byte value ) {
if (value > IR_DATA_VALUE_MAX ) {
value = IR_DATA_VALUE_MAX;
}
FOREACH_FACE(f) {
faces[f].outValue = value;
}
}
// Set our broadcasted state on indicated face to newState.
// This state is repeatedly broadcast to the partner tile on the indicated face.
// By default we power up in state 0.
void setValueSentOnFace( byte value , byte face ) {
if (value > IR_DATA_VALUE_MAX ) {
value = IR_DATA_VALUE_MAX;
}
faces[face].outValue = value;
}
// --------------Button code
// Here we keep a local snapshot of the button block stuff
static uint8_t buttonSnapshotDown; // 1 if button is currently down (debounced)
static uint8_t buttonSnapshotBitflags;
static uint8_t buttonSnapshotClickcount; // Number of clicks on most recent multiclick
bool buttonDown(void) {
return buttonSnapshotDown != 0;
}
static bool grabandclearbuttonflag( uint8_t flagbit ) {
bool r = buttonSnapshotBitflags & flagbit;
buttonSnapshotBitflags &= ~ flagbit;
return r;
}
bool buttonPressed(void) {
return grabandclearbuttonflag( BUTTON_BITFLAG_PRESSED );
}
bool buttonReleased(void) {
return grabandclearbuttonflag( BUTTON_BITFLAG_RELEASED );
}
bool buttonSingleClicked() {
return grabandclearbuttonflag( BUTTON_BITFLAG_SINGLECLICKED );
}
bool buttonDoubleClicked() {
return grabandclearbuttonflag( BUTTON_BITFLAG_DOUBLECLICKED );
}
bool buttonMultiClicked() {
return grabandclearbuttonflag( BUTTON_BITFLAG_MULITCLICKED );
}
// The number of clicks in the longest consecutive valid click cycle since the last time called.
byte buttonClickCount(void) {
return buttonSnapshotClickcount;
}
// Remember that a long press fires while the button is still down
bool buttonLongPressed(void) {
return grabandclearbuttonflag( BUTTON_BITFLAG_LONGPRESSED );
}
// 6 second press. Note that this will trigger seed mode if the blink is alone so
// you will only ever see this if blink has neighbors when the button hits the 6 second mark.
// Remember that a long press fires while the button is still down
bool buttonLongLongPressed(void) {
return grabandclearbuttonflag( BUTTON_BITFLAG_3SECPRESSED );
}
// --- Utility functions
Color makeColorRGB( byte red, byte green, byte blue ) {
// Internal color representation is only 5 bits, so we have to divide down from 8 bits
return Color( red >> 3 , green >> 3 , blue >> 3 );
}
Color makeColorHSB( uint8_t hue, uint8_t saturation, uint8_t brightness ) {
uint8_t r;
uint8_t g;
uint8_t b;
if (saturation == 0)
{
// achromatic (grey)
r =g = b= brightness;
}
else
{
unsigned int scaledHue = (hue * 6);
unsigned int sector = scaledHue >> 8; // sector 0 to 5 around the color wheel
unsigned int offsetInSector = scaledHue - (sector << 8); // position within the sector
unsigned int p = (brightness * ( 255 - saturation )) >> 8;
unsigned int q = (brightness * ( 255 - ((saturation * offsetInSector) >> 8) )) >> 8;
unsigned int t = (brightness * ( 255 - ((saturation * ( 255 - offsetInSector )) >> 8) )) >> 8;
switch( sector ) {
case 0:
r = brightness;
g = t;
b = p;
break;
case 1:
r = q;
g = brightness;
b = p;
break;
case 2:
r = p;
g = brightness;
b = t;
break;
case 3:
r = p;
g = q;
b = brightness;
break;
case 4:
r = t;
g = p;
b = brightness;
break;
default: // case 5:
r = brightness;
g = p;
b = q;
break;
}
}
return( makeColorRGB( r , g , b ) );
}
// OMG, the Ardiuno rand() function is just a mod! We at least want a uniform distibution.
// We base our generator on a 32-bit Marsaglia XOR shifter
// https://en.wikipedia.org/wiki/Xorshift
/* The state word must be initialized to non-zero */