Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

teensy_loader_cli.c 23KB

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