how to detect USB insertion in imac? - objective-c

how to detect USB insertion in imac using objective c? im trying to write an app running in background to detect if there is any usb being inserted to the imac. is there any code to do that in objective c?

OS X should automatically do this for you, unless you are trying to look for something specific. There is a file floating around the net, called "MobileDevice.h", that should give you some idea of where to start on checking if a device is inserted into USB (whether it's connected or not).
Here is a link to one place, as there are many others.
MobileDevice.h on Pastie
I hope this helps, as it has a USB listener, that you may be able to use.
EDIT
Code from Pastie:
syslog.c
#include "MobileDevice.h"
#include <assert.h>
static void cb(am_device_notification_callback_info *info, void *foo) {
struct am_device *dev;
CFStringRef error;
printf("... %x\n", info->msg);
if(info->msg == ADNCI_MSG_CONNECTED) {
dev = info->dev;
afc_connection *socket = NULL;
AMDeviceConnect(dev);
assert(AMDeviceIsPaired(dev));
assert(AMDeviceValidatePairing(dev) == 0);
assert(AMDeviceStartSession(dev) == 0);
AMDeviceStartService(dev, CFSTR("com.apple.syslog_relay"), (void*)&socket, NULL);
printf("socket=%p\n", socket);
char c;
while(recv((int) socket, &c, 1, 0) == 1) {
if(c != 0)
putchar(c);
}
}
}
int main(int argc, char **argv) {
am_device_notification *notif;
int ret = AMDeviceNotificationSubscribe(cb, 0, 0, NULL, &notif);
CFRunLoopRun();
}
MobileDevice.h
/* ----------------------------------------------------------------------------
* MobileDevice.h - interface to MobileDevice.framework
* $LastChangedDate: 2007-07-09 18:59:29 -0700 (Mon, 09 Jul 2007) $
*
* Copied from http://iphonesvn.halifrag.com/svn/iPhone/
* With modifications from Allen Porter and Scott Turner
*
* ------------------------------------------------------------------------- */
#ifndef MOBILEDEVICE_H
#define MOBILEDEVICE_H
#ifdef __cplusplus
extern "C" {
#endif
#if defined(WIN32)
#include <CoreFoundation.h>
typedef unsigned int mach_error_t;
#elif defined(__APPLE__)
#include <CoreFoundation/CoreFoundation.h>
#include <mach/error.h>
#endif
/* Error codes */
#define MDERR_APPLE_MOBILE (err_system(0x3a))
#define MDERR_IPHONE (err_sub(0))
/* Apple Mobile (AM*) errors */
#define MDERR_OK ERR_SUCCESS
#define MDERR_SYSCALL (ERR_MOBILE_DEVICE | 0x01)
#define MDERR_OUT_OF_MEMORY (ERR_MOBILE_DEVICE | 0x03)
#define MDERR_QUERY_FAILED (ERR_MOBILE_DEVICE | 0x04)
#define MDERR_INVALID_ARGUMENT (ERR_MOBILE_DEVICE | 0x0b)
#define MDERR_DICT_NOT_LOADED (ERR_MOBILE_DEVICE | 0x25)
/* Apple File Connection (AFC*) errors */
#define MDERR_AFC_OUT_OF_MEMORY 0x03
/* USBMux errors */
#define MDERR_USBMUX_ARG_NULL 0x16
#define MDERR_USBMUX_FAILED 0xffffffff
/* Messages passed to device notification callbacks: passed as part of
* am_device_notification_callback_info. */
#define ADNCI_MSG_CONNECTED 1
#define ADNCI_MSG_DISCONNECTED 2
#define ADNCI_MSG_UNKNOWN 3
#define AMD_IPHONE_PRODUCT_ID 0x1290
#define AMD_IPHONE_SERIAL "3391002d9c804d105e2c8c7d94fc35b6f3d214a3"
/* Services, found in /System/Library/Lockdown/Services.plist */
#define AMSVC_AFC CFSTR("com.apple.afc")
#define AMSVC_BACKUP CFSTR("com.apple.mobilebackup")
#define AMSVC_CRASH_REPORT_COPY CFSTR("com.apple.crashreportcopy")
#define AMSVC_DEBUG_IMAGE_MOUNT CFSTR("com.apple.mobile.debug_image_mount")
#define AMSVC_NOTIFICATION_PROXY CFSTR("com.apple.mobile.notification_proxy")
#define AMSVC_PURPLE_TEST CFSTR("com.apple.purpletestr")
#define AMSVC_SOFTWARE_UPDATE CFSTR("com.apple.mobile.software_update")
#define AMSVC_SYNC CFSTR("com.apple.mobilesync")
#define AMSVC_SCREENSHOT CFSTR("com.apple.screenshotr")
#define AMSVC_SYSLOG_RELAY CFSTR("com.apple.syslog_relay")
#define AMSVC_SYSTEM_PROFILER CFSTR("com.apple.mobile.system_profiler")
typedef unsigned int afc_error_t;
typedef unsigned int usbmux_error_t;
typedef unsigned int service_conn_t;
struct am_recovery_device;
typedef struct am_device_notification_callback_info {
struct am_device *dev; /* 0 device */
unsigned int msg; /* 4 one of ADNCI_MSG_* */
} __attribute__ ((packed)) am_device_notification_callback_info;
/* The type of the device restore notification callback functions.
* TODO: change to correct type. */
typedef void (*am_restore_device_notification_callback)(struct
am_recovery_device *);
/* This is a CoreFoundation object of class AMRecoveryModeDevice. */
typedef struct am_recovery_device {
unsigned char unknown0[8]; /* 0 */
am_restore_device_notification_callback callback; /* 8 */
void *user_info; /* 12 */
unsigned char unknown1[12]; /* 16 */
unsigned int readwrite_pipe; /* 28 */
unsigned char read_pipe; /* 32 */
unsigned char write_ctrl_pipe; /* 33 */
unsigned char read_unknown_pipe; /* 34 */
unsigned char write_file_pipe; /* 35 */
unsigned char write_input_pipe; /* 36 */
} __attribute__ ((packed)) am_recovery_device;
/* A CoreFoundation object of class AMRestoreModeDevice. */
typedef struct am_restore_device {
unsigned char unknown[32];
int port;
} __attribute__ ((packed)) am_restore_device;
/* The type of the device notification callback function. */
typedef void(*am_device_notification_callback)(struct
am_device_notification_callback_info *, void* arg);
/* The type of the _AMDDeviceAttached function.
* TODO: change to correct type. */
typedef void *amd_device_attached_callback;
typedef struct am_device {
unsigned char unknown0[16]; /* 0 - zero */
unsigned int device_id; /* 16 */
unsigned int product_id; /* 20 - set to AMD_IPHONE_PRODUCT_ID */
char *serial; /* 24 - set to AMD_IPHONE_SERIAL */
unsigned int unknown1; /* 28 */
unsigned char unknown2[4]; /* 32 */
unsigned int lockdown_conn; /* 36 */
unsigned char unknown3[8]; /* 40 */
} __attribute__ ((packed)) am_device;
typedef struct am_device_notification {
unsigned int unknown0; /* 0 */
unsigned int unknown1; /* 4 */
unsigned int unknown2; /* 8 */
am_device_notification_callback callback; /* 12 */
unsigned int unknown3; /* 16 */
} __attribute__ ((packed)) am_device_notification;
typedef struct afc_connection {
unsigned int handle; /* 0 */
unsigned int unknown0; /* 4 */
unsigned char unknown1; /* 8 */
unsigned char padding[3]; /* 9 */
unsigned int unknown2; /* 12 */
unsigned int unknown3; /* 16 */
unsigned int unknown4; /* 20 */
unsigned int fs_block_size; /* 24 */
unsigned int sock_block_size; /* 28: always 0x3c */
unsigned int io_timeout; /* 32: from AFCConnectionOpen, usu. 0 */
void *afc_lock; /* 36 */
unsigned int context; /* 40 */
} __attribute__ ((packed)) afc_connection;
typedef struct afc_directory {
unsigned char unknown[0]; /* size unknown */
} __attribute__ ((packed)) afc_directory;
typedef struct afc_dictionary {
unsigned char unknown[0]; /* size unknown */
} __attribute__ ((packed)) afc_dictionary;
typedef unsigned long long afc_file_ref;
typedef struct usbmux_listener_1 { /* offset value in iTunes */
unsigned int unknown0; /* 0 1 */
unsigned char *unknown1; /* 4 ptr, maybe device? */
amd_device_attached_callback callback; /* 8 _AMDDeviceAttached */
unsigned int unknown3; /* 12 */
unsigned int unknown4; /* 16 */
unsigned int unknown5; /* 20 */
} __attribute__ ((packed)) usbmux_listener_1;
typedef struct usbmux_listener_2 {
unsigned char unknown0[4144];
} __attribute__ ((packed)) usbmux_listener_2;
typedef struct am_bootloader_control_packet {
unsigned char opcode; /* 0 */
unsigned char length; /* 1 */
unsigned char magic[2]; /* 2: 0x34, 0x12 */
unsigned char payload[0]; /* 4 */
} __attribute__ ((packed)) am_bootloader_control_packet;
/* ----------------------------------------------------------------------------
* Public routines
* ------------------------------------------------------------------------- */
void AMDSetLogLevel(int level);
/* Registers a notification with the current run loop. The callback gets
* copied into the notification struct, as well as being registered with the
* current run loop. dn_unknown3 gets copied into unknown3 in the same.
* (Maybe dn_unknown3 is a user info parameter that gets passed as an arg to
* the callback?) unused0 and unused1 are both 0 when iTunes calls this.
* In iTunes the callback is located from $3db78e-$3dbbaf.
*
* Returns:
* MDERR_OK if successful
* MDERR_SYSCALL if CFRunLoopAddSource() failed
* MDERR_OUT_OF_MEMORY if we ran out of memory
*/
mach_error_t AMDeviceNotificationSubscribe(am_device_notification_callback
callback, unsigned int unused0, unsigned int unused1, void* //unsigned int
dn_unknown3, struct am_device_notification **notification);
/* Connects to the iPhone. Pass in the am_device structure that the
* notification callback will give to you.
*
* Returns:
* MDERR_OK if successfully connected
* MDERR_SYSCALL if setsockopt() failed
* MDERR_QUERY_FAILED if the daemon query failed
* MDERR_INVALID_ARGUMENT if USBMuxConnectByPort returned 0xffffffff
*/
mach_error_t AMDeviceConnect(struct am_device *device);
/* Calls PairingRecordPath() on the given device, than tests whether the path
* which that function returns exists. During the initial connect, the path
* returned by that function is '/', and so this returns 1.
*
* Returns:
* 0 if the path did not exist
* 1 if it did
*/
int AMDeviceIsPaired(struct am_device *device);
/* iTunes calls this function immediately after testing whether the device is
* paired. It creates a pairing file and establishes a Lockdown connection.
*
* Returns:
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the supplied device is null
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
*/
mach_error_t AMDeviceValidatePairing(struct am_device *device);
/* Creates a Lockdown session and adjusts the device structure appropriately
* to indicate that the session has been started. iTunes calls this function
* after validating pairing.
*
* Returns:
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
*/
mach_error_t AMDeviceStartSession(struct am_device *device);
/* Starts a service and returns a handle that can be used in order to further
* access the service. You should stop the session and disconnect before using
* the service. iTunes calls this function after starting a session. It starts
* the service and the SSL connection. unknown may safely be
* NULL (it is when iTunes calls this), but if it is not, then it will be
* filled upon function exit. service_name should be one of the AMSVC_*
* constants. If the service is AFC (AMSVC_AFC), then the handle is the handle
* that will be used for further AFC* calls.
*
* Returns:
* MDERR_OK if successful
* MDERR_SYSCALL if the setsockopt() call failed
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
*/
mach_error_t AMDeviceStartService(struct am_device *device, CFStringRef
service_name, service_conn_t *handle, unsigned int *
unknown);
mach_error_t AMDeviceStartHouseArrestService(struct am_device *device, CFStringRef identifier, void *unknown, service_conn_t *handle, unsigned int *what);
/* Stops a session. You should do this before accessing services.
*
* Returns:
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
*/
mach_error_t AMDeviceStopSession(struct am_device *device);
/* Opens an Apple File Connection. You must start the appropriate service
* first with AMDeviceStartService(). In iTunes, io_timeout is 0.
*
* Returns:
* MDERR_OK if successful
* MDERR_AFC_OUT_OF_MEMORY if malloc() failed
*/
afc_error_t AFCConnectionOpen(service_conn_t handle, unsigned int io_timeout,
struct afc_connection **conn);
/* Pass in a pointer to an afc_device_info structure. It will be filled. */
afc_error_t AFCDeviceInfoOpen(afc_connection *conn, struct
afc_dictionary **info);
/* Turns debug mode on if the environment variable AFCDEBUG is set to a numeric
* value, or if the file '/AFCDEBUG' is present and contains a value. */
void AFCPlatformInit();
/* Opens a directory on the iPhone. Pass in a pointer in dir to be filled in.
* Note that this normally only accesses the iTunes sandbox/partition as the
* root, which is /var/root/Media. Pathnames are specified with '/' delimiters
* as in Unix style.
*
* Returns:
* MDERR_OK if successful
*/
afc_error_t AFCDirectoryOpen(afc_connection *conn, const char *path,
struct afc_directory **dir);
/* Acquires the next entry in a directory previously opened with
* AFCDirectoryOpen(). When dirent is filled with a NULL value, then the end
* of the directory has been reached. '.' and '..' will be returned as the
* first two entries in each directory except the root; you may want to skip
* over them.
*
* Returns:
* MDERR_OK if successful, even if no entries remain
*/
afc_error_t AFCDirectoryRead(afc_connection *conn/*unsigned int unused*/, struct afc_directory *dir,
char **dirent);
afc_error_t AFCDirectoryClose(afc_connection *conn, struct afc_directory *dir);
afc_error_t AFCDirectoryCreate(afc_connection *conn, const char *dirname);
afc_error_t AFCRemovePath(afc_connection *conn, const char *dirname);
afc_error_t AFCRenamePath(afc_connection *conn, const char *from, const char *to);
afc_error_t AFCLinkPath(afc_connection *conn, long long int linktype, const char *target, const char *linkname);
/* Returns the context field of the given AFC connection. */
unsigned int AFCConnectionGetContext(afc_connection *conn);
/* Returns the fs_block_size field of the given AFC connection. */
unsigned int AFCConnectionGetFSBlockSize(afc_connection *conn);
/* Returns the io_timeout field of the given AFC connection. In iTunes this is
* 0. */
unsigned int AFCConnectionGetIOTimeout(afc_connection *conn);
/* Returns the sock_block_size field of the given AFC connection. */
unsigned int AFCConnectionGetSocketBlockSize(afc_connection *conn);
/* Closes the given AFC connection. */
afc_error_t AFCConnectionClose(afc_connection *conn);
/* Registers for device notifications related to the restore process. unknown0
* is zero when iTunes calls this. In iTunes,
* the callbacks are located at:
* 1: $3ac68e-$3ac6b1, calls $3ac542(unknown1, arg, 0)
* 2: $3ac66a-$3ac68d, calls $3ac542(unknown1, 0, arg)
* 3: $3ac762-$3ac785, calls $3ac6b2(unknown1, arg, 0)
* 4: $3ac73e-$3ac761, calls $3ac6b2(unknown1, 0, arg)
*/
unsigned int AMRestoreRegisterForDeviceNotifications(
am_restore_device_notification_callback dfu_connect_callback,
am_restore_device_notification_callback recovery_connect_callback,
am_restore_device_notification_callback dfu_disconnect_callback,
am_restore_device_notification_callback recovery_disconnect_callback,
unsigned int unknown0,
void *user_info);
/* Causes the restore functions to spit out (unhelpful) progress messages to
* the file specified by the given path. iTunes always calls this right before
* restoring with a path of
* "$HOME/Library/Logs/iPhone Updater Logs/iPhoneUpdater X.log", where X is an
* unused number.
*/
unsigned int AMRestoreEnableFileLogging(char *path);
/* Initializes a new option dictionary to default values. Pass the constant
* kCFAllocatorDefault as the allocator. The option dictionary looks as
* follows:
* {
* NORImageType => 'production',
* AutoBootDelay => 0,
* KernelCacheType => 'Release',
* UpdateBaseband => true,
* DFUFileType => 'RELEASE',
* SystemImageType => 'User',
* CreateFilesystemPartitions => true,
* FlashNOR => true,
* RestoreBootArgs => 'rd=md0 nand-enable-reformat=1 -progress'
* BootImageType => 'User'
* }
*
* Returns:
* the option dictionary if successful
* NULL if out of memory
*/
CFMutableDictionaryRef AMRestoreCreateDefaultOptions(CFAllocatorRef allocator);
/* ----------------------------------------------------------------------------
* Less-documented public routines
* ------------------------------------------------------------------------- */
/* mode 2 = read, mode 3 = write */
afc_error_t AFCFileRefOpen(afc_connection *conn, const char *path,
unsigned long long mode, afc_file_ref *ref);
afc_error_t AFCFileRefSeek(afc_connection *conn, afc_file_ref ref,
unsigned long long offset1, unsigned long long offset2);
afc_error_t AFCFileRefRead(afc_connection *conn, afc_file_ref ref,
void *buf, unsigned int *len);
afc_error_t AFCFileRefSetFileSize(afc_connection *conn, afc_file_ref ref,
unsigned long long offset);
afc_error_t AFCFileRefWrite(afc_connection *conn, afc_file_ref ref,
const void *buf, unsigned int len);
afc_error_t AFCFileRefClose(afc_connection *conn, afc_file_ref ref);
afc_error_t AFCFileInfoOpen(afc_connection *conn, const char *path, struct
afc_dictionary **info);
afc_error_t AFCKeyValueRead(struct afc_dictionary *dict, char **key, char **
val);
afc_error_t AFCKeyValueClose(struct afc_dictionary *dict);
unsigned int AMRestorePerformRecoveryModeRestore(struct am_recovery_device *
rdev, CFDictionaryRef opts, void *callback, void *user_info);
unsigned int AMRestorePerformRestoreModeRestore(struct am_restore_device *
rdev, CFDictionaryRef opts, void *callback, void *user_info);
struct am_restore_device *AMRestoreModeDeviceCreate(unsigned int unknown0,
unsigned int connection_id, unsigned int unknown1);
unsigned int AMRestoreCreatePathsForBundle(CFStringRef restore_bundle_path,
CFStringRef kernel_cache_type, CFStringRef boot_image_type, unsigned int
unknown0, CFStringRef *firmware_dir_path, CFStringRef *
kernelcache_restore_path, unsigned int unknown1, CFStringRef *
ramdisk_path);
unsigned int AMDeviceGetConnectionID(struct am_device *device);
mach_error_t AMDeviceEnterRecovery(struct am_device *device);
mach_error_t AMDeviceDisconnect(struct am_device *device);
mach_error_t AMDeviceRetain(struct am_device *device);
mach_error_t AMDeviceRelease(struct am_device *device);
CFStringRef AMDeviceCopyValue(struct am_device *device, unsigned int, CFStringRef cfstring);
CFStringRef AMDeviceCopyDeviceIdentifier(struct am_device *device);
typedef void (*notify_callback)(CFStringRef notification, void *data);
mach_error_t AMDPostNotification(service_conn_t socket, CFStringRef notification, CFStringRef userinfo);
mach_error_t AMDObserveNotification(void *socket, CFStringRef notification);
mach_error_t AMDListenForNotifications(void *socket, notify_callback cb, void *data);
mach_error_t AMDShutdownNotificationProxy(void *socket);
/*edits by geohot*/
mach_error_t AMDeviceDeactivate(struct am_device *device);
mach_error_t AMDeviceActivate(struct am_device *device, CFMutableDictionaryRef);
/*end*/
void *AMDeviceSerialize(struct am_device *device);
void AMDAddLogFileDescriptor(int fd);
kern_return_t AMDeviceSendMessage(service_conn_t socket, void *unused, CFPropertyListRef plist);
kern_return_t AMDeviceReceiveMessage(service_conn_t socket, CFDictionaryRef options, CFPropertyListRef * result);
/* ----------------------------------------------------------------------------
* Semi-private routines
* ------------------------------------------------------------------------- */
/* Pass in a usbmux_listener_1 structure and a usbmux_listener_2 structure
* pointer, which will be filled with the resulting usbmux_listener_2.
*
* Returns:
* MDERR_OK if completed successfully
* MDERR_USBMUX_ARG_NULL if one of the arguments was NULL
* MDERR_USBMUX_FAILED if the listener was not created successfully
*/
usbmux_error_t USBMuxListenerCreate(struct usbmux_listener_1 *esi_fp8, struct
usbmux_listener_2 **eax_fp12);
/* ----------------------------------------------------------------------------
* Less-documented semi-private routines
* ------------------------------------------------------------------------- */
usbmux_error_t USBMuxListenerHandleData(void *);
/* ----------------------------------------------------------------------------
* Private routines - here be dragons
* ------------------------------------------------------------------------- */
/* AMRestorePerformRestoreModeRestore() calls this function with a dictionary
* in order to perform certain special restore operations
* (RESTORED_OPERATION_*). It is thought that this function might enable
* significant access to the phone. */
typedef unsigned int (*t_performOperation)(struct am_restore_device *rdev,
CFDictionaryRef op); // __attribute__ ((regparm(2)));
#ifdef __cplusplus
}
#endif
#endif

Related

Why Does This Objective C/C++ Code Require main.m instead of main.mm?

I get strange code errors when I rename the following command line program from main.m to main.mm. Works just fine as main.m. Anyone know why?
https://stackoverflow.com/a/36469891/105539
SOURCE
#import <Foundation/Foundation.h>
void detectNewFile (
ConstFSEventStreamRef streamRef,
void *clientCallBackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
int i;
char **paths = eventPaths;
printf("GOT AN EVENT!!!!\n");
for (i=0; i<numEvents; i++) {
printf("Change %llu in %s, flags %u\n", eventIds[i], paths[i], (unsigned int)eventFlags[i]);
}
}
int main(int argc, const char * argv[]) {
#autoreleasepool {
short nPathCount = 2;
CFStringRef mypath[nPathCount];
mypath[0] = CFSTR("/Users/mike/Documents");
mypath[1] = CFSTR("/Users/mike/Downloads");
CFArrayRef pathsToWatch = CFArrayCreate(NULL, (const void **)&mypath, nPathCount, NULL);
void *callbackInfo = NULL;
CFAbsoluteTime latency = 1.0; // seconds
FSEventStreamRef hStream = FSEventStreamCreate(NULL,
&detectNewFile,
callbackInfo,
pathsToWatch,
kFSEventStreamEventIdSinceNow,
latency,
kFSEventStreamCreateFlagFileEvents
);
FSEventStreamScheduleWithRunLoop(hStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
FSEventStreamStart(hStream);
printf("Waiting on new file creations...\n");
CFRunLoopRun(); // runs in an endless loop, only letting the callback function run
} // end autorelease pool
return 0;
}
ERRORS
FOR:
char **paths = eventPaths;
Cannot initialize a variable of type 'char **' with an lvalue of type 'void *'
FOR:
FSEventStreamRef hStream = FSEventStreamCreate(NULL,
&detectNewFile,
callbackInfo,
pathsToWatch,
kFSEventStreamEventIdSinceNow,
latency,
kFSEventStreamCreateFlagFileEvents
);
No matching function for call to 'FSEventStreamCreate'
Thanks to #johnelemans, I found the problems. In C, it's legal to have automatic casting from void * to char **, but not in C++, which is what the .mm file would switch this into. The fix is to use casting:
char **paths = (char **)eventPaths;
Then, on the FSEventStreamCreate, it didn't like the void * instead of this:
FSEventStreamContext *callbackInfo = NULL;
...and didn't like the CFAbsoluteTime instead of:
CFTimeInterval latency = 1.0; // seconds
Then, you need to add CoreServices.framework library to the build steps.
I made those changes and it compiles now.

C Convert CFNumber(kCFNumberSInt64Type) to a long or int

(Have updated the question with code)
As the title says I was wondering if it possible to convert a CFNumber(kCFNumberSInt64Type) to a long or int ?
Here is the code that im currently using.
#include "MobileDevice.h"
void device_callback(struct am_device_notification_callback_info *info, void *arg) {
struct am_device *dev;
if (info->msg == ADNCI_MSG_CONNECTED) {
dev = info->dev;
CFRetain(dev);
AMDSetLogLevel(5);
AMDeviceConnect(dev);
assert(AMDeviceIsPaired(dev));
assert(!AMDeviceValidatePairing(dev));
assert(!AMDeviceStartSession(dev));
assert(AMDeviceIsPaired(dev));
assert(AMDeviceValidatePairing(dev) == 0);
int64_t i1, i2 = 42;
CFNumberRef ecid = AMDeviceCopyValue(dev, 0, CFSTR("UniqueChipID")); // this is what I want as a long/int
printf("ecid (%s)",CFNumberGetValue(ecid, kCFNumberSInt64Type, &i1));
}
}
int main(int argc, char *argv[]) {
struct am_device_notification *notify;
AMDeviceNotificationSubscribe(&device_callback, 0, 0, NULL, &notify);
CFRunLoopRun();
}
/* ----------------------------------------------------------------------------
* MobileDevice.h - interface to MobileDevice.framework
* $LastChangedDate: 2007-07-09 18:59:29 -0700 (Mon, 09 Jul 2007) $
*
* Copied from http://iphonesvn.halifrag.com/svn/iPhone/
* With modifications from Allen Porter and Scott Turner
*
* ------------------------------------------------------------------------- */
#ifndef MOBILEDEVICE_H
#define MOBILEDEVICE_H
#ifdef __cplusplus
extern "C" {
#endif
#if defined(WIN32)
#include <CoreFoundation.h>
typedef unsigned int mach_error_t;
#elif defined(__APPLE__)
#include <CoreFoundation/CoreFoundation.h>
#include <mach/error.h>
#endif
/* Error codes */
#define MDERR_APPLE_MOBILE (err_system(0x3a))
#define MDERR_IPHONE (err_sub(0))
/* Apple Mobile (AM*) errors */
#define MDERR_OK ERR_SUCCESS
#define MDERR_SYSCALL (ERR_MOBILE_DEVICE | 0x01)
#define MDERR_OUT_OF_MEMORY (ERR_MOBILE_DEVICE | 0x03)
#define MDERR_QUERY_FAILED (ERR_MOBILE_DEVICE | 0x04)
#define MDERR_INVALID_ARGUMENT (ERR_MOBILE_DEVICE | 0x0b)
#define MDERR_DICT_NOT_LOADED (ERR_MOBILE_DEVICE | 0x25)
/* Apple File Connection (AFC*) errors */
#define MDERR_AFC_OUT_OF_MEMORY 0x03
/* USBMux errors */
#define MDERR_USBMUX_ARG_NULL 0x16
#define MDERR_USBMUX_FAILED 0xffffffff
/* Messages passed to device notification callbacks: passed as part of
* am_device_notification_callback_info. */
#define ADNCI_MSG_CONNECTED 1
#define ADNCI_MSG_DISCONNECTED 2
#define ADNCI_MSG_UNKNOWN 3
#define AMD_IPHONE_PRODUCT_ID 0x1290
#define AMD_IPHONE_SERIAL "3391002d9c804d105e2c8c7d94fc35b6f3d214a3"
/* Services, found in /System/Library/Lockdown/Services.plist */
#define AMSVC_AFC CFSTR("com.apple.afc")
#define AMSVC_BACKUP CFSTR("com.apple.mobilebackup")
#define AMSVC_CRASH_REPORT_COPY CFSTR("com.apple.crashreportcopy")
#define AMSVC_DEBUG_IMAGE_MOUNT CFSTR("com.apple.mobile.debug_image_mount")
#define AMSVC_NOTIFICATION_PROXY CFSTR("com.apple.mobile.notification_proxy")
#define AMSVC_PURPLE_TEST CFSTR("com.apple.purpletestr")
#define AMSVC_SOFTWARE_UPDATE CFSTR("com.apple.mobile.software_update")
#define AMSVC_SYNC CFSTR("com.apple.mobilesync")
#define AMSVC_SCREENSHOT CFSTR("com.apple.screenshotr")
#define AMSVC_SYSLOG_RELAY CFSTR("com.apple.syslog_relay")
#define AMSVC_SYSTEM_PROFILER CFSTR("com.apple.mobile.system_profiler")
typedef unsigned int afc_error_t;
typedef unsigned int usbmux_error_t;
typedef unsigned int service_conn_t;
struct am_recovery_device;
typedef struct am_device_notification_callback_info {
struct am_device *dev; /* 0 device */
unsigned int msg; /* 4 one of ADNCI_MSG_* */
} __attribute__ ((packed)) am_device_notification_callback_info;
/* The type of the device restore notification callback functions.
* TODO: change to correct type. */
typedef void (*am_restore_device_notification_callback)(struct
am_recovery_device *);
/* This is a CoreFoundation object of class AMRecoveryModeDevice. */
typedef struct am_recovery_device {
unsigned char unknown0[8]; /* 0 */
am_restore_device_notification_callback callback; /* 8 */
void *user_info; /* 12 */
unsigned char unknown1[12]; /* 16 */
unsigned int readwrite_pipe; /* 28 */
unsigned char read_pipe; /* 32 */
unsigned char write_ctrl_pipe; /* 33 */
unsigned char read_unknown_pipe; /* 34 */
unsigned char write_file_pipe; /* 35 */
unsigned char write_input_pipe; /* 36 */
} __attribute__ ((packed)) am_recovery_device;
/* A CoreFoundation object of class AMRestoreModeDevice. */
typedef struct am_restore_device {
unsigned char unknown[32];
int port;
} __attribute__ ((packed)) am_restore_device;
/* The type of the device notification callback function. */
typedef void(*am_device_notification_callback)(struct
am_device_notification_callback_info *, void* arg);
/* The type of the _AMDDeviceAttached function.
* TODO: change to correct type. */
typedef void *amd_device_attached_callback;
typedef struct am_device {
unsigned char unknown0[16]; /* 0 - zero */
unsigned int device_id; /* 16 */
unsigned int product_id; /* 20 - set to AMD_IPHONE_PRODUCT_ID */
char *serial; /* 24 - set to AMD_IPHONE_SERIAL */
unsigned int unknown1; /* 28 */
unsigned char unknown2[4]; /* 32 */
unsigned int lockdown_conn; /* 36 */
unsigned char unknown3[8]; /* 40 */
} __attribute__ ((packed)) am_device;
typedef struct am_device_notification {
unsigned int unknown0; /* 0 */
unsigned int unknown1; /* 4 */
unsigned int unknown2; /* 8 */
am_device_notification_callback callback; /* 12 */
unsigned int unknown3; /* 16 */
} __attribute__ ((packed)) am_device_notification;
typedef struct afc_connection {
unsigned int handle; /* 0 */
unsigned int unknown0; /* 4 */
unsigned char unknown1; /* 8 */
unsigned char padding[3]; /* 9 */
unsigned int unknown2; /* 12 */
unsigned int unknown3; /* 16 */
unsigned int unknown4; /* 20 */
unsigned int fs_block_size; /* 24 */
unsigned int sock_block_size; /* 28: always 0x3c */
unsigned int io_timeout; /* 32: from AFCConnectionOpen, usu. 0 */
void *afc_lock; /* 36 */
unsigned int context; /* 40 */
} __attribute__ ((packed)) afc_connection;
typedef struct afc_directory {
unsigned char unknown[0]; /* size unknown */
} __attribute__ ((packed)) afc_directory;
typedef struct afc_dictionary {
unsigned char unknown[0]; /* size unknown */
} __attribute__ ((packed)) afc_dictionary;
typedef unsigned long long afc_file_ref;
typedef struct usbmux_listener_1 { /* offset value in iTunes */
unsigned int unknown0; /* 0 1 */
unsigned char *unknown1; /* 4 ptr, maybe device? */
amd_device_attached_callback callback; /* 8 _AMDDeviceAttached */
unsigned int unknown3; /* 12 */
unsigned int unknown4; /* 16 */
unsigned int unknown5; /* 20 */
} __attribute__ ((packed)) usbmux_listener_1;
typedef struct usbmux_listener_2 {
unsigned char unknown0[4144];
} __attribute__ ((packed)) usbmux_listener_2;
typedef struct am_bootloader_control_packet {
unsigned char opcode; /* 0 */
unsigned char length; /* 1 */
unsigned char magic[2]; /* 2: 0x34, 0x12 */
unsigned char payload[0]; /* 4 */
} __attribute__ ((packed)) am_bootloader_control_packet;
/* ----------------------------------------------------------------------------
* Public routines
* ------------------------------------------------------------------------- */
void AMDSetLogLevel(int level);
/* Registers a notification with the current run loop. The callback gets
* copied into the notification struct, as well as being registered with the
* current run loop. dn_unknown3 gets copied into unknown3 in the same.
* (Maybe dn_unknown3 is a user info parameter that gets passed as an arg to
* the callback?) unused0 and unused1 are both 0 when iTunes calls this.
* In iTunes the callback is located from $3db78e-$3dbbaf.
*
* Returns:
* MDERR_OK if successful
* MDERR_SYSCALL if CFRunLoopAddSource() failed
* MDERR_OUT_OF_MEMORY if we ran out of memory
*/
mach_error_t AMDeviceNotificationSubscribe(am_device_notification_callback
callback, unsigned int unused0, unsigned int unused1, void* //unsigned int
dn_unknown3, struct am_device_notification **notification);
/* Connects to the iPhone. Pass in the am_device structure that the
* notification callback will give to you.
*
* Returns:
* MDERR_OK if successfully connected
* MDERR_SYSCALL if setsockopt() failed
* MDERR_QUERY_FAILED if the daemon query failed
* MDERR_INVALID_ARGUMENT if USBMuxConnectByPort returned 0xffffffff
*/
mach_error_t AMDeviceConnect(struct am_device *device);
/* Calls PairingRecordPath() on the given device, than tests whether the path
* which that function returns exists. During the initial connect, the path
* returned by that function is '/', and so this returns 1.
*
* Returns:
* 0 if the path did not exist
* 1 if it did
*/
int AMDeviceIsPaired(struct am_device *device);
/* iTunes calls this function immediately after testing whether the device is
* paired. It creates a pairing file and establishes a Lockdown connection.
*
* Returns:
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the supplied device is null
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
*/
mach_error_t AMDeviceValidatePairing(struct am_device *device);
/* Creates a Lockdown session and adjusts the device structure appropriately
* to indicate that the session has been started. iTunes calls this function
* after validating pairing.
*
* Returns:
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
*/
mach_error_t AMDeviceStartSession(struct am_device *device);
/* Starts a service and returns a handle that can be used in order to further
* access the service. You should stop the session and disconnect before using
* the service. iTunes calls this function after starting a session. It starts
* the service and the SSL connection. unknown may safely be
* NULL (it is when iTunes calls this), but if it is not, then it will be
* filled upon function exit. service_name should be one of the AMSVC_*
* constants. If the service is AFC (AMSVC_AFC), then the handle is the handle
* that will be used for further AFC* calls.
*
* Returns:
* MDERR_OK if successful
* MDERR_SYSCALL if the setsockopt() call failed
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
*/
mach_error_t AMDeviceStartService(struct am_device *device, CFStringRef
service_name, service_conn_t *handle, unsigned int *
unknown);
mach_error_t AMDeviceStartHouseArrestService(struct am_device *device, CFStringRef identifier, void *unknown, service_conn_t *handle, unsigned int *what);
/* Stops a session. You should do this before accessing services.
*
* Returns:
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
*/
mach_error_t AMDeviceStopSession(struct am_device *device);
/* Opens an Apple File Connection. You must start the appropriate service
* first with AMDeviceStartService(). In iTunes, io_timeout is 0.
*
* Returns:
* MDERR_OK if successful
* MDERR_AFC_OUT_OF_MEMORY if malloc() failed
*/
afc_error_t AFCConnectionOpen(service_conn_t handle, unsigned int io_timeout,
struct afc_connection **conn);
/* Pass in a pointer to an afc_device_info structure. It will be filled. */
afc_error_t AFCDeviceInfoOpen(afc_connection *conn, struct
afc_dictionary **info);
/* Turns debug mode on if the environment variable AFCDEBUG is set to a numeric
* value, or if the file '/AFCDEBUG' is present and contains a value. */
void AFCPlatformInit();
/* Opens a directory on the iPhone. Pass in a pointer in dir to be filled in.
* Note that this normally only accesses the iTunes sandbox/partition as the
* root, which is /var/root/Media. Pathnames are specified with '/' delimiters
* as in Unix style.
*
* Returns:
* MDERR_OK if successful
*/
afc_error_t AFCDirectoryOpen(afc_connection *conn, const char *path,
struct afc_directory **dir);
/* Acquires the next entry in a directory previously opened with
* AFCDirectoryOpen(). When dirent is filled with a NULL value, then the end
* of the directory has been reached. '.' and '..' will be returned as the
* first two entries in each directory except the root; you may want to skip
* over them.
*
* Returns:
* MDERR_OK if successful, even if no entries remain
*/
afc_error_t AFCDirectoryRead(afc_connection *conn/*unsigned int unused*/, struct afc_directory *dir,
char **dirent);
afc_error_t AFCDirectoryClose(afc_connection *conn, struct afc_directory *dir);
afc_error_t AFCDirectoryCreate(afc_connection *conn, const char *dirname);
afc_error_t AFCRemovePath(afc_connection *conn, const char *dirname);
afc_error_t AFCRenamePath(afc_connection *conn, const char *from, const char *to);
afc_error_t AFCLinkPath(afc_connection *conn, long long int linktype, const char *target, const char *linkname);
/* Returns the context field of the given AFC connection. */
unsigned int AFCConnectionGetContext(afc_connection *conn);
/* Returns the fs_block_size field of the given AFC connection. */
unsigned int AFCConnectionGetFSBlockSize(afc_connection *conn);
/* Returns the io_timeout field of the given AFC connection. In iTunes this is
* 0. */
unsigned int AFCConnectionGetIOTimeout(afc_connection *conn);
/* Returns the sock_block_size field of the given AFC connection. */
unsigned int AFCConnectionGetSocketBlockSize(afc_connection *conn);
/* Closes the given AFC connection. */
afc_error_t AFCConnectionClose(afc_connection *conn);
/* Registers for device notifications related to the restore process. unknown0
* is zero when iTunes calls this. In iTunes,
* the callbacks are located at:
* 1: $3ac68e-$3ac6b1, calls $3ac542(unknown1, arg, 0)
* 2: $3ac66a-$3ac68d, calls $3ac542(unknown1, 0, arg)
* 3: $3ac762-$3ac785, calls $3ac6b2(unknown1, arg, 0)
* 4: $3ac73e-$3ac761, calls $3ac6b2(unknown1, 0, arg)
*/
unsigned int AMRestoreRegisterForDeviceNotifications(
am_restore_device_notification_callback dfu_connect_callback,
am_restore_device_notification_callback recovery_connect_callback,
am_restore_device_notification_callback dfu_disconnect_callback,
am_restore_device_notification_callback recovery_disconnect_callback,
unsigned int unknown0,
void *user_info);
/* Causes the restore functions to spit out (unhelpful) progress messages to
* the file specified by the given path. iTunes always calls this right before
* restoring with a path of
* "$HOME/Library/Logs/iPhone Updater Logs/iPhoneUpdater X.log", where X is an
* unused number.
*/
unsigned int AMRestoreEnableFileLogging(char *path);
/* Initializes a new option dictionary to default values. Pass the constant
* kCFAllocatorDefault as the allocator. The option dictionary looks as
* follows:
* {
* NORImageType => 'production',
* AutoBootDelay => 0,
* KernelCacheType => 'Release',
* UpdateBaseband => true,
* DFUFileType => 'RELEASE',
* SystemImageType => 'User',
* CreateFilesystemPartitions => true,
* FlashNOR => true,
* RestoreBootArgs => 'rd=md0 nand-enable-reformat=1 -progress'
* BootImageType => 'User'
* }
*
* Returns:
* the option dictionary if successful
* NULL if out of memory
*/
CFMutableDictionaryRef AMRestoreCreateDefaultOptions(CFAllocatorRef allocator);
/* ----------------------------------------------------------------------------
* Less-documented public routines
* ------------------------------------------------------------------------- */
/* mode 2 = read, mode 3 = write */
afc_error_t AFCFileRefOpen(afc_connection *conn, const char *path,
unsigned long long mode, afc_file_ref *ref);
afc_error_t AFCFileRefSeek(afc_connection *conn, afc_file_ref ref,
unsigned long long offset1, unsigned long long offset2);
afc_error_t AFCFileRefRead(afc_connection *conn, afc_file_ref ref,
void *buf, unsigned int *len);
afc_error_t AFCFileRefSetFileSize(afc_connection *conn, afc_file_ref ref,
unsigned long long offset);
afc_error_t AFCFileRefWrite(afc_connection *conn, afc_file_ref ref,
const void *buf, unsigned int len);
afc_error_t AFCFileRefClose(afc_connection *conn, afc_file_ref ref);
afc_error_t AFCFileInfoOpen(afc_connection *conn, const char *path, struct
afc_dictionary **info);
afc_error_t AFCKeyValueRead(struct afc_dictionary *dict, char **key, char **
val);
afc_error_t AFCKeyValueClose(struct afc_dictionary *dict);
unsigned int AMRestorePerformRecoveryModeRestore(struct am_recovery_device *
rdev, CFDictionaryRef opts, void *callback, void *user_info);
unsigned int AMRestorePerformRestoreModeRestore(struct am_restore_device *
rdev, CFDictionaryRef opts, void *callback, void *user_info);
struct am_restore_device *AMRestoreModeDeviceCreate(unsigned int unknown0,
unsigned int connection_id, unsigned int unknown1);
unsigned int AMRestoreCreatePathsForBundle(CFStringRef restore_bundle_path,
CFStringRef kernel_cache_type, CFStringRef boot_image_type, unsigned int
unknown0, CFStringRef *firmware_dir_path, CFStringRef *
kernelcache_restore_path, unsigned int unknown1, CFStringRef *
ramdisk_path);
unsigned int AMDeviceGetConnectionID(struct am_device *device);
mach_error_t AMDeviceEnterRecovery(struct am_device *device);
mach_error_t AMDeviceDisconnect(struct am_device *device);
mach_error_t AMDeviceRetain(struct am_device *device);
mach_error_t AMDeviceRelease(struct am_device *device);
CFStringRef AMDeviceCopyValue(struct am_device *device, unsigned int, CFStringRef cfstring);
CFStringRef AMDeviceCopyDeviceIdentifier(struct am_device *device);
typedef void (*notify_callback)(CFStringRef notification, void *data);
mach_error_t AMDPostNotification(service_conn_t socket, CFStringRef notification, CFStringRef userinfo);
mach_error_t AMDObserveNotification(void *socket, CFStringRef notification);
mach_error_t AMDListenForNotifications(void *socket, notify_callback cb, void *data);
mach_error_t AMDShutdownNotificationProxy(void *socket);
/*edits by geohot*/
mach_error_t AMDeviceDeactivate(struct am_device *device);
mach_error_t AMDeviceActivate(struct am_device *device, CFMutableDictionaryRef);
/*end*/
void *AMDeviceSerialize(struct am_device *device);
void AMDAddLogFileDescriptor(int fd);
//kern_return_t AMDeviceSendMessage(service_conn_t socket, void *unused, CFPropertyListRef plist);
//kern_return_t AMDeviceReceiveMessage(service_conn_t socket, CFDictionaryRef options, CFPropertyListRef * result);
/* ----------------------------------------------------------------------------
* Semi-private routines
* ------------------------------------------------------------------------- */
/* Pass in a usbmux_listener_1 structure and a usbmux_listener_2 structure
* pointer, which will be filled with the resulting usbmux_listener_2.
*
* Returns:
* MDERR_OK if completed successfully
* MDERR_USBMUX_ARG_NULL if one of the arguments was NULL
* MDERR_USBMUX_FAILED if the listener was not created successfully
*/
usbmux_error_t USBMuxListenerCreate(struct usbmux_listener_1 *esi_fp8, struct
usbmux_listener_2 **eax_fp12);
/* ----------------------------------------------------------------------------
* Less-documented semi-private routines
* ------------------------------------------------------------------------- */
usbmux_error_t USBMuxListenerHandleData(void *);
/* ----------------------------------------------------------------------------
* Private routines - here be dragons
* ------------------------------------------------------------------------- */
/* AMRestorePerformRestoreModeRestore() calls this function with a dictionary
* in order to perform certain special restore operations
* (RESTORED_OPERATION_*). It is thought that this function might enable
* significant access to the phone. */
typedef unsigned int (*t_performOperation)(struct am_restore_device *rdev,
CFDictionaryRef op); // __attribute__ ((regparm(2)));
#ifdef __cplusplus
}
#endif
#endif
Would love if someone knows a solution to the problem I have :D
First, you posted way too much irrelevant code. When you post code to ask about, you should reduce it to a minimal example that still reproduces the problem.
You should also explain precisely what the problem is. Is there a compile error? Do you get a wrong value?
Anyway, I assume the problem is with this line:
printf("ecid (%s)",CFNumberGetValue(ecid, kCFNumberSInt64Type, &i1));
That's because the return value from CFNumberGetValue() is not the value which was retrieved. It is a boolean value indicating success or failure. The value that was retrieved is stored in the variable whose address was passed in the third parameter. You passed the address of i1, so it is stored in that variable.
Also, you have used the %s format specifier, which requires a pointer to a C-style string (null-terminated array of characters). You won't get sensible results if you pass an integer or a boolean. You'll likely get a crash.
You could do something like:
if (CFNumberGetValue(ecid, kCFNumberSInt64Type, &i1))
printf("ecid (%lld)", i1);
else
/* handle failure */;
Another approach, since you're using Objective-C, is to take advantage of the fact that CFNumber is toll-free bridged to NSNumber:
NSNumber* ecid = (NSNumber*)CFBridgingRelease(AMDeviceCopyValue(dev, 0, CFSTR("UniqueChipID"))); // this is what I want as a long/int
printf("ecid (%lld)", ecid.longLongValue);
You are looking for CFNumberGetValue.
#include <stdint.h>
...
int64_t i1, i2 = 42;
CFNumberRef cfnum = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &i2);
/* We now got a CFNumberRef which encapsulates i2's value */
CFNumberGetValue(cfnum, kCFNumberSInt64Type, &i1);
/* We now got the same value in i1 */
I am not too well versed with Objective C, but I think C99 support (and the optional <stdint.h>) should be guaranteed.

Implementing a header in Objective C

I'm completely new to Objective C and I'm trying to use it to wrap a C-library. I have a main.m wrap.m and wrap.h files. From what I gather in the header file I included #interface and in the source file I will include #implementation However I'm not really understanding what to include in each of them. Right now my main file is:
int copy_data(struct archive *ar, struct archive *aw) {
for (;;) {
const void *buff;
size_t size;
off_t offset;
int r = archive_read_data_block(ar, &buff, &size, &offset);
if (r == ARCHIVE_EOF)
return (ARCHIVE_OK);
archive_write_data_block(aw, buff, size, offset);
}
}
int main(int argc, const char * argv[])
{
#autoreleasepool {
struct archive *a;
struct archive *ext;
struct archive_entry *entry;
int flags;
int r;
/* Select which attributes we want to restore. */
flags = ARCHIVE_EXTRACT_TIME;
flags |= ARCHIVE_EXTRACT_PERM;
flags |= ARCHIVE_EXTRACT_ACL;
flags |= ARCHIVE_EXTRACT_FFLAGS;
a = archive_read_new();
archive_read_support_format_all(a);
archive_read_support_compression_all(a);
ext = archive_write_disk_new();
archive_write_disk_set_options(ext, flags);
archive_write_disk_set_standard_lookup(ext);
r = archive_read_open_filename(a, argv[1], 10240);
for (;;) {
r = archive_read_next_header(a, &entry);
if (r == ARCHIVE_EOF)
break;
r = archive_write_header(ext, entry);
if (archive_entry_size(entry) > 0) {
copy_data(a, ext);
}
archive_write_finish_entry(ext);
}
archive_read_close(a);
archive_read_free(a);
archive_write_close(ext);
archive_write_free(ext);
NSLog(#"No Issues");
}
return 0;
}
So far what I'm getting in my wrap.h file is:
typedef struct{
int *a;
int *ext;
}archive;
#interface main : NSObject
#property int flags;
#property int r;
I don't know if that is close to what I need to do, and I'm getting errors on my ARCHIVE_EXTRACT saying they are undeclared identifiers which I assume also have to go into my wrap.h file but I'm not sure how to do that. Any help at all would be appreciated!
If you start your project in Xcode using the CommandLineTool template, you can select your language to be "C" or "C++", so you wouldn't have to mess with Objective-C at all.
As for the .h file that you currently have, don't do "#property" or "#interface" for "main". "main" is a C style function and not an Objective-C thing.
If you are actually interested in an objectivec solution, follow Michael Dautermann's instructions to start a new Command Line project but instead of Type C use the Foundation option. This will give you a working main (just a regular c function). Then select new->objective c class to create your wrap.h/wrap.m. In the wrap.h you will pretty much exclusively be declaring your own objectivec public wrapper methods. In the wrap.m, you'll be importing what you want to wrap, and defining your wrapper functions.
//
// main.m
//
#import <Foundation/Foundation.h>
#import "wrap.h"
int main(int argc, const char * argv[])
{
#autoreleasepool {
[wrap wrappedStuff];
}
return 0;
}
//
// wrap.h
//
----------
#import <Foundation/Foundation.h>
#interface wrap : NSObject
+ (void)wrappedStuff;
#end
//
// wrap.m
//
#import "wrap.h"
#include "WhatImWrapping.h"
#implementation wrap
int copy_data(struct archive *ar, struct archive *aw) {
for (;;) {
const void *buff;
size_t size;
off_t offset;
int r = archive_read_data_block(ar, &buff, &size, &offset);
if (r == ARCHIVE_EOF)
return (ARCHIVE_OK);
archive_write_data_block(aw, buff, size, offset);
}
}
+ (void)wrappedStuff
{
struct archive *a;
struct archive *ext;
struct archive_entry *entry;
int flags;
int r;
/* Select which attributes we want to restore. */
flags = ARCHIVE_EXTRACT_TIME;
flags |= ARCHIVE_EXTRACT_PERM;
flags |= ARCHIVE_EXTRACT_ACL;
flags |= ARCHIVE_EXTRACT_FFLAGS;
a = archive_read_new();
archive_read_support_format_all(a);
archive_read_support_compression_all(a);
ext = archive_write_disk_new();
archive_write_disk_set_options(ext, flags);
archive_write_disk_set_standard_lookup(ext);
r = archive_read_open_filename(a, argv[1], 10240);
for (;;) {
r = archive_read_next_header(a, &entry);
if (r == ARCHIVE_EOF)
break;
r = archive_write_header(ext, entry);
if (archive_entry_size(entry) > 0) {
copy_data(a, ext);
}
archive_write_finish_entry(ext);
}
archive_read_close(a);
archive_read_free(a);
archive_write_close(ext);
archive_write_free(ext);
NSLog(#"No Issues");
}
#end

Repetier V0.70b firmware uploading to Printrboard

I am new to the RepRap community, 3D printing in general, and the new Printrbot PLUS. I am trying to update the firmware to Repetier's package as I would like to use their software and want as much compatibility as possible.
I've heard the Sprinter firmware works well on the Printrboard but considering the Repetier recently updated their package for the Printrboard as well, I'd like to give it a go.
I go to hit upload in Arduino 1.01 after changing the first configuration setting to 9 (for Printrboard) and then get these errors:
In file included from Commands.cpp:23:
/Reptier.h: In function 'void extruder_unstep()':
Reptier.h:189: error: 'DIO34_WPORT' was not declared in this scope
Reptier.h:189: error: 'DIO34_PIN' was not declared in this scope
Reptier.h:189: error: 'DIO34_WPORT' was not declared in this scope
Reptier.h:189: error: 'DIO34_PIN' was not declared in this scope
/Reptier.h: In function 'void extruder_set_direction(byte)':
Reptier.h:212: error: 'DIO35_WPORT' was not declared in this scope
Reptier.h:212: error: 'DIO35_PIN' was not declared in this scope
Reptier.h:212: error: 'DIO35_WPORT' was not declared in this scope
Reptier.h:212: error: 'DIO35_PIN' was not declared in this scope
Reptier.h:214: error: 'DIO35_WPORT' was not declared in this scope
Reptier.h:214: error: 'DIO35_PIN' was not declared in this scope
Reptier.h:214: error: 'DIO35_WPORT' was not declared in this scope
Reptier.h:214: error: 'DIO35_PIN' was not declared in this scope
This is all on the "Repetier.h" tab of the file stack which reads as follows.
/*
This file is part of Repetier-Firmware.
Repetier-Firmware is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Foobar is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar. If not, see <http://www.gnu.org/licenses/>.
This firmware is a nearly complete rewrite of the sprinter firmware
by kliment (https://github.com/kliment/Sprinter)
which based on Tonokip RepRap firmware rewrite based off of Hydra-mmm firmware.
*/
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#define COMPAT_PRE1
#endif
#include "gcode.h"
#include "fastio.h"
#ifdef SDSUPPORT
#include "Sd2Card.h"
#include "SdFat.h"
extern void initsd();
#endif
#define REPETIER_VERSION "0.71"
#define uint uint16_t
#define uint8 uint8_t
#define int8 int8_t
#define uint32 uint32_t
#define int32 int32_t
/*#if MOTHERBOARD==6 || MOTHERBOARD==62 || MOTHERBOARD==7
#if MOTHERBOARD!=7
#define SIMULATE_PWM
#endif
#define EXTRUDER_TIMER_VECTOR TIMER2_COMPA_vect
#define EXTRUDER_OCR OCR2A
#define EXTRUDER_TCCR TCCR2A
#define EXTRUDER_TIMSK TIMSK2
#define EXTRUDER_OCIE OCIE2A
#define PWM_TIMER_VECTOR TIMER2_COMPB_vect
#define PWM_OCR OCR2B
#define PWM_TCCR TCCR2B
#define PWM_TIMSK TIMSK2
#define PWM_OCIE OCIE2B
#else*/
#define EXTRUDER_TIMER_VECTOR TIMER0_COMPA_vect
#define EXTRUDER_OCR OCR0A
#define EXTRUDER_TCCR TCCR0A
#define EXTRUDER_TIMSK TIMSK0
#define EXTRUDER_OCIE OCIE0A
#define PWM_TIMER_VECTOR TIMER0_COMPB_vect
#define PWM_OCR OCR0B
#define PWM_TCCR TCCR0A
#define PWM_TIMSK TIMSK0
#define PWM_OCIE OCIE0B
//#endif
/** \brief Data to drive one extruder.
This structure contains all definitions for an extruder and all
current state variables, like current temperature, feeder position etc.
*/
typedef struct { // Size: 12*1 Byte+12*4 Byte+4*2Byte = 68 Byte
byte id;
long xOffset;
long yOffset;
float stepsPerMM; ///< Steps per mm.
byte sensorType; ///< Type of temperature sensor.
byte sensorPin; ///< Pin to read extruder temperature.
byte enablePin; ///< Pin to enable extruder stepper motor.
// byte directionPin; ///< Pin number to assign the direction.
// byte stepPin; ///< Pin number for a step.
byte enableOn;
// byte invertDir; ///< 1 if the direction of the extruder should be inverted.
float maxFeedrate;
float maxAcceleration; ///< Maximum acceleration in mm/s^2.
float maxStartFeedrate; ///< Maximum start feedrate in mm/s.
long extrudePosition; ///< Current extruder position in steps.
int currentTemperature; ///< Currenttemperature value read from sensor.
int targetTemperature; ///< Target temperature value in units of sensor.
int currentTemperatureC; ///< Current temperature in °C.
int targetTemperatureC; ///< Target temperature in °C.
long lastTemperatureUpdate; ///< Time in millis of the last temperature update.
char heatManager; ///< How is temperature controled. 0 = on/off, 1 = PID-Control
int watchPeriod; ///< Time in seconds, a M109 command will wait to stabalize temperature
#ifdef USE_ADVANCE
#ifdef ENABLE_QUADRATIC_ADVANCE
float advanceK; ///< Koefficient for advance algorithm. 0 = off
#endif
float advanceL;
#endif
// byte output; ///< Output value 0 = off, 255=MAX
#ifdef TEMP_PID
long tempIState; ///< Temp. var. for PID computation.
byte pidDriveMax; ///< Used for windup in PID calculation.
byte pidDriveMin; ///< Used for windup in PID calculation.
long pidPGain; ///< Pgain (proportional gain) for PID temperature control [0,01 Units].
long pidIGain; ///< Igain (integral) for PID temperature control [0,01 Units].
long pidDGain; ///< Dgain (damping) for PID temperature control [0,01 Units].
byte pidMax; ///< Maximum PWM value, the heater should be set.
long tempIStateLimitMax;
long tempIStateLimitMin;
byte tempPointer;
int tempArray[8];
#endif
} Extruder;
extern const uint8 osAnalogInputChannels[] PROGMEM;
extern uint8 osAnalogInputCounter[ANALOG_INPUTS];
extern uint osAnalogInputBuildup[ANALOG_INPUTS];
extern uint8 osAnalogInputPos; // Current sampling position
extern volatile uint osAnalogInputValues[ANALOG_INPUTS];
extern byte pwm_pos[4]; // 0-2 = Heater 0-2 of extruder, 3 = Fan
extern int target_bed_celsius;
#if HEATED_BED_SENSOR_TYPE!=0
extern int current_bed_raw;
extern int target_bed_raw;
#endif
#ifdef USE_ADVANCE
#ifdef ENABLE_QUADRATIC_ADVANCE
extern int maxadv;
#endif
extern int maxadv2;
extern float maxadvspeed;
#endif
extern Extruder *current_extruder;
extern Extruder extruder[];
// Initalize extruder and heated bed related pins
extern void initExtruder();
extern void extruder_select(byte ext_num);
// Set current extruder position
//extern void extruder_set_position(float pos,bool relative);
// set the temperature of current extruder
extern void extruder_set_temperature(int temp_celsius,byte extr);
extern int extruder_get_temperature();
// Set temperature of heated bed
extern void heated_bed_set_temperature(int temp_celsius);
//extern long extruder_steps_to_position(float value,byte relative);
extern void extruder_set_direction(byte steps);
extern void extruder_disable();
extern byte heated_bed_output;
//#ifdef TEMP_PID
//extern byte current_extruder_out;
//#endif
/** \brief Sends the high-signal to the stepper for next extruder step.
Call this function only, if interrupts are disabled.
*/
inline void extruder_step() {
#if NUM_EXTRUDER==1
#else
switch(current_extruder->id) {
case 0:
WRITE(EXT0_STEP_PIN,HIGH);
break;
#ifdef EXT1_STEP_PIN
case 1:
WRITE(EXT1_STEP_PIN,HIGH);
break;
#endif
#ifdef EXT2_STEP_PIN
case 2:
WRITE(EXT2_STEP_PIN,HIGH);
break;
#endif
}
#endif
}
/** \brief Sets stepper signal to low for current extruder.
Call this function only, if interrupts are disabled.
*/
inline void extruder_unstep() {
#if NUM_EXTRUDER==1
WRITE(EXT0_STEP_PIN,LOW);
#else
switch(current_extruder->id) {
case 0:
WRITE(EXT0_STEP_PIN,LOW);
break;
#ifdef EXT1_STEP_PIN
case 1:
WRITE(EXT1_STEP_PIN,LOW);
break;
#endif
#ifdef EXT2_STEP_PIN
case 2:
WRITE(EXT2_STEP_PIN,LOW);
break;
#endif
}
#endif
}
/** \brief Activates the extruder stepper and sets the direction. */
inline void extruder_set_direction(byte dir) {
#if NUM_EXTRUDER==1
if(dir)
WRITE(EXT0_DIR_PIN,!EXT0_INVERSE);
else
WRITE(EXT0_DIR_PIN,EXT0_INVERSE);
#else
switch(current_extruder->id) {
case 0:
if(dir)
WRITE(EXT0_DIR_PIN,!EXT0_INVERSE);
else
WRITE(EXT0_DIR_PIN,EXT0_INVERSE);
break;
#ifdef EXT1_DIR_PIN
case 1:
if(dir)
WRITE(EXT1_DIR_PIN,!EXT1_INVERSE);
else
WRITE(EXT1_DIR_PIN,EXT1_INVERSE);
break;
#endif
#ifdef EXT2_DIR_PIN
case 2:
if(dir)
WRITE(EXT2_DIR_PIN,!EXT2_INVERSE);
else
WRITE(EXT2_DIR_PIN,EXT2_INVERSE);
break;
#endif
}
#endif
}
inline void extruder_enable() {
#if NUM_EXTRUDER==1
#if EXT0_ENABLE_PIN>-1
WRITE(EXT0_ENABLE_PIN,EXT0_ENABLE_ON );
#endif
#else
if(current_extruder->enablePin > -1)
digitalWrite(current_extruder->enablePin,current_extruder->enableOn);
#endif
}
extern void(* resetFunc) (void);
// Read a temperature and return its value in °C
// this high level method supports all known methods
extern int read_raw_temperature(byte type,byte pin);
extern int heated_bed_get_temperature();
// Convert a raw temperature value into °C
extern int conv_raw_temp(byte type,int raw_temp);
// Converts a temperture temp in °C into a raw value
// which can be compared with results of read_raw_temperature
extern int conv_temp_raw(byte type,int temp);
// Updates the temperature of all extruders and heated bed if it's time.
// Toggels the heater power if necessary.
extern void manage_temperatures();
extern byte manage_monitor;
void process_command(GCode *code);
void manage_inactivity(byte debug);
extern void wait_until_end_of_move();
extern void update_ramps_parameter();
extern void finishNextSegment();
extern void printPosition();
extern void change_feedrate_multiply(int factor); ///< Set feedrate multiplier
extern void set_fan_speed(int speed,bool wait); /// Set fan speed 0..255
extern void home_axis(bool xaxis,bool yaxis,bool zaxis); /// Home axis
extern byte get_coordinates(GCode *com);
extern void move_steps(long x,long y,long z,long e,float feedrate,bool waitEnd,bool check_endstop);
extern void queue_move(byte check_endstops,byte pathOptimize);
extern void linear_move(long steps_remaining[]);
extern inline void disable_x();
extern inline void disable_y();
extern inline void disable_z();
extern inline void enable_x();
extern inline void enable_y();
extern inline void enable_z();
extern void kill(byte only_steppers);
extern float axis_steps_per_unit[];
extern float inv_axis_steps_per_unit[];
extern float max_feedrate[];
extern float homing_feedrate[];
extern float max_start_speed_units_per_second[];
extern long max_acceleration_units_per_sq_second[];
extern long max_travel_acceleration_units_per_sq_second[];
extern unsigned long axis_steps_per_sqr_second[];
extern unsigned long axis_travel_steps_per_sqr_second[];
extern byte relative_mode; ///< Determines absolute (false) or relative Coordinates (true).
extern byte relative_mode_e; ///< Determines Absolute or Relative E Codes while in Absolute Coordinates mode. E is always relative in Relative Coordinates mode.
extern byte unit_inches;
extern unsigned long previous_millis_cmd;
extern unsigned long max_inactive_time;
extern unsigned long stepper_inactive_time;
extern void setupTimerInterrupt();
typedef struct { // RAM usage: 72 Byte
byte flag0; // 1 = stepper disabled
#if USE_OPS==1 || defined(USE_ADVANCE)
volatile int extruderStepsNeeded; ///< This many extruder steps are still needed, <0 = reverse steps needed.
// float extruderSpeed; ///< Extruder speed in mm/s.
byte minExtruderSpeed; ///< Timer delay for start extruder speed
byte maxExtruderSpeed; ///< Timer delay for end extruder speed
byte extruderAccelerateDelay; ///< delay between 2 speec increases
#endif
long interval; ///< Last step duration in ticks.
#if USE_OPS==1
bool filamentRetracted; ///< Is the extruder filament retracted
#endif
unsigned long timer; ///< used for acceleration/deceleration timing
unsigned long stepNumber; ///< Step number in current move.
#ifdef USE_ADVANCE
#ifdef ENABLE_QUADRATIC_ADVANCE
long advance_executed; ///< Executed advance steps
#endif
int advance_steps_set;
unsigned int advance_lin_set;
#endif
long currentPositionSteps[4]; ///< Position in steps from origin.
long destinationSteps[4]; ///< Target position in steps.
#if USE_OPS==1
int opsRetractSteps; ///< Retract filament this much steps
int opsPushbackSteps; ///< Retract+extra distance for backslash
float opsMinDistance;
float opsRetractDistance;
float opsRetractBackslash;
byte opsMode; ///< OPS operation mode. 0 = Off, 1 = Classic, 2 = Fast
float opsMoveAfter; ///< Start move after opsModeAfter percent off full retract.
int opsMoveAfterSteps; ///< opsMoveAfter converted in steps (negative value!).
#endif
long xMaxSteps; ///< For software endstops, limit of move in positive direction.
long yMaxSteps; ///< For software endstops, limit of move in positive direction.
long zMaxSteps; ///< For software endstops, limit of move in positive direction.
float feedrate; ///< Last requested feedrate.
int feedrateMultiply; ///< Multiplier for feedrate in percent (factor 1 = 100)
unsigned int extrudeMultiply; ///< Flow multiplier in percdent (factor 1 = 100)
float maxJerk; ///< Maximum allowed jerk in mm/s
float maxZJerk; ///< Maximum allowed jerk in z direction in mm/s
long offsetX; ///< X-offset for different extruder positions.
long offsetY; ///< Y-offset for different extruder positions.
unsigned int vMaxReached; ///< MAximumu reached speed
byte stepper_loops;
} PrinterState;
extern PrinterState printer_state;
/** Marks the first step of a new move */
#define FLAG_WARMUP 1
#define FLAG_ACCELERATING 2
#define FLAG_DECELERATING 4
#define FLAG_ACCELERATION_ENABLED 8
#define FLAG_CHECK_ENDSTOPS 16
#define FLAG_SKIP_ACCELERATING 32
#define FLAG_SKIP_DEACCELERATING 64
#define FLAG_BLOCKED 128
/** Are the step parameter computed */
#define FLAG_JOIN_STEPPARAMS_COMPUTED 1
/** The right speed is fixed. Don't check this block or any block to the left. */
#define FLAG_JOIN_END_FIXED 2
/** The left speed is fixed. Don't check left block. */
#define FLAG_JOIN_START_FIXED 4
/** Start filament retraction at move start */
#define FLAG_JOIN_START_RETRACT 8
/** Wait for filament pushback, before ending move */
#define FLAG_JOIN_END_RETRACT 16
/** Disable retract for this line */
#define FLAG_JOIN_NO_RETRACT 32
/** Wait for the extruder to finish it's up movement */
#define FLAG_JOIN_WAIT_EXTRUDER_UP 64
/** Wait for the extruder to finish it's down movement */
#define FLAG_JOIN_WAIT_EXTRUDER_DOWN 128
// Printing related data
typedef struct { // RAM usage: 24*4+15 = 111 Byte
byte primaryAxis;
byte flags;
byte joinFlags;
byte halfstep; ///< 0 = disabled, 1 = halfstep, 2 = fulstep
byte dir; ///< Direction of movement. 1 = X+, 2 = Y+, 4= Z+, values can be combined.
long delta[4]; ///< Steps we want to move.
long error[4]; ///< Error calculation for Bresenham algorithm
float speedX; ///< Speed in x direction at fullInterval in mm/s
float speedY; ///< Speed in y direction at fullInterval in mm/s
float speedZ; ///< Speed in z direction at fullInterval in mm/s
float fullSpeed; ///< Desired speed mm/s
float acceleration; ///< Real acceleration mm/s²
float distance;
float startFactor;
float endFactor;
unsigned long fullInterval; ///< interval at full speed in ticks/step.
unsigned long stepsRemaining; ///< Remaining steps, until move is finished
unsigned int accelSteps; ///< How much steps does it take, to reach the plateau.
unsigned int decelSteps; ///< How much steps does it take, to reach the end speed.
unsigned long accelerationPrim; ///< Acceleration along primary axis
unsigned long facceleration; ///< accelerationPrim*262144/F_CPU
unsigned int vMax; ///< Maximum reached speed in steps/s.
unsigned int vStart; ///< Starting speed in steps/s.
unsigned int vEnd; ///< End speed in steps/s
#ifdef USE_ADVANCE
#ifdef ENABLE_QUADRATIC_ADVANCE
long advanceRate; ///< Advance steps at full speed
long advanceFull; ///< Maximum advance at fullInterval [steps*65536]
long advanceStart;
long advanceEnd;
#endif
unsigned int advanceL; ///< Recomputated L value
#endif
#if USE_OPS==1
long opsReverseSteps; ///< How many steps are needed to reverse retracted filament at full speed
#endif
#ifdef DEBUG_STEPCOUNT
long totalStepsRemaining;
#endif
} PrintLine;
extern PrintLine lines[];
extern byte lines_write_pos; // Position where we write the next cached line move
extern byte lines_pos; // Position for executing line movement
extern volatile byte lines_count; // Number of lines cached 0 = nothing to do
extern byte printmoveSeen;
extern long baudrate;
#ifdef SIMULATE_FAN_PWM
extern int fan_speed;
#endif
#if OS_ANALOG_INPUTS>0
// Get last result for pin x
extern volatile uint osAnalogInputValues[OS_ANALOG_INPUTS];
#endif
#define BEGIN_INTERRUPT_PROTECTED {byte sreg=SREG;__asm volatile( "cli" ::: "memory" );
#define END_INTERRUPT_PROTECTED SREG=sreg;}
#define ESCAPE_INTERRUPT_PROTECTED SREG=sreg;
#define SECONDS_TO_TICKS(s) (unsigned long)(s*(float)F_CPU)
extern long CPUDivU2(unsigned int divisor);
extern byte counter_periodical;
extern volatile byte execute_periodical;
extern byte counter_250ms;
extern void write_monitor();
extern void check_periodical();
#define CELSIUS_EXTRA_BITS 3
#define ANALOG_REDUCE_BITS 0
#define ANALOG_REDUCE_FACTOR 1
#ifdef SDSUPPORT
extern Sd2Card card; // ~14 Byte
extern SdVolume volume;
extern SdFile root;
extern SdFile file;
extern uint32_t filesize;
extern uint32_t sdpos;
extern bool sdmode;
extern bool sdactive;
extern bool savetosd;
extern int16_t n;
#endif
I don't know what to declare as those variables, but I know they are variables that need to be defined. How can I fix this problem?

Block life cycle in function?

Block variable in objective-c is a reference and I learned from somewhere infer that following code may be transformed by compiler to another form.
Original code:
typedef int (^block_type)();
block_type create_k(int i)
{
block_type block = ^(){
return i;
};
//[block copy];
return block;
}
Generated Code:
typedef void (*generic_invoke_funcptr)(void *, ...);
struct __block_literal {
void *isa;
int flags;
int reserved;
generic_invoke_funcptr invoke;
struct __block_descriptor_tmp *descriptor;
const int captured_i;
};
static const struct __block_descriptor_tmp {
unsigned long reserved;
unsigned long literal_size;
/* no copy/dispose helpers needed */
} __block_descriptor_tmp = {
0UL, sizeof(struct __block_literal)
};
// ^int (void) { return i; }
int __create_k_block_invoke_(struct __block_literal *bp) {
return bp->captured_i;
}
typedef int (*iv_funcptr)(struct __block_literal *);
typedef int (^block_type)();
block_type create_k(int i)
{
//block_type block = ^(){
// return i;
//};
struct __block_literal __b = {
.isa = &_NSConcreteStackBlock,
.flags = BLOCK_HAS_DESCRIPTOR,
.reserved = 0,
.invoke = (generic_invoke_funcptr)__f_block_invoke_,
.descriptor = &__block_descriptor_tmp,
.captured_i = i
};
struct __block_literal *block = &__b;
return block;
}
So |_b| in stack and block is only a reference to |_b|. If |create_k| return |block|, the receiver only get a invalid address.
But
int main(int argc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
printf("%d\n", create_k(40)());
[pool drain];
return 0;
}
By exec it, print |40| and |block| is a valid block. What's the matter?
My guess would be that the memory for that stack frame hasn't been zeroed yet. Try calling another function between create_k() and printf() to get some other random data in there.