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