]> git.cryptolib.org Git - labortage2013badge.git/blob - firmware/main.c
45026555b0d114f4ee6fa650345ab83b56b08759
[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 {
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 void memory_clean(void) {
191     memset(secret, 0, 32);
192     secret_length_b = 0;
193 }
194
195 uint8_t secret_set(void){
196     uint8_t r;
197     union {
198         uint8_t w8[32];
199         uint16_t w16[16];
200     } read_back;
201     const uint8_t length_B = (secret_length_b + 7) / 8;
202
203     eeprom_busy_wait();
204     eeprom_write_block(secret, secret_ee, length_B);
205     eeprom_busy_wait();
206     eeprom_read_block(read_back.w8, secret_ee, length_B);
207     r = memcmp(secret, read_back.w8, length_B);
208     memory_clean();
209     memset(read_back.w8, 0, 32);
210     if (r) {
211         return 1;
212     }
213     eeprom_busy_wait();
214     eeprom_write_word(&secret_length_ee, secret_length_b);
215     eeprom_busy_wait();
216     r = eeprom_read_word(&secret_length_ee) == secret_length_b;
217     memory_clean();
218     *read_back.w16 = 0;
219     if (!r) {
220         return 1;
221     }
222     return 0;
223 }
224
225 void token_generate(void) {
226     percnt_inc(0);
227     eeprom_busy_wait();
228     eeprom_read_block(secret, secret_ee, 32);
229     eeprom_busy_wait();
230     hotp(token, secret, eeprom_read_word(&secret_length_ee), percnt_get(0), eeprom_read_byte(&digits_ee));
231     memory_clean();
232 }
233
234 void counter_reset(void) {
235     uint8_t reset_counter;
236     eeprom_busy_wait();
237     reset_counter = eeprom_read_byte(&reset_counter_ee);
238     percnt_reset(0);
239     eeprom_busy_wait();
240     eeprom_write_byte(&reset_counter_ee, reset_counter + 1);
241 }
242
243 void counter_init(void) {
244     eeprom_busy_wait();
245     if (eeprom_read_byte(&reset_counter_ee) == 0) {
246         counter_reset();
247     }
248     percnt_init(0);
249 }
250
251 void buildReport(uchar send_key) {
252     keyboard_report.modifier = 0;
253
254     switch (send_key) {
255     case 'A' ... 'Z':
256         keyboard_report.modifier = MOD_SHIFT_LEFT;
257         keyboard_report.keycode[0] = KEY_A + (send_key-'A');
258         break;
259     case 'a' ... 'z':
260         keyboard_report.keycode[0] = KEY_A + (send_key-'a');
261         break;
262     case '1' ... '9':
263         keyboard_report.keycode[0] = KEY_1 + (send_key-'1');
264         break;
265     case '0':
266         keyboard_report.keycode[0] = KEY_0;
267         break;
268     default:
269         keyboard_report.keycode[0] = 0;
270     }
271 }
272
273 uint8_t read_button(void){
274         uint8_t t,v=0;
275         t = DDRB;
276         DDRB &= ~(1<<BUTTON_PIN);
277         PORTB |= 1<<BUTTON_PIN;
278         PORTB &= ~(1<<BUTTON_PIN);
279         v |= PINB;
280         DDRB |= t&(1<<BUTTON_PIN);
281         PORTB &= ~(t&(1<<BUTTON_PIN));
282         v >>= BUTTON_PIN;
283         v &= 1;
284         v ^= 1;
285         return v;
286 }
287
288 void init_temperature_sensor(void){
289         ADMUX = 0x8F;
290         ADCSRA = 0x87;
291 }
292
293 uint16_t read_temperture_sensor(void){
294         ADCSRA |= 0x40;
295         while(ADCSRA & 0x40)
296                 ;
297         return ADC;
298 }
299
300 usbMsgLen_t usbFunctionSetup(uchar data[8])
301 {
302         usbRequest_t    *rq = (usbRequest_t *)data;
303         if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) {    /* class request type */
304             switch(rq->bRequest) {
305         case USBRQ_HID_GET_REPORT: // send "no keys pressed" if asked here
306             // wValue: ReportType (highbyte), ReportID (lowbyte)
307             usbMsgPtr = (void *)&keyboard_report; // we only have this one
308             keyboard_report.modifier = 0;
309             keyboard_report.keycode[0] = 0;
310             return sizeof(keyboard_report);
311         case USBRQ_HID_SET_REPORT: // if wLength == 1, should be LED state
312             if (rq->wLength.word == 1) {
313                 current_command = LED_WRITE;
314                 return USB_NO_MSG;
315             }
316             return 0;
317         case USBRQ_HID_GET_IDLE: // send idle rate to PC as required by spec
318             usbMsgPtr = &idleRate;
319             return 1;
320         case USBRQ_HID_SET_IDLE: // save idle rate as required by spec
321             idleRate = rq->wValue.bytes[1];
322             return 0;
323         }
324     }
325     if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
326                 current_command = rq->bRequest;
327         switch(rq->bRequest)
328                 {
329         case CUSTOM_RQ_SET_SECRET:
330             secret_length_b = rq->wValue.word;
331             if (secret_length_b > 256) {
332                 secret_length_b = 256;
333             }
334             uni_buffer.w8[0] = 0;
335             return USB_NO_MSG;
336         case CUSTOM_RQ_INC_COUNTER:
337             percnt_inc(0);
338             return 0;
339         case CUSTOM_RQ_GET_COUNTER:
340             uni_buffer.w32[0] = percnt_get(0);
341             usbMsgPtr = (usbMsgPtr_t)uni_buffer.w32;
342             return 4;
343         case CUSTOM_RQ_RESET_COUNTER:
344             counter_reset();
345             return 0;
346         case CUSTOM_RQ_GET_RESET_COUNTER:
347             eeprom_busy_wait();
348             uni_buffer.w8[0] = eeprom_read_byte(&reset_counter_ee);
349             usbMsgPtr = uni_buffer.w8;
350             return 1;
351         case CUSTOM_RQ_SET_DIGITS:
352             if (rq->wValue.bytes[0] > 9) {
353                 rq->wValue.bytes[0] = 9;
354             }
355             eeprom_busy_wait();
356             eeprom_write_byte(&digits_ee, rq->wValue.bytes[0]);
357             return 0;
358         case CUSTOM_RQ_GET_DIGITS:
359             eeprom_busy_wait();
360             uni_buffer.w8[0] = eeprom_read_byte(&digits_ee);
361             usbMsgPtr = uni_buffer.w8;
362             return 1;
363         case CUSTOM_RQ_GET_TOKEN:
364             token_generate();
365             usbMsgPtr = token;
366             return strlen(token);
367
368         case CUSTOM_RQ_PRESS_BUTTON:
369             key_state = STATE_SEND_KEY;
370             return 0;
371         case CUSTOM_RQ_CLR_DBG:
372             memset(dbg_buffer, 0, sizeof(dbg_buffer));
373             return 0;
374                 case CUSTOM_RQ_SET_DBG:
375                         return USB_NO_MSG;
376                 case CUSTOM_RQ_GET_DBG:{
377                         usbMsgLen_t len = 8;
378                         if(len > rq->wLength.word){
379                                 len = rq->wLength.word;
380                         }
381                         usbMsgPtr = dbg_buffer;
382                         return len;
383                 }
384                 case CUSTOM_RQ_READ_MEM:
385                         usbMsgPtr = (uchar*)rq->wValue.word;
386                         return rq->wLength.word;
387                 case CUSTOM_RQ_WRITE_MEM:
388                 case CUSTOM_RQ_EXEC_SPM:
389 /*                      uni_buffer_fill = 4;
390                         uni_buffer.w16[0] = rq->wValue.word;
391                         uni_buffer.w16[1] = rq->wLength.word;
392                         return USB_NO_MSG;
393 */              case CUSTOM_RQ_READ_FLASH:
394                         uni_buffer.w16[0] = rq->wValue.word;
395                         uni_buffer.w16[1] = rq->wLength.word;
396             uni_buffer_fill = 4;
397                         return USB_NO_MSG;
398                 case CUSTOM_RQ_RESET:
399                         soft_reset((uint8_t)(rq->wValue.word));
400                         break;
401                 case CUSTOM_RQ_READ_BUTTON:
402                         uni_buffer.w8[0] = read_button();
403                         usbMsgPtr = uni_buffer.w8;
404                         return 1;
405                 case CUSTOM_RQ_READ_TMPSENS:
406                         uni_buffer.w16[0] = read_temperture_sensor();
407                         usbMsgPtr = uni_buffer.w8;
408                         return 2;
409                 }
410     }
411
412     return 0;   /* default for not implemented requests: return no data back to host */
413 }
414
415
416 uchar usbFunctionWrite(uchar *data, uchar len)
417 {
418         switch(current_command){
419
420         case LED_WRITE:
421             if (data[0] != LED_state)
422                 LED_state = data[0];
423             return 1; // Data read, not expecting more
424         case CUSTOM_RQ_SET_SECRET:
425         {
426             if (uni_buffer.w8[0] < (secret_length_b + 7) / 8) {
427                 memcpy(&secret[uni_buffer.w8[0]], data, len);
428                 uni_buffer.w8[0] += len;
429             }
430             if (uni_buffer.w8[0] >= (secret_length_b + 7) / 8) {
431                 secret_set();
432                 return 1;
433             }
434             return 0;
435         }
436         case CUSTOM_RQ_SET_DBG:
437                 if(len > sizeof(dbg_buffer)){
438                         len = sizeof(dbg_buffer);
439                 }
440                 memcpy(dbg_buffer, data, len);
441                 return 1;
442         case CUSTOM_RQ_WRITE_MEM:
443                 memcpy(uni_buffer.ptr[0], data, len);
444                 uni_buffer.w16[0] += len;
445                 return !(uni_buffer.w16[1] -= len);
446         case CUSTOM_RQ_EXEC_SPM:
447                 if(uni_buffer_fill < 8){
448                         uint8_t l = 8 - uni_buffer_fill;
449                         if(len<l){
450                                 len = l;
451                         }
452                         memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
453                         uni_buffer_fill += len;
454                         return 0;
455                 }
456                 uni_buffer.w16[1] -= len;
457                 if (uni_buffer.w16[1] > 8) {
458                         memcpy(uni_buffer.ptr[0], data, len);
459                         uni_buffer.w16[0] += len;
460                         return 0;
461                 } else {
462                         memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
463                         exec_spm(uni_buffer.w16[2], uni_buffer.w16[3], uni_buffer.ptr[0], data, len);
464                         return 1;
465                 }
466         default:
467                 return 1;
468         }
469         return 0;
470 }
471 uchar usbFunctionRead(uchar *data, uchar len){
472         uchar ret = len;
473         switch(current_command){
474         case CUSTOM_RQ_READ_FLASH:
475                 while(len--){
476                         *data++ = pgm_read_byte((uni_buffer.w16[0])++);
477                 }
478                 return ret;
479         default:
480                 break;
481         }
482         return 0;
483 }
484
485 static void calibrateOscillator(void)
486 {
487 uchar       step = 128;
488 uchar       trialValue = 0, optimumValue;
489 int         x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
490  
491     /* do a binary search: */
492     do {
493         OSCCAL = trialValue + step;
494         x = usbMeasureFrameLength();    // proportional to current real frequency
495         if(x < targetValue)             // frequency still too low
496             trialValue += step;
497         step >>= 1;
498     } while(step > 0);
499     /* We have a precision of +/- 1 for optimum OSCCAL here */
500     /* now do a neighborhood search for optimum value */
501     optimumValue = trialValue;
502     optimumDev = x; // this is certainly far away from optimum
503     for (OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
504         x = usbMeasureFrameLength() - targetValue;
505         if (x < 0)
506             x = -x;
507         if (x < optimumDev) {
508             optimumDev = x;
509             optimumValue = OSCCAL;
510         }
511     }
512     OSCCAL = optimumValue;
513 }
514  
515
516 void usbEventResetReady(void)
517 {
518     cli();  // usbMeasureFrameLength() counts CPU cycles, so disable interrupts.
519     calibrateOscillator();
520     sei();
521 // we never read the value from eeprom so this causes only degradation of eeprom
522 //    eeprom_write_byte(0, OSCCAL);   // store the calibrated value in EEPROM
523 }
524
525 /* ------------------------------------------------------------------------- */
526
527 char key_seq[] = "Hello World";
528
529 int main(void)
530 {
531         uchar  i;
532         size_t idx = 0;
533
534     wdt_enable(WDTO_1S);
535     /* Even if you don't use the watchdog, turn it off here. On newer devices,
536      * the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
537      */
538     /* RESET status: all port bits are inputs without pull-up.
539      * That's the way we need D+ and D-. Therefore we don't need any
540      * additional hardware initialization.
541      */
542
543     init_temperature_sensor();
544     usbInit();
545     usbDeviceDisconnect();  /* enforce re-enumeration, do this while interrupts are disabled! */
546     i = 0;
547     while(--i){             /* fake USB disconnect for ~512 ms */
548         wdt_reset();
549         _delay_ms(2);
550     }
551     usbDeviceConnect();
552     LED_PORT_DDR |= _BV(R_BIT) | _BV(G_BIT) | _BV(B_BIT);   /* make the LED bit an output */
553
554         
555     sei();
556
557     for(;;){                /* main event loop */
558         wdt_reset();
559         usbPoll();
560
561         if(usbInterruptIsReady() && key_state != STATE_WAIT){
562             switch(key_state) {
563             case STATE_SEND_KEY:
564                 buildReport(key_seq[idx]);
565                 key_state = STATE_RELEASE_KEY; // release next
566                 break;
567             case STATE_RELEASE_KEY:
568                 buildReport(0);
569                 ++idx;
570                 if (key_seq[idx] == '\0') {
571                     idx = 0;
572                     key_state = STATE_WAIT;
573                 } else {
574                     key_state = STATE_SEND_KEY;
575                 }
576                 break;
577             default:
578                 key_state = STATE_WAIT; // should not happen
579             }
580                         // start sending
581             usbSetInterrupt((void *)&keyboard_report, sizeof(keyboard_report));
582
583         }
584
585     }
586     return 0;
587 }
588
589 /* ------------------------------------------------------------------------- */