54476a0e7a1ad143a0f53c42392f12421fa41d08
[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 current_command;
111
112 typedef struct {
113     uint8_t modifier;
114     uint8_t reserved;
115     uint8_t keycode[6];
116 } keyboard_report_t;
117
118 static keyboard_report_t keyboard_report; /* report sent to the host */
119 static uchar idleRate;  /* in 4 ms units */
120 static uchar key_state = STATE_WAIT;
121 volatile static uchar LED_state = 0xff;
122 /* ------------------------------------------------------------------------- */
123
124 static
125 void memory_clean(void) {
126     memset(secret, 0, 32);
127     secret_length_b = 0;
128 }
129
130 #define NO_CHECK 1
131
132 static
133 uint8_t secret_set(void){
134 #if !NO_CHECK
135     uint8_t r;
136     union {
137         uint8_t w8[32];
138         uint16_t w16[16];
139     } read_back;
140 #endif
141     const uint8_t length_B = (secret_length_b + 7) / 8;
142
143     eeprom_busy_wait();
144     eeprom_write_block(secret, secret_ee, length_B);
145 #if !NO_CHECK
146     eeprom_busy_wait();
147     eeprom_read_block(read_back.w8, secret_ee, length_B);
148     r = memcmp(secret, read_back.w8, length_B);
149     memory_clean();
150     memset(read_back.w8, 0, 32);
151     if (r) {
152         return 1;
153     }
154 #endif
155     eeprom_busy_wait();
156     eeprom_write_word(&secret_length_ee, secret_length_b);
157 #if !NO_CHECK
158     eeprom_busy_wait();
159     r = eeprom_read_word(&secret_length_ee) == secret_length_b;
160     memory_clean();
161     *read_back.w16 = 0;
162     if (!r) {
163         return 1;
164     }
165 #else
166     memory_clean();
167 #endif
168
169     return 0;
170 }
171
172 static
173 void counter_inc(void){
174 #if SIMPLE_COUNTER
175     uint32_t t;
176     eeprom_busy_wait();
177     t = eeprom_read_dword(&counter_ee);
178     eeprom_busy_wait();
179     eeprom_write_dword(&counter_ee, t + 1);
180 #else
181     percnt_inc(0);
182 #endif
183 }
184
185 static
186 void counter_reset(void) {
187     uint8_t reset_counter;
188     eeprom_busy_wait();
189     reset_counter = eeprom_read_byte(&reset_counter_ee);
190 #if SIMPLE_COUNTER
191     eeprom_busy_wait();
192     eeprom_write_dword(&counter_ee, 0);
193 #else
194     percnt_reset(0);
195 #endif
196     eeprom_busy_wait();
197     eeprom_write_byte(&reset_counter_ee, reset_counter + 1);
198 }
199
200 static
201 void counter_init(void) {
202 #if !SIMPLE_COUNTER
203     eeprom_busy_wait();
204     if (eeprom_read_byte(&reset_counter_ee) == 0) {
205         counter_reset();
206     }
207     percnt_init(0);
208 #endif
209 }
210
211 static
212 void token_generate(void) {
213     counter_inc();
214     eeprom_busy_wait();
215     eeprom_read_block(secret, secret_ee, 32);
216     eeprom_busy_wait();
217 #if SIMPLE_COUNTER
218     hotp(token, secret, eeprom_read_word(&secret_length_ee), eeprom_read_dword(&counter_ee), eeprom_read_byte(&digits_ee));
219 #else
220     hotp(token, secret, eeprom_read_word(&secret_length_ee), percnt_get(0), eeprom_read_byte(&digits_ee));
221 #endif
222     memory_clean();
223 }
224
225
226 static
227 void buildReport(uchar send_key) {
228     keyboard_report.modifier = 0;
229
230     switch (send_key) {
231     case '1' ... '9':
232         keyboard_report.keycode[0] = KEY_1 + (send_key-'1');
233         break;
234     case '0':
235         keyboard_report.keycode[0] = KEY_0;
236         break;
237     default:
238         keyboard_report.keycode[0] = 0;
239     }
240 }
241
242 static
243 int8_t button_get_debounced(volatile uint8_t debounce_count) {
244     uint8_t v;
245     v = PINB & _BV(BUTTON_PIN);
246     while (debounce_count-- && v == (PINB & _BV(BUTTON_PIN))) {
247         ;
248     }
249     if (debounce_count) {
250         return -1;
251     }
252     return v ? 0 : 1;
253 }
254
255 usbMsgLen_t usbFunctionSetup(uchar data[8])
256 {
257         usbRequest_t    *rq = (usbRequest_t *)data;
258         if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) {    /* class request type */
259             switch(rq->bRequest) {
260         case USBRQ_HID_GET_REPORT: /* send "no keys pressed" if asked here */
261             /* wValue: ReportType (highbyte), ReportID (lowbyte) */
262             usbMsgPtr = (void *)&keyboard_report; /* we only have this one */
263             keyboard_report.modifier = 0;
264             keyboard_report.keycode[0] = 0;
265             return sizeof(keyboard_report);
266         case USBRQ_HID_SET_REPORT: /* if wLength == 1, should be LED state */
267             if (rq->wLength.word == 1) {
268                 current_command = LED_WRITE;
269                 return USB_NO_MSG;
270             }
271             return 0;
272         case USBRQ_HID_GET_IDLE: /* send idle rate to PC as required by spec */
273             usbMsgPtr = &idleRate;
274             return 1;
275         case USBRQ_HID_SET_IDLE: /* save idle rate as required by spec */
276             idleRate = rq->wValue.bytes[1];
277             return 0;
278         }
279     }
280     if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
281                 current_command = rq->bRequest;
282         usbMsgPtr = uni_buffer.w8;
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             return 4;
303         case CUSTOM_RQ_RESET_COUNTER:
304             counter_reset();
305             return 0;
306         case CUSTOM_RQ_GET_RESET_COUNTER:
307             eeprom_busy_wait();
308             uni_buffer.w8[0] = eeprom_read_byte(&reset_counter_ee);
309             return 1;
310         case CUSTOM_RQ_SET_DIGITS:
311             if (rq->wValue.bytes[0] > 9) {
312                 rq->wValue.bytes[0] = 9;
313             }
314             eeprom_busy_wait();
315             eeprom_write_byte(&digits_ee, rq->wValue.bytes[0]);
316             return 0;
317         case CUSTOM_RQ_GET_DIGITS:
318             eeprom_busy_wait();
319             uni_buffer.w8[0] = eeprom_read_byte(&digits_ee);
320             return 1;
321         case CUSTOM_RQ_GET_TOKEN:
322             token_generate();
323             usbMsgPtr = (usbMsgPtr_t)token;
324             return strlen(token);
325         case CUSTOM_RQ_PRESS_BUTTON:
326             key_state = STATE_SEND_KEY;
327             return 0;
328         case CUSTOM_RQ_CLR_DBG:
329             memset(dbg_buffer, 0, sizeof(dbg_buffer));
330             return 0;
331                 case CUSTOM_RQ_SET_DBG:
332                         return USB_NO_MSG;
333                 case CUSTOM_RQ_GET_DBG:{
334                         usbMsgLen_t len = 8;
335                         if(len > rq->wLength.word){
336                                 len = rq->wLength.word;
337                         }
338                         usbMsgPtr = dbg_buffer;
339                         return len;
340                 }
341                 case CUSTOM_RQ_RESET:
342                         soft_reset((uint8_t)(rq->wValue.word));
343                         break;
344                 case CUSTOM_RQ_READ_BUTTON:
345                         uni_buffer.w8[0] = button_get_debounced(25);
346                         return 1;
347                 }
348     }
349
350     return 0;   /* default for not implemented requests: return no data back to host */
351 }
352
353
354 uchar usbFunctionWrite(uchar *data, uchar len)
355 {
356         switch(current_command){
357
358         case LED_WRITE:
359             if (data[0] != LED_state)
360                 LED_state = data[0];
361             return 1; /* Data read, not expecting more */
362         case CUSTOM_RQ_SET_SECRET:
363         {
364             if (uni_buffer.w8[0] < (secret_length_b + 7) / 8) {
365                 memcpy(&secret[uni_buffer.w8[0]], data, len);
366                 uni_buffer.w8[0] += len;
367             }
368             if (uni_buffer.w8[0] >= (secret_length_b + 7) / 8) {
369                 secret_set();
370                 return 1;
371             }
372             return 0;
373         }
374         case CUSTOM_RQ_SET_DBG:
375                 if(len > sizeof(dbg_buffer)){
376                         len = sizeof(dbg_buffer);
377                 }
378                 memcpy(dbg_buffer, data, len);
379                 return 1;
380         default:
381                 return 1;
382         }
383         return 0;
384 }
385 uchar usbFunctionRead(uchar *data, uchar len){
386         return 0;
387 }
388
389 static void calibrateOscillator(void)
390 {
391 uchar       step = 128;
392 uchar       trialValue = 0, optimumValue;
393 int         x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
394  
395     /* do a binary search: */
396     do {
397         OSCCAL = trialValue + step;
398         x = usbMeasureFrameLength();    /* proportional to current real frequency */
399         if(x < targetValue)             /* frequency still too low */
400             trialValue += step;
401         step >>= 1;
402     } while(step > 0);
403     /* We have a precision of +/- 1 for optimum OSCCAL here */
404     /* now do a neighborhood search for optimum value */
405     optimumValue = trialValue;
406     optimumDev = x; /* this is certainly far away from optimum */
407     for (OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
408         x = usbMeasureFrameLength() - targetValue;
409         if (x < 0)
410             x = -x;
411         if (x < optimumDev) {
412             optimumDev = x;
413             optimumValue = OSCCAL;
414         }
415     }
416     OSCCAL = optimumValue;
417 }
418  
419
420 void usbEventResetReady(void)
421 {
422     cli();  /* usbMeasureFrameLength() counts CPU cycles, so disable interrupts. */
423     calibrateOscillator();
424     sei();
425 }
426
427 /* ------------------------------------------------------------------------- */
428
429 int main(void)
430 {
431         size_t idx = 0;
432         int8_t i = 0, last_stable_button_state = 0;
433
434     wdt_enable(WDTO_1S);
435     /* Even if you don't use the watchdog, turn it off here. On newer devices,
436      * the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
437      */
438     /* RESET status: all port bits are inputs without pull-up.
439      * That's the way we need D+ and D-. Therefore we don't need any
440      * additional hardware initialization.
441      */
442
443     DDRB &= ~_BV(BUTTON_PIN); /* make button pin input */
444     PORTB |= _BV(BUTTON_PIN); /* turn on pull-up resistor */
445     counter_init();
446     usbInit();
447     usbDeviceDisconnect();  /* enforce re-enumeration, do this while interrupts are disabled! */
448     while(--i){             /* fake USB disconnect for ~512 ms */
449         wdt_reset();
450         _delay_ms(2);
451     }
452     usbDeviceConnect();
453         
454     sei();
455
456     for(;;){                /* main event loop */
457         wdt_reset();
458         usbPoll();
459
460         i = button_get_debounced(25);
461         if (i != -1) {
462             if (last_stable_button_state == 0 && i == 1) {
463                 key_state = STATE_SEND_KEY;
464             }
465             last_stable_button_state = i;
466         }
467
468         if(usbInterruptIsReady() && key_state != STATE_WAIT){
469             switch(key_state) {
470             case STATE_SEND_KEY:
471                 buildReport(token[idx]);
472                 key_state = STATE_RELEASE_KEY; /* release next */
473                 break;
474             case STATE_RELEASE_KEY:
475                 buildReport(0);
476                 ++idx;
477                 if (token[idx] == '\0') {
478                     idx = 0;
479                     key_state = STATE_WAIT;
480                 } else {
481                     key_state = STATE_SEND_KEY;
482                 }
483                 break;
484             default:
485                 key_state = STATE_WAIT; /* should not happen */
486             }
487                         /* start sending */
488             usbSetInterrupt((void *)&keyboard_report, sizeof(keyboard_report));
489
490         }
491
492     }
493     return 0;
494 }
495
496 /* ------------------------------------------------------------------------- */