a bit smaller
[labortage2013badge.git] / firmware / main.c
1 /* Name: main.c
2  * Project: hid-custom-rq example
3  * Author: Christian Starkjohann
4  * Creation Date: 2008-04-07
5  * Tabsize: 4
6  * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
7  * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
8  * This Revision: $Id: main.c 692 2008-11-07 15:07:40Z cs $
9  */
10
11 /*
12 This example should run on most AVRs with only little changes. No special
13 hardware resources except INT0 are used. You may have to change usbconfig.h for
14 different I/O pins for USB. Please note that USB D+ must be the INT0 pin, or
15 at least be connected to INT0 as well.
16 We assume that an LED is connected to port B bit 0. If you connect it to a
17 different port or bit, change the macros below:
18 */
19 #define LED_PORT_DDR        DDRB
20 #define LED_PORT_OUTPUT     PORTB
21 #define R_BIT            4
22 #define G_BIT            3
23 #define B_BIT            1
24 #define BUTTON_PIN 4
25
26 #include <stdint.h>
27 #include <string.h>
28 #include <stdbool.h>
29
30 #include <avr/io.h>
31 #include <avr/wdt.h>
32 #include <avr/eeprom.h>
33 #include <avr/interrupt.h>  /* for sei() */
34 #include <util/delay.h>     /* for _delay_ms() */
35
36 #include <avr/pgmspace.h>   /* required by usbdrv.h */
37 #include "usbdrv.h"
38 #include "oddebug.h"        /* This is also an example for using debug macros */
39 #include "requests.h"       /* The custom request numbers we use */
40 #include "special_functions.h"
41 #include "hotp.h"
42 #include "percnt2.h"
43
44 /* ------------------------------------------------------------------------- */
45 /* ----------------------------- USB interface ----------------------------- */
46 /* ------------------------------------------------------------------------- */
47 PROGMEM const char usbHidReportDescriptor[USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH] = {
48     0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
49     0x09, 0x06,                    // USAGE (Keyboard)
50     0xa1, 0x01,                    // COLLECTION (Application)
51     0x75, 0x01,                    //   REPORT_SIZE (1)
52     0x95, 0x08,                    //   REPORT_COUNT (8)
53     0x05, 0x07,                    //   USAGE_PAGE (Keyboard)(Key Codes)
54     0x19, 0xe0,                    //   USAGE_MINIMUM (Keyboard LeftControl)(224)
55     0x29, 0xe7,                    //   USAGE_MAXIMUM (Keyboard Right GUI)(231)
56     0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
57     0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
58     0x81, 0x02,                    //   INPUT (Data,Var,Abs) ; Modifier byte
59     0x95, 0x01,                    //   REPORT_COUNT (1)
60     0x75, 0x08,                    //   REPORT_SIZE (8)
61     0x81, 0x03,                    //   INPUT (Cnst,Var,Abs) ; Reserved byte
62     0x95, 0x05,                    //   REPORT_COUNT (5)
63     0x75, 0x01,                    //   REPORT_SIZE (1)
64     0x05, 0x08,                    //   USAGE_PAGE (LEDs)
65     0x19, 0x01,                    //   USAGE_MINIMUM (Num Lock)
66     0x29, 0x05,                    //   USAGE_MAXIMUM (Kana)
67     0x91, 0x02,                    //   OUTPUT (Data,Var,Abs) ; LED report
68     0x95, 0x01,                    //   REPORT_COUNT (1)
69     0x75, 0x03,                    //   REPORT_SIZE (3)
70     0x91, 0x03,                    //   OUTPUT (Cnst,Var,Abs) ; LED report padding
71     0x95, 0x06,                    //   REPORT_COUNT (6)
72     0x75, 0x08,                    //   REPORT_SIZE (8)
73     0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
74     0x25, 0x65,                    //   LOGICAL_MAXIMUM (101)
75     0x05, 0x07,                    //   USAGE_PAGE (Keyboard)(Key Codes)
76     0x19, 0x00,                    //   USAGE_MINIMUM (Reserved (no event indicated))(0)
77     0x29, 0x65,                    //   USAGE_MAXIMUM (Keyboard Application)(101)
78     0x81, 0x00,                    //   INPUT (Data,Ary,Abs)
79     0xc0                           // END_COLLECTION
80 };
81
82 uint16_t secret_length_ee EEMEM = 0;
83 uint8_t  secret_ee[32] EEMEM;
84 uint8_t  reset_counter_ee EEMEM = 0;
85 uint8_t  digits_ee EEMEM = 8;
86
87 /* Keyboard usage values, see usb.org's HID-usage-tables document, chapter
88  * 10 Keyboard/Keypad Page for more codes.
89  */
90 #define MOD_CONTROL_LEFT    (1<<0)
91 #define MOD_SHIFT_LEFT      (1<<1)
92 #define MOD_ALT_LEFT        (1<<2)
93 #define MOD_GUI_LEFT        (1<<3)
94 #define MOD_CONTROL_RIGHT   (1<<4)
95 #define MOD_SHIFT_RIGHT     (1<<5)
96 #define MOD_ALT_RIGHT       (1<<6)
97 #define MOD_GUI_RIGHT       (1<<7)
98
99 #define KEY_A       4
100 #define KEY_B       5
101 #define KEY_C       6
102 #define KEY_D       7
103 #define KEY_E       8
104 #define KEY_F       9
105 #define KEY_G       10
106 #define KEY_H       11
107 #define KEY_I       12
108 #define KEY_J       13
109 #define KEY_K       14
110 #define KEY_L       15
111 #define KEY_M       16
112 #define KEY_N       17
113 #define KEY_O       18
114 #define KEY_P       19
115 #define KEY_Q       20
116 #define KEY_R       21
117 #define KEY_S       22
118 #define KEY_T       23
119 #define KEY_U       24
120 #define KEY_V       25
121 #define KEY_W       26
122 #define KEY_X       27
123 #define KEY_Y       28
124 #define KEY_Z       29
125 #define KEY_1       30
126 #define KEY_2       31
127 #define KEY_3       32
128 #define KEY_4       33
129 #define KEY_5       34
130 #define KEY_6       35
131 #define KEY_7       36
132 #define KEY_8       37
133 #define KEY_9       38
134 #define KEY_0       39
135
136 #define KEY_F1      58
137 #define KEY_F2      59
138 #define KEY_F3      60
139 #define KEY_F4      61
140 #define KEY_F5      62
141 #define KEY_F6      63
142 #define KEY_F7      64
143 #define KEY_F8      65
144 #define KEY_F9      66
145 #define KEY_F10     67
146 #define KEY_F11     68
147 #define KEY_F12     69
148
149 #define NUM_LOCK 1
150 #define CAPS_LOCK 2
151 #define SCROLL_LOCK 4
152
153 static uint8_t dbg_buffer[8];
154
155 static uint8_t secret[32];
156 static uint16_t secret_length_b;
157 static char token[10];
158
159
160 #define UNI_BUFFER_SIZE 36
161
162 static union __attribute__((packed)) {
163         uint8_t  w8[UNI_BUFFER_SIZE];
164         uint16_t w16[UNI_BUFFER_SIZE/2];
165         uint32_t w32[UNI_BUFFER_SIZE/4];
166         void*    ptr[UNI_BUFFER_SIZE/sizeof(void*)];
167 } uni_buffer;
168
169 static uint8_t uni_buffer_fill;
170 static uint8_t current_command;
171
172 typedef struct {
173     uint8_t modifier;
174     uint8_t reserved;
175     uint8_t keycode[6];
176 } keyboard_report_t;
177
178 #define STATE_WAIT 0
179 #define STATE_SEND_KEY 1
180 #define STATE_RELEASE_KEY 2
181 #define STATE_NEXT 3
182
183
184 static keyboard_report_t keyboard_report; // sent to PC
185 static uchar idleRate;           /* in 4 ms units */
186 static uchar key_state = STATE_WAIT;
187 volatile static uchar LED_state = 0xff; // received from PC
188 /* ------------------------------------------------------------------------- */
189
190 static
191 void memory_clean(void) {
192     memset(secret, 0, 32);
193     secret_length_b = 0;
194 }
195
196 static
197 uint8_t secret_set(void){
198     uint8_t r;
199     union {
200         uint8_t w8[32];
201         uint16_t w16[16];
202     } read_back;
203     const uint8_t length_B = (secret_length_b + 7) / 8;
204
205     eeprom_busy_wait();
206     eeprom_write_block(secret, secret_ee, length_B);
207     eeprom_busy_wait();
208     eeprom_read_block(read_back.w8, secret_ee, length_B);
209     r = memcmp(secret, read_back.w8, length_B);
210     memory_clean();
211     memset(read_back.w8, 0, 32);
212     if (r) {
213         return 1;
214     }
215     eeprom_busy_wait();
216     eeprom_write_word(&secret_length_ee, secret_length_b);
217     eeprom_busy_wait();
218     r = eeprom_read_word(&secret_length_ee) == secret_length_b;
219     memory_clean();
220     *read_back.w16 = 0;
221     if (!r) {
222         return 1;
223     }
224     return 0;
225 }
226
227 static
228 void token_generate(void) {
229     percnt_inc(0);
230     eeprom_busy_wait();
231     eeprom_read_block(secret, secret_ee, 32);
232     eeprom_busy_wait();
233     hotp(token, secret, eeprom_read_word(&secret_length_ee), percnt_get(0), eeprom_read_byte(&digits_ee));
234     memory_clean();
235 }
236
237 static
238 void counter_reset(void) {
239     uint8_t reset_counter;
240     eeprom_busy_wait();
241     reset_counter = eeprom_read_byte(&reset_counter_ee);
242     percnt_reset(0);
243     eeprom_busy_wait();
244     eeprom_write_byte(&reset_counter_ee, reset_counter + 1);
245 }
246
247 static
248 void counter_init(void) {
249     eeprom_busy_wait();
250     if (eeprom_read_byte(&reset_counter_ee) == 0) {
251         counter_reset();
252     }
253     percnt_init(0);
254 }
255
256 static
257 void buildReport(uchar send_key) {
258     keyboard_report.modifier = 0;
259
260     switch (send_key) {
261     case 'A' ... 'Z':
262         keyboard_report.modifier = MOD_SHIFT_LEFT;
263         keyboard_report.keycode[0] = KEY_A + (send_key-'A');
264         break;
265     case 'a' ... 'z':
266         keyboard_report.keycode[0] = KEY_A + (send_key-'a');
267         break;
268     case '1' ... '9':
269         keyboard_report.keycode[0] = KEY_1 + (send_key-'1');
270         break;
271     case '0':
272         keyboard_report.keycode[0] = KEY_0;
273         break;
274     default:
275         keyboard_report.keycode[0] = 0;
276     }
277 }
278
279 static
280 int8_t button_get_debounced(volatile uint8_t debounce_count) {
281     uint8_t v;
282     v = PINB & _BV(BUTTON_PIN);
283     while (debounce_count-- && v == (PINB & _BV(BUTTON_PIN))) {
284         ;
285     }
286     if (debounce_count) {
287         return -1;
288     }
289     return v ? 0 : 1;
290 }
291
292 static
293 void init_temperature_sensor(void){
294         ADMUX = 0x8F;
295         ADCSRA = 0x87;
296 }
297
298 static
299 uint16_t read_temperture_sensor(void){
300         ADCSRA |= 0x40;
301         while(ADCSRA & 0x40)
302                 ;
303         return ADC;
304 }
305
306 usbMsgLen_t usbFunctionSetup(uchar data[8])
307 {
308         usbRequest_t    *rq = (usbRequest_t *)data;
309         if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) {    /* class request type */
310             switch(rq->bRequest) {
311         case USBRQ_HID_GET_REPORT: // send "no keys pressed" if asked here
312             // wValue: ReportType (highbyte), ReportID (lowbyte)
313             usbMsgPtr = (void *)&keyboard_report; // we only have this one
314             keyboard_report.modifier = 0;
315             keyboard_report.keycode[0] = 0;
316             return sizeof(keyboard_report);
317         case USBRQ_HID_SET_REPORT: // if wLength == 1, should be LED state
318             if (rq->wLength.word == 1) {
319                 current_command = LED_WRITE;
320                 return USB_NO_MSG;
321             }
322             return 0;
323         case USBRQ_HID_GET_IDLE: // send idle rate to PC as required by spec
324             usbMsgPtr = &idleRate;
325             return 1;
326         case USBRQ_HID_SET_IDLE: // save idle rate as required by spec
327             idleRate = rq->wValue.bytes[1];
328             return 0;
329         }
330     }
331     if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
332                 current_command = rq->bRequest;
333         switch(rq->bRequest)
334                 {
335         case CUSTOM_RQ_SET_SECRET:
336             secret_length_b = rq->wValue.word;
337             if (secret_length_b > 256) {
338                 secret_length_b = 256;
339             }
340             uni_buffer.w8[0] = 0;
341             return USB_NO_MSG;
342         case CUSTOM_RQ_INC_COUNTER:
343             percnt_inc(0);
344             return 0;
345         case CUSTOM_RQ_GET_COUNTER:
346             uni_buffer.w32[0] = percnt_get(0);
347             usbMsgPtr = (usbMsgPtr_t)uni_buffer.w32;
348             return 4;
349         case CUSTOM_RQ_RESET_COUNTER:
350             counter_reset();
351             return 0;
352         case CUSTOM_RQ_GET_RESET_COUNTER:
353             eeprom_busy_wait();
354             uni_buffer.w8[0] = eeprom_read_byte(&reset_counter_ee);
355             usbMsgPtr = uni_buffer.w8;
356             return 1;
357         case CUSTOM_RQ_SET_DIGITS:
358             if (rq->wValue.bytes[0] > 9) {
359                 rq->wValue.bytes[0] = 9;
360             }
361             eeprom_busy_wait();
362             eeprom_write_byte(&digits_ee, rq->wValue.bytes[0]);
363             return 0;
364         case CUSTOM_RQ_GET_DIGITS:
365             eeprom_busy_wait();
366             uni_buffer.w8[0] = eeprom_read_byte(&digits_ee);
367             usbMsgPtr = uni_buffer.w8;
368             return 1;
369         case CUSTOM_RQ_GET_TOKEN:
370             token_generate();
371             usbMsgPtr = (usbMsgPtr_t)token;
372             return strlen(token);
373
374         case CUSTOM_RQ_PRESS_BUTTON:
375             key_state = STATE_SEND_KEY;
376             return 0;
377         case CUSTOM_RQ_CLR_DBG:
378             memset(dbg_buffer, 0, sizeof(dbg_buffer));
379             return 0;
380                 case CUSTOM_RQ_SET_DBG:
381                         return USB_NO_MSG;
382                 case CUSTOM_RQ_GET_DBG:{
383                         usbMsgLen_t len = 8;
384                         if(len > rq->wLength.word){
385                                 len = rq->wLength.word;
386                         }
387                         usbMsgPtr = dbg_buffer;
388                         return len;
389                 }
390                 case CUSTOM_RQ_READ_MEM:
391                         usbMsgPtr = (uchar*)rq->wValue.word;
392                         return rq->wLength.word;
393                 case CUSTOM_RQ_WRITE_MEM:
394                 case CUSTOM_RQ_EXEC_SPM:
395 /*                      uni_buffer_fill = 4;
396                         uni_buffer.w16[0] = rq->wValue.word;
397                         uni_buffer.w16[1] = rq->wLength.word;
398                         return USB_NO_MSG;
399 */              case CUSTOM_RQ_READ_FLASH:
400                         uni_buffer.w16[0] = rq->wValue.word;
401                         uni_buffer.w16[1] = rq->wLength.word;
402             uni_buffer_fill = 4;
403                         return USB_NO_MSG;
404                 case CUSTOM_RQ_RESET:
405                         soft_reset((uint8_t)(rq->wValue.word));
406                         break;
407                 case CUSTOM_RQ_READ_BUTTON:
408                         uni_buffer.w8[0] = button_get_debounced(25);
409                         usbMsgPtr = uni_buffer.w8;
410                         return 1;
411                 case CUSTOM_RQ_READ_TMPSENS:
412                         uni_buffer.w16[0] = read_temperture_sensor();
413                         usbMsgPtr = uni_buffer.w8;
414                         return 2;
415                 }
416     }
417
418     return 0;   /* default for not implemented requests: return no data back to host */
419 }
420
421
422 uchar usbFunctionWrite(uchar *data, uchar len)
423 {
424         switch(current_command){
425
426         case LED_WRITE:
427             if (data[0] != LED_state)
428                 LED_state = data[0];
429             return 1; // Data read, not expecting more
430         case CUSTOM_RQ_SET_SECRET:
431         {
432             if (uni_buffer.w8[0] < (secret_length_b + 7) / 8) {
433                 memcpy(&secret[uni_buffer.w8[0]], data, len);
434                 uni_buffer.w8[0] += len;
435             }
436             if (uni_buffer.w8[0] >= (secret_length_b + 7) / 8) {
437                 secret_set();
438                 return 1;
439             }
440             return 0;
441         }
442         case CUSTOM_RQ_SET_DBG:
443                 if(len > sizeof(dbg_buffer)){
444                         len = sizeof(dbg_buffer);
445                 }
446                 memcpy(dbg_buffer, data, len);
447                 return 1;
448         case CUSTOM_RQ_WRITE_MEM:
449                 memcpy(uni_buffer.ptr[0], data, len);
450                 uni_buffer.w16[0] += len;
451                 return !(uni_buffer.w16[1] -= len);
452         case CUSTOM_RQ_EXEC_SPM:
453                 if(uni_buffer_fill < 8){
454                         uint8_t l = 8 - uni_buffer_fill;
455                         if(len<l){
456                                 len = l;
457                         }
458                         memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
459                         uni_buffer_fill += len;
460                         return 0;
461                 }
462                 uni_buffer.w16[1] -= len;
463                 if (uni_buffer.w16[1] > 8) {
464                         memcpy(uni_buffer.ptr[0], data, len);
465                         uni_buffer.w16[0] += len;
466                         return 0;
467                 } else {
468                         memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
469                         exec_spm(uni_buffer.w16[2], uni_buffer.w16[3], uni_buffer.ptr[0], data, len);
470                         return 1;
471                 }
472         default:
473                 return 1;
474         }
475         return 0;
476 }
477 uchar usbFunctionRead(uchar *data, uchar len){
478         uchar ret = len;
479         switch(current_command){
480         case CUSTOM_RQ_READ_FLASH:
481                 while(len--){
482                         *data++ = pgm_read_byte((uni_buffer.w16[0])++);
483                 }
484                 return ret;
485         default:
486                 break;
487         }
488         return 0;
489 }
490
491 static void calibrateOscillator(void)
492 {
493 uchar       step = 128;
494 uchar       trialValue = 0, optimumValue;
495 int         x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
496  
497     /* do a binary search: */
498     do {
499         OSCCAL = trialValue + step;
500         x = usbMeasureFrameLength();    // proportional to current real frequency
501         if(x < targetValue)             // frequency still too low
502             trialValue += step;
503         step >>= 1;
504     } while(step > 0);
505     /* We have a precision of +/- 1 for optimum OSCCAL here */
506     /* now do a neighborhood search for optimum value */
507     optimumValue = trialValue;
508     optimumDev = x; // this is certainly far away from optimum
509     for (OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
510         x = usbMeasureFrameLength() - targetValue;
511         if (x < 0)
512             x = -x;
513         if (x < optimumDev) {
514             optimumDev = x;
515             optimumValue = OSCCAL;
516         }
517     }
518     OSCCAL = optimumValue;
519 }
520  
521
522 void usbEventResetReady(void)
523 {
524     cli();  // usbMeasureFrameLength() counts CPU cycles, so disable interrupts.
525     calibrateOscillator();
526     sei();
527 // we never read the value from eeprom so this causes only degradation of eeprom
528 //    eeprom_write_byte(0, OSCCAL);   // store the calibrated value in EEPROM
529 }
530
531 /* ------------------------------------------------------------------------- */
532
533 int main(void)
534 {
535         size_t idx = 0;
536         int8_t i = 0, last_stable_button_state = 0;
537
538     wdt_enable(WDTO_1S);
539     /* Even if you don't use the watchdog, turn it off here. On newer devices,
540      * the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
541      */
542     /* RESET status: all port bits are inputs without pull-up.
543      * That's the way we need D+ and D-. Therefore we don't need any
544      * additional hardware initialization.
545      */
546
547     DDRB &= ~_BV(BUTTON_PIN); /* make button pin input */
548     PORTB |= _BV(BUTTON_PIN); /* turn on pull-up resistor */
549     init_temperature_sensor();
550     usbInit();
551     usbDeviceDisconnect();  /* enforce re-enumeration, do this while interrupts are disabled! */
552     while(--i){             /* fake USB disconnect for ~512 ms */
553         wdt_reset();
554         _delay_ms(2);
555     }
556     usbDeviceConnect();
557         
558     sei();
559
560     for(;;){                /* main event loop */
561         wdt_reset();
562         usbPoll();
563
564         i = button_get_debounced(25);
565         if (i != -1) {
566             if (last_stable_button_state == 0 && i == 1) {
567                 key_state = STATE_SEND_KEY;
568             }
569             last_stable_button_state = i;
570         }
571
572         if(usbInterruptIsReady() && key_state != STATE_WAIT){
573             switch(key_state) {
574             case STATE_SEND_KEY:
575                 buildReport(token[idx]);
576                 key_state = STATE_RELEASE_KEY; // release next
577                 break;
578             case STATE_RELEASE_KEY:
579                 buildReport(0);
580                 ++idx;
581                 if (token[idx] == '\0') {
582                     idx = 0;
583                     key_state = STATE_WAIT;
584                 } else {
585                     key_state = STATE_SEND_KEY;
586                 }
587                 break;
588             default:
589                 key_state = STATE_WAIT; // should not happen
590             }
591                         // start sending
592             usbSetInterrupt((void *)&keyboard_report, sizeof(keyboard_report));
593
594         }
595
596     }
597     return 0;
598 }
599
600 /* ------------------------------------------------------------------------- */