+ printf("HM-CFG-USB firmware version: %u, used credits: %u%%\n", rdata.version, rdata.credits);
+
+ if (rdata.credits >= 40) {
+ printf("\nRebooting HM-CFG-USB to avoid running out of credits\n\n");
+
+ if (!dev.hmcfgusb->bootloader) {
+ printf("HM-CFG-USB not in bootloader mode, entering bootloader.\n");
+ printf("Waiting for device to reappear...\n");
+
+ do {
+ if (dev.hmcfgusb) {
+ if (!dev.hmcfgusb->bootloader)
+ hmcfgusb_enter_bootloader(dev.hmcfgusb);
+ hmcfgusb_close(dev.hmcfgusb);
+ }
+ sleep(1);
+ } while (((dev.hmcfgusb = hmcfgusb_init(parse_hmcfgusb, &rdata)) == NULL) || (!dev.hmcfgusb->bootloader));
+ }
+
+ if (dev.hmcfgusb->bootloader) {
+ printf("HM-CFG-USB in bootloader mode, rebooting\n");
+
+ do {
+ if (dev.hmcfgusb) {
+ if (dev.hmcfgusb->bootloader)
+ hmcfgusb_leave_bootloader(dev.hmcfgusb);
+ hmcfgusb_close(dev.hmcfgusb);
+ }
+ sleep(1);
+ } while (((dev.hmcfgusb = hmcfgusb_init(parse_hmcfgusb, &rdata)) == NULL) || (dev.hmcfgusb->bootloader));
+ }
+ }
+
+ printf("\n\nHM-CFG-USB opened\n\n");
+
+ if (new_hmid && (my_hmid != new_hmid)) {
+ printf("Changing hmid from %06x to %06x\n", my_hmid, new_hmid);
+
+ memset(out, 0, sizeof(out));
+ out[0] = 'A';
+ out[1] = (new_hmid >> 16) & 0xff;
+ out[2] = (new_hmid >> 8) & 0xff;
+ out[3] = new_hmid & 0xff;
+
+ hmcfgusb_send(dev.hmcfgusb, out, sizeof(out), 1);
+
+ my_hmid = new_hmid;
+ }
+
+ if (kNo) {
+ printf("Setting AES-key\n");
+
+ memset(out, 0, sizeof(out));
+ out[0] = 'Y';
+ out[1] = 0x01;
+ out[2] = kNo;
+ out[3] = sizeof(key);
+ memcpy(&(out[4]), key, sizeof(key));
+ hmcfgusb_send(dev.hmcfgusb, out, sizeof(out), 1);
+
+ memset(out, 0, sizeof(out));
+ out[0] = 'Y';
+ out[1] = 0x02;
+ out[2] = 0x00;
+ out[3] = 0x00;
+ hmcfgusb_send(dev.hmcfgusb, out, sizeof(out), 1);
+
+ memset(out, 0, sizeof(out));
+ out[0] = 'Y';
+ out[1] = 0x03;
+ out[2] = 0x00;
+ out[3] = 0x00;
+ hmcfgusb_send(dev.hmcfgusb, out, sizeof(out), 1);
+ }