]> git.donarmstrong.com Git - kiibohd-controller.git/blob - LoadFile/teensy_loader_cli.c
Merge pull request #71 from glguy/pr-cli-history
[kiibohd-controller.git] / LoadFile / teensy_loader_cli.c
1 /* Teensy Loader, Command Line Interface
2  * Program and Reboot Teensy Board with HalfKay Bootloader
3  * http://www.pjrc.com/teensy/loader_cli.html
4  * Copyright 2008-2010, PJRC.COM, LLC
5  * Modifications 2014, Jacob Alexander <haata@kiibohd.com>
6  *
7  * You may redistribute this program and/or modify it under the terms
8  * of the GNU General Public License as published by the Free Software
9  * Foundation, version 3 of the License.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see http://www.gnu.org/licenses/
18  */
19
20 /* Want to incorporate this code into a proprietary application??
21  * Just email paul@pjrc.com to ask.  Usually it's not a problem,
22  * but you do need to ask to use this code in any way other than
23  * those permitted by the GNU General Public License, version 3  */
24
25 /* For non-root permissions on ubuntu or similar udev-based linux
26  * http://www.pjrc.com/teensy/49-teensy.rules
27  */
28
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdint.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <unistd.h>
36
37 void usage(void)
38 {
39         fprintf(stderr, "Usage: teensy_loader_cli -mmcu=<MCU> [-w] [-h] [-n] [-v] <file.hex>\n");
40         fprintf(stderr, "\t-w : Wait for device to appear\n");
41         fprintf(stderr, "\t-r : Use hard reboot if device not online\n");
42         fprintf(stderr, "\t-n : No reboot after programming\n");
43         fprintf(stderr, "\t-v : Verbose output\n");
44 #if defined(USE_LIBUSB)
45         fprintf(stderr, "\n<MCU> = atmega32u4 | at90usb162 | at90usb646 | at90usb1286 | mk20dx128 | mk20dx256\n");
46 #else
47         fprintf(stderr, "\n<MCU> = atmega32u4 | at90usb162 | at90usb646 | at90usb1286\n");
48 #endif
49         fprintf(stderr, "\nFor more information, please visit:\n");
50         fprintf(stderr, "http://www.pjrc.com/teensy/loader_cli.html\n");
51         exit(1);
52 }
53
54 // USB Access Functions
55 int teensy_open(void);
56 int teensy_write(void *buf, int len, double timeout);
57 void teensy_close(void);
58 int hard_reboot(void);
59
60 // Intel Hex File Functions
61 int read_intel_hex(const char *filename);
62 int ihex_bytes_within_range(int begin, int end);
63 void ihex_get_data(int addr, int len, unsigned char *bytes);
64 int memory_is_blank(int addr, int block_size);
65
66 // Misc stuff
67 int printf_verbose(const char *format, ...);
68 void delay(double seconds);
69 void die(const char *str, ...);
70 void parse_options(int argc, char **argv);
71
72 // options (from user via command line args)
73 int wait_for_device_to_appear = 0;
74 int hard_reboot_device = 0;
75 int reboot_after_programming = 1;
76 int verbose = 0;
77 int code_size = 0, block_size = 0;
78 const char *filename=NULL;
79
80
81 /****************************************************************/
82 /*                                                              */
83 /*                       Main Program                           */
84 /*                                                              */
85 /****************************************************************/
86
87 int main(int argc, char **argv)
88 {
89         unsigned char buf[2048];
90         int num, addr, r, write_size=block_size+2;
91         int first_block=1, waited=0;
92
93         // parse command line arguments
94         parse_options(argc, argv);
95         if (!filename) {
96                 fprintf(stderr, "Filename must be specified\n\n");
97                 usage();
98         }
99         if (!code_size) {
100                 fprintf(stderr, "MCU type must be specified\n\n");
101                 usage();
102         }
103         printf_verbose("Teensy Loader, Command Line, Version 2.0, Kiibohd-Mods\n");
104
105         // read the intel hex file
106         // this is done first so any error is reported before using USB
107         num = read_intel_hex(filename);
108         if (num < 0) die("error reading intel hex file \"%s\"", filename);
109         printf_verbose("Read \"%s\": %d bytes, %.1f%% usage\n",
110                 filename, num, (double)num / (double)code_size * 100.0);
111
112         // open the USB device
113         while (1) {
114                 if (teensy_open()) break;
115                 if (hard_reboot_device) {
116                         if (!hard_reboot()) die("Unable to find rebootor\n");
117                         printf_verbose("Hard Reboot performed\n");
118                         hard_reboot_device = 0; // only hard reboot once
119                         wait_for_device_to_appear = 1;
120                 }
121                 if (!wait_for_device_to_appear) die("Unable to open device\n");
122                 if (!waited) {
123                         printf_verbose("Waiting for Teensy device...\n");
124                         printf_verbose(" (hint: press the reset button)\n");
125                         waited = 1;
126                 }
127                 delay(0.25);
128         }
129         printf_verbose("Found HalfKay Bootloader\n");
130
131         // if we waited for the device, read the hex file again
132         // perhaps it changed while we were waiting?
133         if (waited) {
134                 num = read_intel_hex(filename);
135                 if (num < 0) die("error reading intel hex file \"%s\"", filename);
136                 printf_verbose("Read \"%s\": %d bytes, %.1f%% usage\n",
137                         filename, num, (double)num / (double)code_size * 100.0);
138         }
139
140         // program the data
141         printf_verbose("Programming");
142         fflush(stdout);
143         for (addr = 0; addr < code_size; addr += block_size) {
144                 if (!first_block && !ihex_bytes_within_range(addr, addr + block_size - 1)) {
145                         // don't waste time on blocks that are unused,
146                         // but always do the first one to erase the chip
147                         continue;
148                 }
149                 if (!first_block && memory_is_blank(addr, block_size)) continue;
150                 printf_verbose(".");
151                 if (code_size < 0x10000) {
152                         buf[0] = addr & 255;
153                         buf[1] = (addr >> 8) & 255;
154                         ihex_get_data(addr, block_size, buf + 2);
155                         write_size = block_size + 2;
156                 } else if (block_size == 256) {
157                         buf[0] = (addr >> 8) & 255;
158                         buf[1] = (addr >> 16) & 255;
159                         ihex_get_data(addr, block_size, buf + 2);
160                         write_size = block_size + 2;
161                 } else if (block_size >= 1024) {
162                         buf[0] = addr & 255;
163                         buf[1] = (addr >> 8) & 255;
164                         buf[2] = (addr >> 16) & 255;
165                         memset(buf + 3, 0, 61);
166                         ihex_get_data(addr, block_size, buf + 64);
167                         write_size = block_size + 64;
168                 } else {
169                         die("Unknown code/block size\n");
170                 }
171                 r = teensy_write(buf, write_size, first_block ? 3.0 : 0.25);
172                 if (!r) die("error writing to Teensy\n");
173                 first_block = 0;
174         }
175         printf_verbose("\n");
176
177         // reboot to the user's new code
178         if (reboot_after_programming) {
179                 printf_verbose("Booting\n");
180                 buf[0] = 0xFF;
181                 buf[1] = 0xFF;
182                 buf[2] = 0xFF;
183                 memset(buf + 3, 0, sizeof(buf) - 3);
184                 teensy_write(buf, write_size, 0.25);
185         }
186         teensy_close();
187         return 0;
188 }
189
190
191
192
193 /****************************************************************/
194 /*                                                              */
195 /*             USB Access - libusb (Linux, Windows & FreeBSD)   */
196 /*                                                              */
197 /****************************************************************/
198
199 #if defined(USE_LIBUSB)
200
201 #include <libusb-1.0/libusb.h>
202
203 struct libusb_device_handle *open_usb_device( int vid, int pid )
204 {
205         libusb_device **devs;
206         struct libusb_device_handle *handle = NULL;
207         struct libusb_device_handle *ret = NULL;
208
209         if ( libusb_init( NULL ) != 0 )
210                 fprintf( stderr, "libusb_init failed.\n" );
211
212         size_t count = libusb_get_device_list( NULL, &devs );
213         if ( count < 0 )
214                 fprintf( stderr, "libusb_get_device_list failed.\n" );
215
216         for ( size_t c = 0; c < count; c++ )
217         {
218                 struct libusb_device_descriptor desc;
219                 libusb_device *dev = devs[c];
220
221                 if ( libusb_get_device_descriptor( dev, &desc ) < 0 )
222                         fprintf( stderr, "libusb_get_device_descriptor failed.\n" );
223
224                 //printf("ID: %04x  Product: %04x\n", desc.idVendor, desc.idProduct );
225                 // Not correct device
226                 if ( desc.idVendor != vid || desc.idProduct != pid )
227                         continue;
228
229                 // Attempt to open the device
230                 if ( libusb_open( dev, &handle ) != 0 )
231                 {
232                         fprintf( stderr, "Found device but unable to open\n" );
233                         continue;
234                 }
235
236                 // Only required on Linux, other platforms will just ignore this call
237                 libusb_detach_kernel_driver( handle, 0 );
238
239                 // Mac OS-X - removing this call to usb_claim_interface() might allow
240                 // this to work, even though it is a clear misuse of the libusb API.
241                 // normally Apple's IOKit should be used on Mac OS-X
242                 // XXX Is this still valid with libusb-1.0?
243
244                 // Attempt to claim interface
245                 int err = libusb_claim_interface( handle, 0 );
246                 if ( err < 0 )
247                 {
248                         libusb_close( handle );
249                         fprintf( stderr, "Unable to claim interface, check USB permissions: %d\n", err );
250                         continue;
251                 }
252
253                 ret = handle;
254                 break;
255         }
256
257         libusb_free_device_list( devs, 1 );
258
259         return ret;
260 }
261
262 static struct libusb_device_handle *libusb_teensy_handle = NULL;
263
264 int teensy_open()
265 {
266         teensy_close();
267
268         libusb_teensy_handle = open_usb_device( 0x16C0, 0x0478 );
269
270         if ( libusb_teensy_handle )
271                 return 1;
272
273         return 0;
274 }
275
276 int teensy_write( void *buf, int len, double timeout )
277 {
278         int r;
279
280         if ( !libusb_teensy_handle )
281                 return 0;
282
283         while ( timeout > 0 ) {
284                 r = libusb_control_transfer( libusb_teensy_handle,
285                         0x21, 9, 0x0200, 0,
286                         (unsigned char *)buf, len,
287                         (int)(timeout * 1000.0) );
288
289                 if ( r >= 0 )
290                         return 1;
291
292                 //printf("teensy_write, r=%d\n", r);
293                 usleep( 10000 );
294                 timeout -= 0.01;  // TODO: subtract actual elapsed time
295         }
296
297         return 0;
298 }
299
300 void teensy_close()
301 {
302         if ( !libusb_teensy_handle)
303                 return;
304
305         libusb_release_interface( libusb_teensy_handle, 0 );
306         libusb_close( libusb_teensy_handle );
307
308         libusb_teensy_handle = NULL;
309 }
310
311 int hard_reboot()
312 {
313         struct libusb_device_handle *rebootor;
314         int r;
315
316         rebootor = open_usb_device( 0x16C0, 0x0477 );
317
318         if (!rebootor)
319                 return 0;
320
321         r = libusb_control_transfer( rebootor,
322                 0x21, 9, 0x0200, 0,
323                 (unsigned char*)"reboot", 6,
324                 100 );
325
326         libusb_release_interface( rebootor, 0 );
327         libusb_close( rebootor );
328
329         if (r < 0)
330                 return 0;
331
332         return 1;
333 }
334
335 #endif
336
337
338
339 /****************************************************************/
340 /*                                                              */
341 /*             USB Access - Apple's IOKit, Mac OS-X             */
342 /*                                                              */
343 /****************************************************************/
344
345 #if defined(USE_APPLE_IOKIT)
346
347 // http://developer.apple.com/technotes/tn2007/tn2187.html
348 #include <IOKit/IOKitLib.h>
349 #include <IOKit/hid/IOHIDLib.h>
350 #include <IOKit/hid/IOHIDDevice.h>
351
352 struct usb_list_struct {
353         IOHIDDeviceRef ref;
354         int pid;
355         int vid;
356         struct usb_list_struct *next;
357 };
358
359 static struct usb_list_struct *usb_list=NULL;
360 static IOHIDManagerRef hid_manager=NULL;
361
362 void attach_callback(void *context, IOReturn r, void *hid_mgr, IOHIDDeviceRef dev)
363 {
364         CFTypeRef type;
365         struct usb_list_struct *n, *p;
366         int32_t pid, vid;
367
368         if (!dev) return;
369         type = IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDVendorIDKey));
370         if (!type || CFGetTypeID(type) != CFNumberGetTypeID()) return;
371         if (!CFNumberGetValue((CFNumberRef)type, kCFNumberSInt32Type, &vid)) return;
372         type = IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDProductIDKey));
373         if (!type || CFGetTypeID(type) != CFNumberGetTypeID()) return;
374         if (!CFNumberGetValue((CFNumberRef)type, kCFNumberSInt32Type, &pid)) return;
375         n = (struct usb_list_struct *)malloc(sizeof(struct usb_list_struct));
376         if (!n) return;
377         //printf("attach callback: vid=%04X, pid=%04X\n", vid, pid);
378         n->ref = dev;
379         n->vid = vid;
380         n->pid = pid;
381         n->next = NULL;
382         if (usb_list == NULL) {
383                 usb_list = n;
384         } else {
385                 for (p = usb_list; p->next; p = p->next) ;
386                 p->next = n;
387         }
388 }
389
390 void detach_callback(void *context, IOReturn r, void *hid_mgr, IOHIDDeviceRef dev)
391 {
392         struct usb_list_struct *p, *tmp, *prev=NULL;
393
394         p = usb_list;
395         while (p) {
396                 if (p->ref == dev) {
397                         if (prev) {
398                                 prev->next = p->next;
399                         } else {
400                                 usb_list = p->next;
401                         }
402                         tmp = p;
403                         p = p->next;
404                         free(tmp);
405                 } else {
406                         prev = p;
407                         p = p->next;
408                 }
409         }
410 }
411
412 void init_hid_manager(void)
413 {
414         CFMutableDictionaryRef dict;
415         IOReturn ret;
416
417         if (hid_manager) return;
418         hid_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
419         if (hid_manager == NULL || CFGetTypeID(hid_manager) != IOHIDManagerGetTypeID()) {
420                 if (hid_manager) CFRelease(hid_manager);
421                 printf_verbose("no HID Manager - maybe this is a pre-Leopard (10.5) system?\n");
422                 return;
423         }
424         dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
425                 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
426         if (!dict) return;
427         IOHIDManagerSetDeviceMatching(hid_manager, dict);
428         CFRelease(dict);
429         IOHIDManagerScheduleWithRunLoop(hid_manager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
430         IOHIDManagerRegisterDeviceMatchingCallback(hid_manager, attach_callback, NULL);
431         IOHIDManagerRegisterDeviceRemovalCallback(hid_manager, detach_callback, NULL);
432         ret = IOHIDManagerOpen(hid_manager, kIOHIDOptionsTypeNone);
433         if (ret != kIOReturnSuccess) {
434                 IOHIDManagerUnscheduleFromRunLoop(hid_manager,
435                         CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
436                 CFRelease(hid_manager);
437                 printf_verbose("Error opening HID Manager");
438         }
439 }
440
441 static void do_run_loop(void)
442 {
443         while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true) == kCFRunLoopRunHandledSource) ;
444 }
445
446 IOHIDDeviceRef open_usb_device(int vid, int pid)
447 {
448         struct usb_list_struct *p;
449         IOReturn ret;
450
451         init_hid_manager();
452         do_run_loop();
453         for (p = usb_list; p; p = p->next) {
454                 if (p->vid == vid && p->pid == pid) {
455                         ret = IOHIDDeviceOpen(p->ref, kIOHIDOptionsTypeNone);
456                         if (ret == kIOReturnSuccess) return p->ref;
457                 }
458         }
459         return NULL;
460 }
461
462 void close_usb_device(IOHIDDeviceRef dev)
463 {
464         struct usb_list_struct *p;
465
466         do_run_loop();
467         for (p = usb_list; p; p = p->next) {
468                 if (p->ref == dev) {
469                         IOHIDDeviceClose(dev, kIOHIDOptionsTypeNone);
470                         return;
471                 }
472         }
473 }
474
475 static IOHIDDeviceRef iokit_teensy_reference = NULL;
476
477 int teensy_open(void)
478 {
479         teensy_close();
480         iokit_teensy_reference = open_usb_device(0x16C0, 0x0478);
481         if (iokit_teensy_reference) return 1;
482         return 0;
483 }
484
485 int teensy_write(void *buf, int len, double timeout)
486 {
487         IOReturn ret;
488
489         // timeouts do not work on OS-X
490         // IOHIDDeviceSetReportWithCallback is not implemented
491         // even though Apple documents it with a code example!
492         // submitted to Apple on 22-sep-2009, problem ID 7245050
493         if (!iokit_teensy_reference) return 0;
494         ret = IOHIDDeviceSetReport(iokit_teensy_reference,
495                 kIOHIDReportTypeOutput, 0, buf, len);
496         if (ret == kIOReturnSuccess) return 1;
497         return 0;
498 }
499
500 void teensy_close(void)
501 {
502         if (!iokit_teensy_reference) return;
503         close_usb_device(iokit_teensy_reference);
504         iokit_teensy_reference = NULL;
505 }
506
507 int hard_reboot(void)
508 {
509         IOHIDDeviceRef rebootor;
510         IOReturn ret;
511
512         rebootor = open_usb_device(0x16C0, 0x0477);
513         if (!rebootor) return 0;
514         ret = IOHIDDeviceSetReport(rebootor,
515                 kIOHIDReportTypeOutput, 0, (uint8_t *)("reboot"), 6);
516         close_usb_device(rebootor);
517         if (ret == kIOReturnSuccess) return 1;
518         return 0;
519 }
520
521 #endif
522
523
524
525 /****************************************************************/
526 /*                                                              */
527 /*              USB Access - BSD's UHID driver                  */
528 /*                                                              */
529 /****************************************************************/
530
531 #if defined(USE_UHID)
532
533 // Thanks to Todd T Fries for help getting this working on OpenBSD
534 // and to Chris Kuethe for the initial patch to use UHID.
535
536 #include <sys/ioctl.h>
537 #include <fcntl.h>
538 #include <dirent.h>
539 #include <dev/usb/usb.h>
540 #ifndef USB_GET_DEVICEINFO
541 #include <dev/usb/usb_ioctl.h>
542 #endif
543
544 int open_usb_device(int vid, int pid)
545 {
546         int r, fd;
547         DIR *dir;
548         struct dirent *d;
549         struct usb_device_info info;
550         char buf[256];
551
552         dir = opendir("/dev");
553         if (!dir) return -1;
554         while ((d = readdir(dir)) != NULL) {
555                 if (strncmp(d->d_name, "uhid", 4) != 0) continue;
556                 snprintf(buf, sizeof(buf), "/dev/%s", d->d_name);
557                 fd = open(buf, O_RDWR);
558                 if (fd < 0) continue;
559                 r = ioctl(fd, USB_GET_DEVICEINFO, &info);
560                 if (r < 0) {
561                         // NetBSD: added in 2004
562                         // OpenBSD: added November 23, 2009
563                         // FreeBSD: missing (FreeBSD 8.0) - USE_LIBUSB works!
564                         die("Error: your uhid driver does not support"
565                           " USB_GET_DEVICEINFO, please upgrade!\n");
566                         close(fd);
567                         closedir(dir);
568                         exit(1);
569                 }
570                 //printf("%s: v=%d, p=%d\n", buf, info.udi_vendorNo, info.udi_productNo);
571                 if (info.udi_vendorNo == vid && info.udi_productNo == pid) {
572                         closedir(dir);
573                         return fd;
574                 }
575                 close(fd);
576         }
577         closedir(dir);
578         return -1;
579 }
580
581 static int uhid_teensy_fd = -1;
582
583 int teensy_open(void)
584 {
585         teensy_close();
586         uhid_teensy_fd = open_usb_device(0x16C0, 0x0478);
587         if (uhid_teensy_fd < 0) return 0;
588         return 1;
589 }
590
591 int teensy_write(void *buf, int len, double timeout)
592 {
593         int r;
594
595         // TODO: imeplement timeout... how??
596         r = write(uhid_teensy_fd, buf, len);
597         if (r == len) return 1;
598         return 0;
599 }
600
601 void teensy_close(void)
602 {
603         if (uhid_teensy_fd >= 0) {
604                 close(uhid_teensy_fd);
605                 uhid_teensy_fd = -1;
606         }
607 }
608
609 int hard_reboot(void)
610 {
611         int r, rebootor_fd;
612
613         rebootor_fd = open_usb_device(0x16C0, 0x0477);
614         if (rebootor_fd < 0) return 0;
615         r = write(rebootor_fd, "reboot", 6);
616         delay(0.1);
617         close(rebootor_fd);
618         if (r == 6) return 1;
619         return 0;
620 }
621
622 #endif
623
624
625
626 /****************************************************************/
627 /*                                                              */
628 /*                     Read Intel Hex File                      */
629 /*                                                              */
630 /****************************************************************/
631
632 // the maximum flash image size we can support
633 // chips with larger memory may be used, but only this
634 // much intel-hex data can be loaded into memory!
635 #define MAX_MEMORY_SIZE 0x40000
636
637 static unsigned char firmware_image[MAX_MEMORY_SIZE];
638 static unsigned char firmware_mask[MAX_MEMORY_SIZE];
639 static int end_record_seen=0;
640 static int byte_count;
641 static unsigned int extended_addr = 0;
642 static int parse_hex_line(char *line);
643
644 int read_intel_hex(const char *filename)
645 {
646         FILE *fp;
647         int i, lineno=0;
648         char buf[1024];
649
650         byte_count = 0;
651         end_record_seen = 0;
652         for (i=0; i<MAX_MEMORY_SIZE; i++) {
653                 firmware_image[i] = 0xFF;
654                 firmware_mask[i] = 0;
655         }
656         extended_addr = 0;
657
658         fp = fopen(filename, "r");
659         if (fp == NULL) {
660                 //printf("Unable to read file %s\n", filename);
661                 return -1;
662         }
663         while (!feof(fp)) {
664                 *buf = '\0';
665                 if (!fgets(buf, sizeof(buf), fp)) break;
666                 lineno++;
667                 if (*buf) {
668                         if (parse_hex_line(buf) == 0) {
669                                 printf("Warning, HEX parse error line %d\n", lineno);
670                                 return -2;
671                         }
672                 }
673                 if (end_record_seen) break;
674                 if (feof(stdin)) break;
675         }
676         fclose(fp);
677         return byte_count;
678 }
679
680
681 /* from ihex.c, at http://www.pjrc.com/tech/8051/pm2_docs/intel-hex.html */
682
683 /* parses a line of intel hex code, stores the data in bytes[] */
684 /* and the beginning address in addr, and returns a 1 if the */
685 /* line was valid, or a 0 if an error occured.  The variable */
686 /* num gets the number of bytes that were stored into bytes[] */
687
688
689 int
690 parse_hex_line(char *line)
691 {
692         int addr, code, num;
693         int sum, len, cksum, i;
694         char *ptr;
695
696         num = 0;
697         if (line[0] != ':') return 0;
698         if (strlen(line) < 11) return 0;
699         ptr = line+1;
700         if (!sscanf(ptr, "%02x", &len)) return 0;
701         ptr += 2;
702         if ((int)strlen(line) < (11 + (len * 2)) ) return 0;
703         if (!sscanf(ptr, "%04x", &addr)) return 0;
704         ptr += 4;
705           /* printf("Line: length=%d Addr=%d\n", len, addr); */
706         if (!sscanf(ptr, "%02x", &code)) return 0;
707         if (addr + extended_addr + len >= MAX_MEMORY_SIZE) return 0;
708         ptr += 2;
709         sum = (len & 255) + ((addr >> 8) & 255) + (addr & 255) + (code & 255);
710         if (code != 0) {
711                 if (code == 1) {
712                         end_record_seen = 1;
713                         return 1;
714                 }
715                 if (code == 2 && len == 2) {
716                         if (!sscanf(ptr, "%04x", &i)) return 1;
717                         ptr += 4;
718                         sum += ((i >> 8) & 255) + (i & 255);
719                         if (!sscanf(ptr, "%02x", &cksum)) return 1;
720                         if (((sum & 255) + (cksum & 255)) & 255) return 1;
721                         extended_addr = i << 4;
722                         //printf("ext addr = %05X\n", extended_addr);
723                 }
724                 if (code == 4 && len == 2) {
725                         if (!sscanf(ptr, "%04x", &i)) return 1;
726                         ptr += 4;
727                         sum += ((i >> 8) & 255) + (i & 255);
728                         if (!sscanf(ptr, "%02x", &cksum)) return 1;
729                         if (((sum & 255) + (cksum & 255)) & 255) return 1;
730                         extended_addr = i << 16;
731                         //printf("ext addr = %08X\n", extended_addr);
732                 }
733                 return 1;       // non-data line
734         }
735         byte_count += len;
736         while (num != len) {
737                 if (sscanf(ptr, "%02x", &i) != 1) return 0;
738                 i &= 255;
739                 firmware_image[addr + extended_addr + num] = i;
740                 firmware_mask[addr + extended_addr + num] = 1;
741                 ptr += 2;
742                 sum += i;
743                 (num)++;
744                 if (num >= 256) return 0;
745         }
746         if (!sscanf(ptr, "%02x", &cksum)) return 0;
747         if (((sum & 255) + (cksum & 255)) & 255) return 0; /* checksum error */
748         return 1;
749 }
750
751 int ihex_bytes_within_range(int begin, int end)
752 {
753         int i;
754
755         if (begin < 0 || begin >= MAX_MEMORY_SIZE ||
756            end < 0 || end >= MAX_MEMORY_SIZE) {
757                 return 0;
758         }
759         for (i=begin; i<=end; i++) {
760                 if (firmware_mask[i]) return 1;
761         }
762         return 0;
763 }
764
765 void ihex_get_data(int addr, int len, unsigned char *bytes)
766 {
767         int i;
768
769         if (addr < 0 || len < 0 || addr + len >= MAX_MEMORY_SIZE) {
770                 for (i=0; i<len; i++) {
771                         bytes[i] = 255;
772                 }
773                 return;
774         }
775         for (i=0; i<len; i++) {
776                 if (firmware_mask[addr]) {
777                         bytes[i] = firmware_image[addr];
778                 } else {
779                         bytes[i] = 255;
780                 }
781                 addr++;
782         }
783 }
784
785 int memory_is_blank(int addr, int block_size)
786 {
787         if (addr < 0 || addr > MAX_MEMORY_SIZE) return 1;
788
789         while (block_size && addr < MAX_MEMORY_SIZE) {
790                 if (firmware_mask[addr] && firmware_image[addr] != 255) return 0;
791                 addr++;
792                 block_size--;
793         }
794         return 1;
795 }
796
797
798
799
800 /****************************************************************/
801 /*                                                              */
802 /*                       Misc Functions                         */
803 /*                                                              */
804 /****************************************************************/
805
806 int printf_verbose(const char *format, ...)
807 {
808         va_list ap;
809         int r;
810
811         va_start(ap, format);
812         if (verbose) {
813                 r = vprintf(format, ap);
814                 fflush(stdout);
815                 return r;
816         }
817         return 0;
818 }
819
820 void delay(double seconds)
821 {
822         #ifdef WIN32
823         Sleep(seconds * 1000.0);
824         #else
825         usleep(seconds * 1000000.0);
826         #endif
827 }
828
829 void die(const char *str, ...)
830 {
831         va_list  ap;
832
833         va_start(ap, str);
834         vfprintf(stderr, str, ap);
835         fprintf(stderr, "\n");
836         exit(1);
837 }
838
839 #if defined(WIN32)
840 #define strcasecmp stricmp
841 #endif
842
843 void parse_options(int argc, char **argv)
844 {
845         int i;
846         const char *arg;
847
848         for (i=1; i<argc; i++) {
849                 arg = argv[i];
850                 //printf("arg: %s\n", arg);
851                 if (*arg == '-') {
852                         if (strcmp(arg, "-w") == 0) {
853                                 wait_for_device_to_appear = 1;
854                         } else if (strcmp(arg, "-r") == 0) {
855                                 hard_reboot_device = 1;
856                         } else if (strcmp(arg, "-n") == 0) {
857                                 reboot_after_programming = 0;
858                         } else if (strcmp(arg, "-v") == 0) {
859                                 verbose = 1;
860                         } else if (strncmp(arg, "-mmcu=", 6) == 0) {
861                                 if (strcasecmp(arg+6, "at90usb162") == 0) {
862                                         code_size = 15872;
863                                         block_size = 128;
864                                 } else if (strcasecmp(arg+6, "atmega32u4") == 0) {
865                                         code_size = 32256;
866                                         block_size = 128;
867                                 } else if (strcasecmp(arg+6, "at90usb646") == 0) {
868                                         code_size = 64512;
869                                         block_size = 256;
870                                 } else if (strcasecmp(arg+6, "at90usb1286") == 0) {
871                                         code_size = 130048;
872                                         block_size = 256;
873 #if defined(USE_LIBUSB)
874                                 } else if (strcasecmp(arg+6, "mk20dx128") == 0) {
875                                         code_size = 131072;
876                                         block_size = 1024;
877                                 } else if (strcasecmp(arg+6, "mk20dx256") == 0) {
878                                         code_size = 262144;
879                                         block_size = 1024;
880 #endif
881                                 } else {
882                                         die("Unknown MCU type\n");
883                                 }
884                         }
885                 } else {
886                         filename = argv[i];
887                 }
888         }
889 }
890