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>
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.
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.
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/
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 */
25 /* For non-root permissions on ubuntu or similar udev-based linux
26 * http://www.pjrc.com/teensy/49-teensy.rules
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");
47 fprintf(stderr, "\n<MCU> = atmega32u4 | at90usb162 | at90usb646 | at90usb1286\n");
49 fprintf(stderr, "\nFor more information, please visit:\n");
50 fprintf(stderr, "http://www.pjrc.com/teensy/loader_cli.html\n");
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);
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);
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);
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;
77 int code_size = 0, block_size = 0;
78 const char *filename=NULL;
81 /****************************************************************/
85 /****************************************************************/
87 int main(int argc, char **argv)
89 unsigned char buf[2048];
90 int num, addr, r, write_size=block_size+2;
91 int first_block=1, waited=0;
93 // parse command line arguments
94 parse_options(argc, argv);
96 fprintf(stderr, "Filename must be specified\n\n");
100 fprintf(stderr, "MCU type must be specified\n\n");
103 printf_verbose("Teensy Loader, Command Line, Version 2.0, Kiibohd-Mods\n");
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);
112 // open the USB device
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;
121 if (!wait_for_device_to_appear) die("Unable to open device\n");
123 printf_verbose("Waiting for Teensy device...\n");
124 printf_verbose(" (hint: press the reset button)\n");
129 printf_verbose("Found HalfKay Bootloader\n");
131 // if we waited for the device, read the hex file again
132 // perhaps it changed while we were waiting?
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);
141 printf_verbose("Programming");
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
149 if (!first_block && memory_is_blank(addr, block_size)) continue;
151 if (code_size < 0x10000) {
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) {
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;
169 die("Unknown code/block size\n");
171 r = teensy_write(buf, write_size, first_block ? 3.0 : 0.25);
172 if (!r) die("error writing to Teensy\n");
175 printf_verbose("\n");
177 // reboot to the user's new code
178 if (reboot_after_programming) {
179 printf_verbose("Booting\n");
183 memset(buf + 3, 0, sizeof(buf) - 3);
184 teensy_write(buf, write_size, 0.25);
193 /****************************************************************/
195 /* USB Access - libusb (Linux, Windows & FreeBSD) */
197 /****************************************************************/
199 #if defined(USE_LIBUSB)
201 #include <libusb-1.0/libusb.h>
203 struct libusb_device_handle *open_usb_device( int vid, int pid )
205 libusb_device **devs;
206 struct libusb_device_handle *handle = NULL;
207 struct libusb_device_handle *ret = NULL;
209 if ( libusb_init( NULL ) != 0 )
210 fprintf( stderr, "libusb_init failed.\n" );
212 size_t count = libusb_get_device_list( NULL, &devs );
214 fprintf( stderr, "libusb_get_device_list failed.\n" );
216 for ( size_t c = 0; c < count; c++ )
218 struct libusb_device_descriptor desc;
219 libusb_device *dev = devs[c];
221 if ( libusb_get_device_descriptor( dev, &desc ) < 0 )
222 fprintf( stderr, "libusb_get_device_descriptor failed.\n" );
224 //printf("ID: %04x Product: %04x\n", desc.idVendor, desc.idProduct );
225 // Not correct device
226 if ( desc.idVendor != vid || desc.idProduct != pid )
229 // Attempt to open the device
230 if ( libusb_open( dev, &handle ) != 0 )
232 fprintf( stderr, "Found device but unable to open\n" );
236 // Only required on Linux, other platforms will just ignore this call
237 libusb_detach_kernel_driver( handle, 0 );
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?
244 // Attempt to claim interface
245 int err = libusb_claim_interface( handle, 0 );
248 libusb_close( handle );
249 fprintf( stderr, "Unable to claim interface, check USB permissions: %d\n", err );
257 libusb_free_device_list( devs, 1 );
262 static struct libusb_device_handle *libusb_teensy_handle = NULL;
268 libusb_teensy_handle = open_usb_device( 0x16C0, 0x0478 );
270 if ( libusb_teensy_handle )
276 int teensy_write( void *buf, int len, double timeout )
280 if ( !libusb_teensy_handle )
283 while ( timeout > 0 ) {
284 r = libusb_control_transfer( libusb_teensy_handle,
286 (unsigned char *)buf, len,
287 (int)(timeout * 1000.0) );
292 //printf("teensy_write, r=%d\n", r);
294 timeout -= 0.01; // TODO: subtract actual elapsed time
302 if ( !libusb_teensy_handle)
305 libusb_release_interface( libusb_teensy_handle, 0 );
306 libusb_close( libusb_teensy_handle );
308 libusb_teensy_handle = NULL;
313 struct libusb_device_handle *rebootor;
316 rebootor = open_usb_device( 0x16C0, 0x0477 );
321 r = libusb_control_transfer( rebootor,
323 (unsigned char*)"reboot", 6,
326 libusb_release_interface( rebootor, 0 );
327 libusb_close( rebootor );
339 /****************************************************************/
341 /* USB Access - Apple's IOKit, Mac OS-X */
343 /****************************************************************/
345 #if defined(USE_APPLE_IOKIT)
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>
352 struct usb_list_struct {
356 struct usb_list_struct *next;
359 static struct usb_list_struct *usb_list=NULL;
360 static IOHIDManagerRef hid_manager=NULL;
362 void attach_callback(void *context, IOReturn r, void *hid_mgr, IOHIDDeviceRef dev)
365 struct usb_list_struct *n, *p;
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));
377 //printf("attach callback: vid=%04X, pid=%04X\n", vid, pid);
382 if (usb_list == NULL) {
385 for (p = usb_list; p->next; p = p->next) ;
390 void detach_callback(void *context, IOReturn r, void *hid_mgr, IOHIDDeviceRef dev)
392 struct usb_list_struct *p, *tmp, *prev=NULL;
398 prev->next = p->next;
412 void init_hid_manager(void)
414 CFMutableDictionaryRef dict;
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");
424 dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
425 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
427 IOHIDManagerSetDeviceMatching(hid_manager, 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");
441 static void do_run_loop(void)
443 while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true) == kCFRunLoopRunHandledSource) ;
446 IOHIDDeviceRef open_usb_device(int vid, int pid)
448 struct usb_list_struct *p;
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;
462 void close_usb_device(IOHIDDeviceRef dev)
464 struct usb_list_struct *p;
467 for (p = usb_list; p; p = p->next) {
469 IOHIDDeviceClose(dev, kIOHIDOptionsTypeNone);
475 static IOHIDDeviceRef iokit_teensy_reference = NULL;
477 int teensy_open(void)
480 iokit_teensy_reference = open_usb_device(0x16C0, 0x0478);
481 if (iokit_teensy_reference) return 1;
485 int teensy_write(void *buf, int len, double timeout)
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;
500 void teensy_close(void)
502 if (!iokit_teensy_reference) return;
503 close_usb_device(iokit_teensy_reference);
504 iokit_teensy_reference = NULL;
507 int hard_reboot(void)
509 IOHIDDeviceRef rebootor;
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;
525 /****************************************************************/
527 /* USB Access - BSD's UHID driver */
529 /****************************************************************/
531 #if defined(USE_UHID)
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.
536 #include <sys/ioctl.h>
539 #include <dev/usb/usb.h>
540 #ifndef USB_GET_DEVICEINFO
541 #include <dev/usb/usb_ioctl.h>
544 int open_usb_device(int vid, int pid)
549 struct usb_device_info info;
552 dir = opendir("/dev");
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);
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");
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) {
581 static int uhid_teensy_fd = -1;
583 int teensy_open(void)
586 uhid_teensy_fd = open_usb_device(0x16C0, 0x0478);
587 if (uhid_teensy_fd < 0) return 0;
591 int teensy_write(void *buf, int len, double timeout)
595 // TODO: imeplement timeout... how??
596 r = write(uhid_teensy_fd, buf, len);
597 if (r == len) return 1;
601 void teensy_close(void)
603 if (uhid_teensy_fd >= 0) {
604 close(uhid_teensy_fd);
609 int hard_reboot(void)
613 rebootor_fd = open_usb_device(0x16C0, 0x0477);
614 if (rebootor_fd < 0) return 0;
615 r = write(rebootor_fd, "reboot", 6);
618 if (r == 6) return 1;
626 /****************************************************************/
628 /* Read Intel Hex File */
630 /****************************************************************/
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
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);
644 int read_intel_hex(const char *filename)
652 for (i=0; i<MAX_MEMORY_SIZE; i++) {
653 firmware_image[i] = 0xFF;
654 firmware_mask[i] = 0;
658 fp = fopen(filename, "r");
660 //printf("Unable to read file %s\n", filename);
665 if (!fgets(buf, sizeof(buf), fp)) break;
668 if (parse_hex_line(buf) == 0) {
669 printf("Warning, HEX parse error line %d\n", lineno);
673 if (end_record_seen) break;
674 if (feof(stdin)) break;
681 /* from ihex.c, at http://www.pjrc.com/tech/8051/pm2_docs/intel-hex.html */
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[] */
690 parse_hex_line(char *line)
693 int sum, len, cksum, i;
697 if (line[0] != ':') return 0;
698 if (strlen(line) < 11) return 0;
700 if (!sscanf(ptr, "%02x", &len)) return 0;
702 if ((int)strlen(line) < (11 + (len * 2)) ) return 0;
703 if (!sscanf(ptr, "%04x", &addr)) return 0;
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;
709 sum = (len & 255) + ((addr >> 8) & 255) + (addr & 255) + (code & 255);
715 if (code == 2 && len == 2) {
716 if (!sscanf(ptr, "%04x", &i)) return 1;
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);
724 if (code == 4 && len == 2) {
725 if (!sscanf(ptr, "%04x", &i)) return 1;
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);
733 return 1; // non-data line
737 if (sscanf(ptr, "%02x", &i) != 1) return 0;
739 firmware_image[addr + extended_addr + num] = i;
740 firmware_mask[addr + extended_addr + num] = 1;
744 if (num >= 256) return 0;
746 if (!sscanf(ptr, "%02x", &cksum)) return 0;
747 if (((sum & 255) + (cksum & 255)) & 255) return 0; /* checksum error */
751 int ihex_bytes_within_range(int begin, int end)
755 if (begin < 0 || begin >= MAX_MEMORY_SIZE ||
756 end < 0 || end >= MAX_MEMORY_SIZE) {
759 for (i=begin; i<=end; i++) {
760 if (firmware_mask[i]) return 1;
765 void ihex_get_data(int addr, int len, unsigned char *bytes)
769 if (addr < 0 || len < 0 || addr + len >= MAX_MEMORY_SIZE) {
770 for (i=0; i<len; i++) {
775 for (i=0; i<len; i++) {
776 if (firmware_mask[addr]) {
777 bytes[i] = firmware_image[addr];
785 int memory_is_blank(int addr, int block_size)
787 if (addr < 0 || addr > MAX_MEMORY_SIZE) return 1;
789 while (block_size && addr < MAX_MEMORY_SIZE) {
790 if (firmware_mask[addr] && firmware_image[addr] != 255) return 0;
800 /****************************************************************/
804 /****************************************************************/
806 int printf_verbose(const char *format, ...)
811 va_start(ap, format);
813 r = vprintf(format, ap);
820 void delay(double seconds)
823 Sleep(seconds * 1000.0);
825 usleep(seconds * 1000000.0);
829 void die(const char *str, ...)
834 vfprintf(stderr, str, ap);
835 fprintf(stderr, "\n");
840 #define strcasecmp stricmp
843 void parse_options(int argc, char **argv)
848 for (i=1; i<argc; i++) {
850 //printf("arg: %s\n", 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) {
860 } else if (strncmp(arg, "-mmcu=", 6) == 0) {
861 if (strcasecmp(arg+6, "at90usb162") == 0) {
864 } else if (strcasecmp(arg+6, "atmega32u4") == 0) {
867 } else if (strcasecmp(arg+6, "at90usb646") == 0) {
870 } else if (strcasecmp(arg+6, "at90usb1286") == 0) {
873 #if defined(USE_LIBUSB)
874 } else if (strcasecmp(arg+6, "mk20dx128") == 0) {
877 } else if (strcasecmp(arg+6, "mk20dx256") == 0) {
882 die("Unknown MCU type\n");