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