hid_bootloader_cli.c 26 KB

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