5 // Created by Nathan Oates on Sun Aug 01 2004.
6 // Copyright (c) 2004-7 Nathan Oates nathan@noates.com All rights reserved.
9 /* This file was modified by Kalle Olavi Niemitalo on 2007-10-18. */
11 // includes code based on uproar, license noted below:
13 // Copyright (c) 2001 Kasima Tharnpipitchai <me@kasima.org>
17 * This source code is free software; you can redistribute it and/or
18 * modify it under the terms of the GNU Public License as published
19 * by the Free Software Foundation; either version 2 of the License,
20 * or (at your option) any later version.
22 * This source code is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
25 * Please refer to the GNU Public License for more details.
27 * You should have received a copy of the GNU Public License along with
28 * this source code; if not, write to:
29 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 /* Much of the code that initializes and closes the device is from Apple
33 * and is released under the license below.
37 * © Copyright 2001 Apple Computer, Inc. All rights reserved.
39 * IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. (“Apple”) in
40 * consideration of your agreement to the following terms, and your use, installation,
41 * modification or redistribution of this Apple software constitutes acceptance of these
42 * terms. If you do not agree with these terms, please do not use, install, modify or
43 * redistribute this Apple software.
45 * In consideration of your agreement to abide by the following terms, and subject to these
46 * terms, Apple grants you a personal, non exclusive license, under Apple’s copyrights in this
47 * original Apple software (the “Apple Software”), to use, reproduce, modify and redistribute
48 * the Apple Software, with or without modifications, in source and/or binary forms; provided
49 * that if you redistribute the Apple Software in its entirety and without modifications, you
50 * must retain this notice and the following text and disclaimers in all such redistributions
51 * of the Apple Software. Neither the name, trademarks, service marks or logos of Apple
52 * Computer, Inc. may be used to endorse or promote products derived from the Apple Software
53 * without specific prior written permission from Apple. Except as expressly stated in this
54 * notice, no other rights or licenses, express or implied, are granted by Apple herein,
55 * including but not limited to any patent rights that may be infringed by your derivative
56 * works or by other works in which the Apple Software may be incorporated.
58 * The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES,
59 * EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-
60 * INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE
61 * SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
63 * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
65 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
66 * REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
67 * WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
68 * OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
76 #include <mach/mach.h>
77 #include <IOKit/IOCFPlugIn.h>
78 #include <CoreFoundation/CFNumber.h>
80 #import "DataHandler.h"
81 #import "TFUSBController.h"
82 #import "TFUSBControllerCommunicationBlock.h"
83 #import "UIElements.h"
85 static void hexDump(UInt8 *buf, int len);
86 static int doSend(IOUSBDeviceInterface197 **dev,
87 IOUSBInterfaceInterface197 **intf, UInt8 *outBuf, UInt32 len, int type);
88 static int doRecv(IOUSBDeviceInterface197 **dev,
89 IOUSBInterfaceInterface197 **intf, UInt8 *inBuf, UInt32 dataLen, int type);
90 static int dealWithInterface(io_service_t usbInterfaceRef,
91 USBDeviceContext *device);
92 static int dealWithDevice(io_service_t usbDeviceRef, USBDeviceContext *device);
93 static int initDevice(USBDeviceContext *device);
97 static int kBlockSize;
98 static int connectedSpeed;
100 @interface TFUSBController (PrivateMethods)
103 - (NSData*) sendCommand:(NSData*) fullyPackagedCommand
104 toDevice:(USBDeviceContext*)device expectResponse:(BOOL) getResponse
105 careForReturn:(BOOL) careFactor;
107 // Protocol message sequences
108 - (id) getFileListForPath:(NSString*)path;
109 - (void) turnTurboOn:(BOOL) turnOn;
110 - (void) renameFile:(NSString*) oldName withName:(NSString*)newName atPath:(NSString*)currentPath;
111 - (void) makeFolder:(NSString*)newName atPath:(NSString*)currentPath;
112 - (void) checkUSB:(USBDeviceContext*)device;
115 - (UIElements*) uiElements;
116 - (void) updateProgress:(NSDictionary*) inDict;
117 - (NSString*) elapsedTime:(NSTimeInterval) totalSeconds;
120 - (BOOL) hasPriorityTransfer;
121 - (NSDictionary*) nextTransferAndQueue:(NSMutableArray**)queue;
122 - (void) removeTransfer:(NSDictionary*)transfer fromQueue:(NSMutableArray*)queue;
126 #define TopfieldVendorID 4571
130 #define TF5kProdID 4096
135 // ---------------------------------------------------------------------------
136 #pragma mark Functions outside TFUSBController
137 // ---------------------------------------------------------------------------
140 hexDump(UInt8 *buf, int len)
142 int row, col, maxrows;
145 if (len % 16) maxrows++;
146 for (row=0; row< maxrows; row++) {
147 for (col=0; col<16; col++) {
148 if (!(col%2)) printf(" ");
149 printf("%02x", buf[row*16 + col] & 0xff);
152 for (col=0; col<16; col++) {
153 if ((buf[row*16 + col]>32) && (buf[row*16 + col]<126)) {
154 printf("%c", buf[row*16 + col]);
156 else { printf("."); }
163 doSend(IOUSBDeviceInterface197 **dev, IOUSBInterfaceInterface197 **intf,
164 UInt8 *outBuf, UInt32 len, int type)
170 printf(("sending:\n"));
171 hexDump(outBuf, len);
173 sendLen = ((len/kBlockSize))*kBlockSize;
174 if (len % kBlockSize)
175 sendLen += kBlockSize;
176 if ((sendLen % 0x200) == 0)
177 sendLen += kBlockSize;
179 err = (*intf)->WritePipeTO(intf, 1, outBuf, sendLen, 1000, 20000);
181 printf("write err: %08x\n", err);
188 doRecv(IOUSBDeviceInterface197 **dev, IOUSBInterfaceInterface197 **intf,
189 UInt8 *inBuf, UInt32 dataLen, int type)
194 if (dataLen > kMaxXferSize) return 1;
196 len = (dataLen/kBlockSize) * kBlockSize;
197 if (dataLen % kBlockSize)
200 err = (*intf)->ReadPipeTO(intf, 2, (void *)inBuf, &len, 1000, 20000);
202 printf("read err 2: %08x\n", err);
203 printf("resetting\n");
204 err = (*intf)->ClearPipeStallBothEnds(intf, 2);
209 printf(("receiving: \n"));
216 dealWithInterface(io_service_t usbInterfaceRef, USBDeviceContext *device)
219 IOCFPlugInInterface **iodev; // requires <IOKit/IOCFPlugIn.h>
220 IOUSBInterfaceInterface197 **intf;
221 IOUSBDeviceInterface197 **dev;
223 UInt8 numPipes, confNum, dSpeed;
226 err = IOCreatePlugInInterfaceForService(usbInterfaceRef, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &iodev, &score);
229 printf("dealWithInterface: unable to create plugin. ret = %08x, iodev = %p\n", err, iodev);
230 return kUproarDeviceErr;
232 err = (*iodev)->QueryInterface(iodev, CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID)&(device->intf));
233 (*iodev)->Release(iodev); // done with this
237 printf("dealWithInterface: unable to create a device interface. ret = %08x, intf = %p\n", err, intf);
238 return kUproarDeviceErr;
242 err = (*intf)->USBInterfaceOpen(intf);
245 printf("dealWithInterface: unable to open interface. ret = %08x\n", err);
246 return kUproarDeviceErr;
248 err = (*intf)->GetNumEndpoints(intf, &numPipes);
251 printf("dealWithInterface: unable to get number of endpoints. ret = %08x\n", err);
252 return kUproarDeviceErr;
255 printf("dealWithInterface: found %d pipes\n", numPipes);
257 err = (*intf)->GetConfigurationValue(intf, &confNum);
258 err = (*dev)->GetDeviceSpeed(dev, &dSpeed);
264 printf("confnum: %08x, dspeed: %08x, blockS:%i\n", confNum, dSpeed, kBlockSize);
265 connectedSpeed = dSpeed;
266 return kUproarSuccess;
271 dealWithDevice(io_service_t usbDeviceRef, USBDeviceContext *device)
274 IOCFPlugInInterface **iodev; // requires <IOKit/IOCFPlugIn.h>
275 IOUSBDeviceInterface197 **dev;
278 IOUSBConfigurationDescriptorPtr confDesc;
279 IOUSBFindInterfaceRequest interfaceRequest;
280 io_iterator_t iterator;
281 io_service_t usbInterfaceRef;
285 err = IOCreatePlugInInterfaceForService(usbDeviceRef, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &iodev, &score);
288 printf("dealWithDevice: unable to create plugin. ret = %08x, iodev = %p\n", err, iodev);
289 return kUproarDeviceErr;
291 err = (*iodev)->QueryInterface(iodev, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID)&(device->dev));
292 (*iodev)->Release(iodev);
297 printf("dealWithDevice: unable to create a device interface. ret = %08x, dev = %p\n", err, dev);
298 return kUproarDeviceErr;
300 err = (*dev)->USBDeviceOpen(dev);
303 printf("dealWithDevice: unable to open device. ret = %08x\n", err);
304 return kUproarDeviceErr;
306 err = (*dev)->GetNumberOfConfigurations(dev, &numConf);
309 printf("dealWithDevice: unable to obtain the number of configurations. ret = %08x\n", err);
310 return kUproarDeviceErr;
312 printf("dealWithDevice: found %d configurations\n", numConf);
313 err = (*dev)->GetConfigurationDescriptorPtr(dev, 0, &confDesc); // get the first config desc (index 0)
316 printf("dealWithDevice:unable to get config descriptor for index 0\n");
317 return kUproarDeviceErr;
319 err = (*dev)->SetConfiguration(dev, confDesc->bConfigurationValue);
322 printf("dealWithDevice: unable to set the configuration\n");
323 return kUproarDeviceErr;
326 interfaceRequest.bInterfaceClass = kIOUSBFindInterfaceDontCare; // requested class
327 interfaceRequest.bInterfaceSubClass = kIOUSBFindInterfaceDontCare; // requested subclass
328 interfaceRequest.bInterfaceProtocol = kIOUSBFindInterfaceDontCare; // requested protocol
329 interfaceRequest.bAlternateSetting = kIOUSBFindInterfaceDontCare; // requested alt setting
331 err = (*dev)->CreateInterfaceIterator(dev, &interfaceRequest, &iterator);
334 printf("dealWithDevice: unable to create interface iterator\n");
335 return kUproarDeviceErr;
338 while (usbInterfaceRef = IOIteratorNext(iterator))
340 printf("found interface: %#jx\n", (uintmax_t)usbInterfaceRef);
341 err = dealWithInterface(usbInterfaceRef, device);
342 IOObjectRelease(usbInterfaceRef); // no longer need this reference
346 IOObjectRelease(iterator);
348 if ((!found) || (err))
349 return kUproarDeviceErr;
351 return kUproarSuccess;
355 initDevice(USBDeviceContext *device)
357 mach_port_t masterPort = 0;
359 CFMutableDictionaryRef matchingDictionary = 0; // requires <IOKit/IOKitLib.h>
360 short idVendor = TopfieldVendorID;
361 short idProduct = TF5kProdID;
362 CFNumberRef numberRef;
363 io_iterator_t iterator = 0;
364 io_service_t usbDeviceRef;
367 err = IOMasterPort(bootstrap_port, &masterPort);
371 printf("Anchortest: could not create master port, err = %08x\n", err);
374 matchingDictionary = IOServiceMatching(kIOUSBDeviceClassName); // requires <IOKit/usb/IOUSBLib.h>
375 if (!matchingDictionary)
377 printf("Anchortest: could not create matching dictionary\n");
380 numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &idVendor);
383 printf("Anchortest: could not create CFNumberRef for vendor\n");
386 CFDictionaryAddValue(matchingDictionary, CFSTR(kUSBVendorName), numberRef);
387 CFRelease(numberRef);
389 numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &idProduct);
392 printf("Anchortest: could not create CFNumberRef for product\n");
395 CFDictionaryAddValue(matchingDictionary, CFSTR(kUSBProductName), numberRef);
396 CFRelease(numberRef);
399 err = IOServiceGetMatchingServices(masterPort, matchingDictionary, &iterator);
400 matchingDictionary = 0; // this was consumed by the above call
402 while (usbDeviceRef = IOIteratorNext(iterator))
404 printf("Found device %#jx\n", (uintmax_t)usbDeviceRef);
405 err = dealWithDevice(usbDeviceRef, device);
406 IOObjectRelease(usbDeviceRef); // no longer need this reference
411 IOObjectRelease(iterator);
413 mach_port_deallocate(mach_task_self(), masterPort);
414 if ((!found) || (err))
415 return kUproarDeviceErr;
417 return kUproarSuccess;
420 @implementation TFUSBController (PrivateMethods)
422 // ---------------------------------------------------------------------------
423 #pragma mark Low-level USB (PrivateMethods)
424 // ---------------------------------------------------------------------------
426 - (NSData*) sendCommand:(NSData*) fullyPackagedCommand
427 toDevice:(USBDeviceContext*)device expectResponse:(BOOL) getResponse
428 careForReturn:(BOOL) careFactor{
430 int cmdLength = [fullyPackagedCommand length];
431 unsigned char outBuffer[cmdLength];
432 memset(outBuffer, 0, cmdLength);
433 // NSLog(@"send: %@", [fullyPackagedCommand description]);
434 [fullyPackagedCommand getBytes:outBuffer];
436 err = doSend(device->dev, device->intf, outBuffer, cmdLength, 2);
438 NSLog(@"sendError: %08x\n");
440 if (! getResponse) return nil;
442 int inLen = 0xFFFF; // i think this is biggest needed?
443 unsigned char inBuf[inLen];
444 memset(inBuf, 0, inLen);
445 err = doRecv(device->dev, device->intf, inBuf, inLen, 2);
447 NSLog(@"inError: %08x\n", err);
449 if (! careFactor) return nil;
450 NSMutableData* data = [NSMutableData dataWithBytes:inBuf length:inLen];
451 data = [self swap:data];
452 inLen = inBuf[1]*256 + inBuf[0]; // work out how long the response really is. NB data is flipped, but inBuf still isn't
453 return [data subdataWithRange:(NSRange) {0,inLen}];
456 // ---------------------------------------------------------------------------
457 #pragma mark Protocol message sequences (PrivateMethods)
458 // ---------------------------------------------------------------------------
460 - (id) getFileListForPath:(NSString*) path {
461 if (myContext == nil)
464 NSData* hddListCmd = [self prepareCmdHddDirWithPath:path];
465 if (hddListCmd == nil)
468 [self checkUSB:myContext]; // sends cancel and waits for response
469 int contiguousErrors = 0;
470 [[dh fileList] removeAllObjects];
471 NSData* response = [self sendCommand:hddListCmd toDevice:myContext
472 expectResponse:YES careForReturn:YES];
473 while (response != nil && contiguousErrors++ < 5) {
474 TopfieldUSBEcode ecode = USB_OK;
475 if (![self isCommunicationBlockValid:response error:NULL ecode:&ecode]) {
476 response = [self sendCommand:[self prepareFailWithECode:ecode]
477 toDevice:myContext expectResponse:YES careForReturn:YES];
478 } else switch ([self cmdFromCommunicationBlock:response]) {
480 // [statusField setStringValue:NSLocalizedString(@"LAST_ERROR", @"Error on last command.")];
481 [[dh fileList] removeAllObjects];
482 response = [self sendCommand:hddListCmd toDevice:myContext
483 expectResponse:YES careForReturn:YES];
486 contiguousErrors = 0;
488 // Swapping sometimes adds a byte of padding. The following uses
489 // only complete 144-byte structures and so ignores such padding.
490 for (i=0; 8+(i+1)*114 <= [response length]; i++) {
491 NSData* typeFile = [response subdataWithRange:(NSRange) {8+i*114,114}];
492 NSMutableDictionary* tfFile = [dh newTFFileFromSwappedHexData:typeFile];
493 if (![[tfFile objectForKey:@"name"] isEqualToString:@".."]) {
494 [dh convertRawDataToUseful:tfFile];
495 [[dh fileList] addObject:tfFile];
499 response = [self sendCommand:[self prepareSuccess]
500 toDevice:myContext expectResponse:YES careForReturn:YES];
502 case USB_DataHddDirEnd:
503 contiguousErrors = 0;
507 [self checkUSB:myContext]; // cancel whatever is going on
508 [[dh fileList] removeAllObjects];
509 response = [self sendCommand:hddListCmd toDevice:myContext
510 expectResponse:YES careForReturn:YES];
515 [tableView reloadData];
516 [[self uiElements] tableView:tableView didClickTableColumn:[[self uiElements]selectedColumn]];
517 [[self uiElements] tableView:tableView didClickTableColumn:[[self uiElements]selectedColumn]]; //twice so get the same sort as before
521 - (void) turnTurboOn:(BOOL) turnOn {
522 if (![[[self uiElements] isConnected] intValue]) return;
523 [self checkUSB:myContext];
524 NSData* turboCommand = [self prepareCmdTurboWithMode:(turnOn ? 1 : 0)];
525 [self sendCommand:turboCommand toDevice:myContext expectResponse:YES careForReturn:NO];
528 - (void) renameFile:(NSString*) oldName withName:(NSString*)newName atPath:(NSString*)currentPath {
529 NSLog(@"%@,%@,%@", oldName, newName, currentPath);
530 [self checkUSB:myContext];
531 NSString* oldFname = [self fnameForFile:oldName atPath:currentPath];
532 NSString* newFname = [self fnameForFile:newName atPath:currentPath];
533 NSData* fileRenCmd = [self prepareCmdHddRenameFromFname:oldFname toFname:newFname];
534 [self sendCommand:fileRenCmd toDevice:myContext expectResponse:YES careForReturn:NO];
537 - (void) makeFolder:(NSString*)newName atPath:(NSString*)currentPath {
538 [self checkUSB:myContext];
539 NSString* fname = [self fnameForFile:newName atPath:currentPath];
540 NSData* newFoldCmd = [self prepareCmdHddCreateDirWithFname:fname];
541 NSData* usbCancel = [self prepareCancel];
542 [self sendCommand:usbCancel toDevice:myContext expectResponse:YES careForReturn:NO];
543 [self sendCommand:newFoldCmd toDevice:myContext expectResponse:YES careForReturn:NO];
546 - (void) checkUSB:(USBDeviceContext*)device {
547 NSData* usbCancel = [self prepareCancel];
549 for (retry = 0; retry < 8; ++retry) {
550 NSData* block = [self sendCommand:usbCancel toDevice:device
551 expectResponse:YES careForReturn:YES];
552 NSError* error = nil;
553 if (![self isCommunicationBlockValid:block error:&error ecode:NULL]) {
554 NSLog(@"bad response to cancel: %@", [error localizedDescription]);
557 // The received value might not be in enum TopfieldUSBCmd.
558 UInt32 cmd = [self cmdFromCommunicationBlock:block];
559 if (cmd != USB_Success) {
560 NSLog(@"response to cancel was %#x rather than success", (unsigned) cmd);
565 // tell someone that no longer connected here??
568 // ---------------------------------------------------------------------------
569 #pragma mark User interface (PrivateMethods)
570 // ---------------------------------------------------------------------------
572 - (UIElements*) uiElements {
573 return [NSApp delegate];
576 -(void) updateProgress:(NSDictionary*) inDict {
577 NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
578 double offset = [[inDict objectForKey:@"offset"] doubleValue];
579 double size = [[inDict objectForKey:@"size"] doubleValue];
580 NSDate* startTime = [inDict objectForKey:@"startTime"];
581 [progressBar setDoubleValue:((double)offset/size*100)];
582 [progressBar displayIfNeeded];
583 [progressTime setStringValue:[self elapsedTime:[[NSDate date] timeIntervalSinceDate:startTime]]];
584 [progressTime displayIfNeeded];
588 - (NSString*) elapsedTime:(NSTimeInterval) totalSeconds {
591 char sp = 20; //padding
592 int hours = (totalSeconds / 3600); // returns number of whole hours fitted in totalSecs
595 int minutes = ((totalSeconds / 60) - hours*60); // Whole minutes
598 int seconds = ((long) totalSeconds % 60); // Here we can use modulo to get num secs NOT fitting in whole minutes (60 secs)
601 return [NSString stringWithFormat:@"%c%i:%c%i:%c%i", hp, hours, mp, minutes, sp, seconds];
604 // ---------------------------------------------------------------------------
605 #pragma mark Queue management (PrivateMethods)
606 // ---------------------------------------------------------------------------
608 - (BOOL) hasPriorityTransfer {
610 @synchronized (self) {
611 ret = ([priorityTransferQueue count] > 0);
616 - (NSDictionary*) nextTransferAndQueue:(NSMutableArray**)queueOut {
617 NSDictionary* transfer = nil;
618 NSMutableArray* queue = nil;
620 @synchronized (self) {
621 if ([priorityTransferQueue count] > 0) {
622 queue = priorityTransferQueue;
623 transfer = [queue objectAtIndex:0];
624 } else if ([transferQueue count] > 0) {
625 queue = transferQueue;
626 transfer = [queue objectAtIndex:0];
629 [[transfer retain] autorelease];
636 - (void) removeTransfer:(NSDictionary*)transfer
637 fromQueue:(NSMutableArray*)queue
639 @synchronized (self) {
640 [queue removeObjectIdenticalTo:transfer];
646 @implementation TFUSBController
648 // ---------------------------------------------------------------------------
649 #pragma mark Low-level USB
650 // ---------------------------------------------------------------------------
652 - (void) closeDevice:(USBDeviceContext *)device
654 IOUSBInterfaceInterface197 **intf;
655 IOUSBDeviceInterface197 **dev;
661 err = (*intf)->USBInterfaceClose(intf);
664 printf("dealWithInterface: unable to close interface. ret = %08x\n", err);
666 err = (*intf)->Release(intf);
669 printf("dealWithInterface: unable to release interface. ret = %08x\n", err);
672 err = (*dev)->USBDeviceClose(dev);
675 printf("dealWithDevice: error closing device - %08x\n", err);
676 (*dev)->Release(dev);
678 err = (*dev)->Release(dev);
681 printf("dealWithDevice: error releasing device - %08x\n", err);
685 - (USBDeviceContext*) initializeUSB {
686 USBDeviceContext *device;
689 device = malloc(sizeof(USBDeviceContext));
690 err = initDevice(device);
692 printf("Could not connect to Topfield\n");
696 printf("Connected to Topfield\n\n");
701 // ---------------------------------------------------------------------------
702 #pragma mark Protocol message sequences
703 // ---------------------------------------------------------------------------
705 - (int) getFile:(NSDictionary*)fileInfo forPath:(NSString*)currentPath
706 toSaveTo:(NSString*)savePath beginAtOffset:(unsigned long long) offset
707 withLooping:(BOOL)looping existingTime:(NSTimeInterval)existingTime {
708 // [progressBar setDoubleValue:0];
709 // [progressTime setDoubleValue:0];
710 NSString* nameOnToppy = [fileInfo objectForKey:@"name"];
711 [[[self uiElements] currentlyField] setStringValue:
712 [NSLocalizedString(@"DOWNLOADING", @"Downloading: ") stringByAppendingString:nameOnToppy]];
713 [[[self uiElements] connectLight] setImage:[NSImage imageNamed:@"blink.tiff"]];
714 [[[self uiElements] currentlyField] displayIfNeeded];
715 //construct file send request
716 NSNumber* fileSize = [fileInfo objectForKey:@"fileSize"];
718 //prepackage commands to send
719 NSData* fileSendCmd = [self prepareCmdHddFileSendWithDirection:USB_FileToHost
720 fname:[self fnameForFile:nameOnToppy atPath:currentPath]
722 NSData* usbSuccess = [self prepareSuccess];
723 NSData* usbCancel = [self prepareCancel];
728 [self turnTurboOn:YES];
730 [self checkUSB:myContext]; //turbo has a check itself
731 [self sendCommand:fileSendCmd toDevice:myContext expectResponse:YES careForReturn:NO];
733 NSDate* startTime = [NSDate date];
734 startTime = [startTime addTimeInterval:(0-existingTime)];
735 // send start request and get response
736 NSData *data = [self sendCommand:usbSuccess toDevice:myContext expectResponse:YES careForReturn:YES];
737 const UInt32 rW_bigendian = EndianU32_NtoB(USB_DataHddFileData);
738 NSData *responseWanted = [NSData dataWithBytes:&rW_bigendian length:4];
739 if ([data length] < 16) {
740 NSLog(@"Incorrect Data length");
743 NSData *responseToCheck = [data subdataWithRange:(NSRange) {4,4}];
744 if (![responseWanted isEqualToData:responseToCheck]) {
745 NSLog(@"Unexpected response from Toppy during download");
749 // clean up data and prepare path to save it
750 NSData* header = [data subdataWithRange:(NSRange) {4,4}]; //cmd data
751 NSData* finalData = [data subdataWithRange:(NSRange) {16,[data length]-16}];
753 // first initialize a file of the right name, as NSFileHandle requires an existing file to work on
755 [[NSData dataWithBytes:"\0" length:1] writeToFile:savePath atomically:NO]; // write 0x00 to initialize (overwritten later)
756 NSFileHandle* outFile = [NSFileHandle fileHandleForWritingAtPath:savePath];
757 [outFile seekToFileOffset:offset];
758 [outFile writeData:finalData];
759 if (looping) { // loop for multiple data sends (ie files > 64k)
761 if ([fileSize isGreaterThan:[NSNumber numberWithDouble:1048576]]) {
763 NSLog(@"large file detected - low GUI update rate");
766 const UInt32 test_bigendian = EndianU32_NtoB(USB_DataHddFileData);
767 double amountReceived = 0xfe00 + offset;
768 NSData* testData = [NSData dataWithBytes:&test_bigendian length:4];
769 while ([header isEqualToData:testData] && [[[self uiElements] isConnected] intValue]) {
770 if ([self hasPriorityTransfer]) {
771 [self addTransfer:[NSDictionary dictionaryWithObjectsAndKeys:
772 fileInfo,@"filename", currentPath,@"path", savePath,@"savePath",
773 [NSNumber numberWithUnsignedLongLong:amountReceived],@"offset",
774 @"download",@"transferType", [NSNumber numberWithBool:YES],@"looping",
775 [NSNumber numberWithInt:[[NSDate date] timeIntervalSinceDate:startTime]],@"existingTime",
777 atIndex:1]; // nb adding to index 1 as the current transfer lies at 0 and will be deleted soon
778 // send reset again just to make sure!
779 [self sendCommand:usbCancel toDevice:myContext expectResponse:YES careForReturn:NO];
781 //now add the right modification date to the file
782 [[NSFileManager defaultManager]
783 changeFileAttributes:[NSDictionary
784 dictionaryWithObject:[fileInfo objectForKey:@"date"]
785 forKey:@"NSFileModificationDate"]
787 [self turnTurboOn:NO];
791 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
792 data = [self sendCommand:usbSuccess toDevice:myContext expectResponse:YES careForReturn:YES];
793 amountReceived += 0xfe00;
794 if (timesAround < 8 || timesAround % updateRate == 0) {
795 [NSThread detachNewThreadSelector:@selector(updateProgress:) toTarget:self
796 withObject:[NSDictionary dictionaryWithObjectsAndKeys:
797 [NSNumber numberWithDouble:(double)amountReceived], @"offset",
798 fileSize, @"size", startTime, @"startTime", nil]];
800 if ([data length] > 16){ //there is something to read
801 header = [[data subdataWithRange:(NSRange) {4,4}] retain]; //cmd data
802 NSData* finalData = [data subdataWithRange:(NSRange) {16,[data length]-16}];
803 [outFile writeData:finalData];
804 [outFile synchronizeFile];
810 [self sendCommand:usbCancel toDevice:myContext expectResponse:YES careForReturn:NO]; // send reset again just to make sure!
812 //now add the right modification date to the file
813 [[NSFileManager defaultManager]
814 changeFileAttributes:[NSDictionary
815 dictionaryWithObject:[fileInfo objectForKey:@"date"]
816 forKey:@"NSFileModificationDate"]
818 [self turnTurboOn:NO];
819 if (looping) [[self uiElements] finishTransfer];
823 - (void) uploadFile:(NSString*) fileToUpload ofSize:(long long) size
824 fromPath:(NSString*)curPath withAttributes:(NSData*) typeFile
825 atOffset:(unsigned long long)offset existingTime:(NSTimeInterval)existingTime {
826 NSLog(@"upload: %@,%@,%qu", fileToUpload, curPath, offset);
827 USBDeviceContext* dev = myContext;
828 // prepare Send command
829 NSMutableArray* array = [NSMutableArray arrayWithArray:[fileToUpload componentsSeparatedByString:@"/"]];
830 NSMutableString* fname = [NSMutableString stringWithString:[array lastObject]];
831 char dir = USB_FileToDevice;
832 NSMutableData* build = [NSMutableData dataWithBytes:&dir length:1];
833 short int nsize = [fname length]+[curPath length]+2;// one for slash, one for padding 0x00
834 const UInt16 nsize_bigendian = EndianU16_NtoB(nsize);
835 [build appendData:[NSData dataWithBytes:&nsize_bigendian length:2]];
836 NSData* d = [curPath dataUsingEncoding:NSISOLatin1StringEncoding];
837 [build appendData:d];
838 dir = 0x5c; // 0x5c = "/"
839 [build appendData:[NSData dataWithBytes:&dir length:1]];
840 [build appendData:[fname dataUsingEncoding:NSISOLatin1StringEncoding]];// may need to pad to 95...
841 if ([fname length] < 95)
842 [build increaseLengthBy:95-[fname length]];
844 [build appendData:[NSData dataWithBytes:&dir length:1]];
845 UInt64 offset_bigendian = EndianU64_NtoB(offset);
846 [build appendData:[NSData dataWithBytes:&offset_bigendian length:8]];
848 // prepackage commands to send
849 NSData* fileSendCmd = [self prepareCommand:USB_CmdHddFileSend withData:build];
850 NSData* fileStartCmd = [self prepareCommand:USB_DataHddFileStart withData:typeFile];
851 NSData* fileEndCmd = [self prepareDataHddFileEnd];
854 NSDate* startTime = [NSDate date];
855 startTime = [startTime addTimeInterval:(0-existingTime)];
858 [self turnTurboOn:YES];
861 // now the proper commands
862 NSData *data = [self sendCommand:fileSendCmd toDevice:dev expectResponse:YES careForReturn:YES];
863 data = [self sendCommand:fileStartCmd toDevice:dev expectResponse:YES careForReturn:YES];
864 const UInt32 rW_bigendian = EndianU32_NtoB(USB_Success);
865 NSData* responseWanted = [NSData dataWithBytes:&rW_bigendian length:4];
866 NSData* responseToCheck = nil;
868 NSFileHandle* fileHandle = [NSFileHandle fileHandleForReadingAtPath:fileToUpload];
869 [fileHandle seekToFileOffset:offset];
871 if ([self hasPriorityTransfer]) {
872 //break out and create a new transfer to continue it
873 NSLog(@"pausing upload");
874 [self addTransfer:[NSDictionary dictionaryWithObjectsAndKeys:
875 fileToUpload,@"filename",
876 [NSNumber numberWithUnsignedLongLong:size],@"fileSize",
877 curPath,@"path",typeFile,@"attributes",@"upload",@"transferType",
878 [NSNumber numberWithUnsignedLongLong:offset],@"offset",
879 [NSNumber numberWithInt:[[NSDate date] timeIntervalSinceDate:startTime]],@"existingTime",
881 atIndex:1]; //nb use index 1 as current transfer is at 0 and will be deleted
882 [self turnTurboOn:NO];
885 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
886 offset_bigendian = EndianU64_NtoB(offset);
887 NSMutableData* fileData = [NSMutableData dataWithBytes:&offset_bigendian length:8];
888 [fileData appendData:[fileHandle readDataOfLength:rate]];
890 NSData* fileDataCmd = [self prepareCommand:USB_DataHddFileData withData:fileData];
891 data = [self sendCommand:fileDataCmd toDevice:dev expectResponse:YES careForReturn:YES];
892 if ([data length] >= 8)
893 responseToCheck = [data subdataWithRange:(NSRange) {4,4}];
894 else responseToCheck = nil;
895 if (responseToCheck == nil || ![responseWanted isEqualToData:responseToCheck])
897 [NSThread detachNewThreadSelector:@selector(updateProgress:) toTarget:self
898 withObject:[NSDictionary dictionaryWithObjectsAndKeys:
899 [NSNumber numberWithDouble:(double)offset], @"offset",
900 [NSNumber numberWithDouble:(double)size], @"size",
901 startTime, @"startTime", nil]];
904 } while (offset < size && [[[self uiElements] isConnected] intValue]);
905 if ([[[self uiElements] isConnected] intValue])
906 data = [self sendCommand:fileEndCmd toDevice:dev expectResponse:YES careForReturn:YES];
907 [fileHandle closeFile];
908 [[self uiElements] goToPath:[[self uiElements]currentPath]];
909 [[self uiElements] tableView:tableView didClickTableColumn:[[self uiElements]selectedColumn]];
910 [[self uiElements] tableView:tableView didClickTableColumn:[[self uiElements]selectedColumn]]; //twice so get the same sort as before
911 [self turnTurboOn:NO];
912 [[self uiElements] finishTransfer];
915 - (void) deleteFile:(NSDictionary*)fileInfo fromPath:(NSString*)currentPath {
916 [self checkUSB:myContext];
917 NSString* fname = [self fnameForFile:[fileInfo objectForKey:@"name"]
919 NSData* fileDelCmd = [self prepareCmdHddDelWithFname:fname];
920 [self sendCommand:fileDelCmd toDevice:myContext expectResponse:YES careForReturn:NO];
923 // ---------------------------------------------------------------------------
924 #pragma mark Queue management
925 // ---------------------------------------------------------------------------
927 - (void) addPriorityTransfer:(id)newTransfer {
928 @synchronized (self) {
929 [priorityTransferQueue addObject:newTransfer];
930 NSLog(@"%i,p:%i-%@",[transferQueue count],[priorityTransferQueue count],[newTransfer objectForKey:@"transferType"]);
934 - (void) addTransfer:(id)newTransfer atIndex:(int)front { //-1 for at end
935 @synchronized (self) {
936 if (front>=0) [transferQueue insertObject:newTransfer atIndex:front];
937 else [transferQueue addObject:newTransfer];
938 NSLog(@"%i,p:%i",[transferQueue count],[priorityTransferQueue count]);
942 - (void) clearQueues {
943 @synchronized (self) {
944 [priorityTransferQueue removeAllObjects];
945 [transferQueue removeAllObjects];
946 [pausedQueue removeAllObjects];
950 - (BOOL) hasCurrentTransfer {
952 @synchronized (self) {
953 ret = ([transferQueue count] > 0);
958 - (id) currentTransferInfo {
960 @synchronized (self) {
961 if ([transferQueue count] > 0) {
962 transfer = [transferQueue objectAtIndex:0];
963 // Make a copy of the object so that it can be safely manipulated
964 // in a different thread from the original.
965 transfer = [[transfer copy] autorelease];
971 - (id) firstPausedTransferInfo {
973 @synchronized (self) {
974 if ([pausedQueue count] > 0) {
975 transfer = [pausedQueue objectAtIndex:0];
976 // Make a copy of the object so that it can be safely manipulated
977 // in a different thread from the original.
978 transfer = [[transfer copy] autorelease];
984 - (void) transfer:(id)sender {
985 while ([[[self uiElements] isConnected] intValue]) {
986 NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
987 NSMutableArray* queue = nil;
988 NSDictionary* currentTransfer = [self nextTransferAndQueue:&queue];
989 if (currentTransfer != nil) {
990 NSString* transferType = [currentTransfer objectForKey:@"transferType"];
991 if ([transferType isEqualToString:@"fileList"]) {
992 [self getFileListForPath:[currentTransfer objectForKey:@"path"]];
994 else if ([transferType isEqualToString:@"turbo"]) {
995 // [self turnTurboOn:[[currentTransfer objectForKey:@"turboOn"] boolValue]];
997 else if ([transferType isEqualToString:@"rename"]) {
998 [self renameFile:[currentTransfer objectForKey:@"oldName"]
999 withName:[currentTransfer objectForKey:@"newName"]
1000 atPath:[currentTransfer objectForKey:@"path"]];
1002 else if ([transferType isEqualToString:@"newFolder"]) {
1003 [self makeFolder:[currentTransfer objectForKey:@"newName"] atPath:[currentTransfer objectForKey:@"path"]];
1005 else if ([transferType isEqualToString:@"delete"]) {
1006 [self deleteFile:[currentTransfer objectForKey:@"file"] fromPath:[currentTransfer objectForKey:@"path"]];
1008 else if ([transferType isEqualToString:@"pause"]) {
1009 @synchronized (self) {
1010 if ([transferQueue count] != 0) {
1011 NSArray* toPause = [transferQueue filteredArrayUsingPredicate:
1012 [NSPredicate predicateWithFormat:@"(filename = %@)",
1013 [currentTransfer objectForKey:@"filename"]]];
1014 if ([toPause count] > 1) NSLog(@"multiple pauses?");
1016 [pausedQueue addObjectsFromArray:toPause];
1017 [transferQueue removeObjectsInArray:toPause];
1022 else if ([transferType isEqualToString:@"resume"]) {
1023 @synchronized (self) {
1024 if ([pausedQueue count] != 0) {
1025 NSArray* toResume = [pausedQueue filteredArrayUsingPredicate:
1026 [NSPredicate predicateWithFormat:@"(filename = %@)",
1027 [currentTransfer objectForKey:@"filename"]]];
1028 if ([toResume count] > 1) NSLog(@"multiple resumes?");
1030 [transferQueue addObjectsFromArray:toResume];
1031 [pausedQueue removeObjectsInArray:toResume];
1036 else if ([transferType isEqualToString:@"download"]) {
1037 [self getFile:[currentTransfer objectForKey:@"filename"]
1038 forPath:[currentTransfer objectForKey:@"path"]
1039 toSaveTo:[currentTransfer objectForKey:@"savePath"]
1040 beginAtOffset:[[currentTransfer objectForKey:@"offset"] unsignedLongLongValue]
1041 withLooping:[[currentTransfer objectForKey:@"looping"] boolValue]
1042 existingTime:[[currentTransfer objectForKey:@"existingTime"] intValue]];
1044 else if ([transferType isEqualToString:@"upload"]) {
1045 [self uploadFile:[currentTransfer objectForKey:@"filename"]
1046 ofSize:[[currentTransfer objectForKey:@"fileSize"] unsignedLongLongValue]
1047 fromPath:[currentTransfer objectForKey:@"path"]
1048 withAttributes:[currentTransfer objectForKey:@"attributes"]
1049 atOffset:[[currentTransfer objectForKey:@"offset"] unsignedLongLongValue]
1050 existingTime:[[currentTransfer objectForKey:@"existingTime"] intValue]];
1053 NSLog(@"Unrecognized transfer type: %@", transferType);
1055 [self removeTransfer:currentTransfer fromQueue:queue];
1062 // ---------------------------------------------------------------------------
1063 #pragma mark User interface
1064 // ---------------------------------------------------------------------------
1066 -(void) setProgressBar:(NSProgressIndicator*)bar time:(NSTextField*)timeField turbo:(NSButton*)turbo{
1068 progressTime = timeField;
1072 - (void) setDH:(id)newDH tableView:(id)tv {
1077 // ---------------------------------------------------------------------------
1078 #pragma mark Miscellaneous
1079 // ---------------------------------------------------------------------------
1082 if (self = [super init]) {
1085 transferQueue = [[NSMutableArray arrayWithCapacity:1] retain];
1086 pausedQueue = [[NSMutableArray arrayWithCapacity:1] retain];
1087 priorityTransferQueue = [[NSMutableArray arrayWithCapacity:1] retain];
1093 return connectedSpeed;
1096 -(void) setDebug:(int)mode {
1098 NSLog(@"Debug level: %i", debug);
1101 -(void) setRate:(int) newRate {
1103 NSLog(@"New rate set: %i", rate);