How to get usb mass storage size using libusb library? - libusb

I am finding out usb mass storage related information using libusb library.
But don't know how to get usb mass storage size?
My tryout is:
void printdev(libusb_device *dev);
int main()
{
libusb_device **devs;
libusb_context *ctx = NULL; //a libusb session
int r;
ssize_t cnt; //holding number of devices in list
r = libusb_init(&ctx); //initialize a library session
if(r < 0)
{
cout<<"Init Error "<<r<<endl; //there was an error
return 1;
}
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if(cnt < 0)
{
cout<<"Get Device Error"<<endl; //there was an error
}
cout<<cnt<<" Devices in list."<<endl; //print total number of usb devices
int i;
for(i = 0; i < cnt; i++)
{
printdev(devs[i]);
}
libusb_free_device_list(devs, 1); //free the list, unref the devices in it
libusb_exit(ctx); //close the session
return 0;
}
void printdev(libusb_device *dev)
{
libusb_device_descriptor desc;
libusb_config_descriptor *conDesc;
char szBuffer[256] = {0};
unsigned char strDesc[256];
libusb_device_handle *devHandle = NULL;
int retVal;
__int64 i64Temp;
DWORD dwProdId;
DWORD dwProdId1;
i64Temp = 13888;
dwProdId = (DWORD)i64Temp;
retVal = libusb_open (dev, &devHandle);
if (retVal != LIBUSB_SUCCESS)
return;
int r = libusb_get_device_descriptor(dev, &desc);
if (r < 0)
{
cout<<"failed to get device descriptor"<<endl;
return;
}
r = libusb_get_config_descriptor(dev, 0, &conDesc);
printf("Interface Class = %d\n", conDesc->interface->altsetting->bInterfaceClass);
cout<<"Number of possible configurations: "<<(int)desc.bNumConfigurations<<" ";
// cout<<"Device Class: "<<desc.bDeviceClass<<endl;
// cout<<"Device Class: "<<desc.bDeviceSubClass<<endl;
printf("Class = %d\n", desc.bDeviceClass);
cout<<"VendorID: "<<desc.idVendor<<endl;
cout<<"ProductID: "<<desc.idProduct<<endl;
dwProdId1 = (DWORD)desc.idProduct;
if (dwProdId1 == dwProdId)
{
printf("in if\n");
}
else
{
printf("in else\n");
}
retVal = libusb_get_string_descriptor_ascii(devHandle, desc.iManufacturer, strDesc, 256);
printf ("Manufacturer: %s\n", strDesc);
retVal = libusb_get_string_descriptor_ascii(devHandle, desc.iSerialNumber, strDesc, 256);
printf ("SerialNumber: %s\n", strDesc);
retVal = libusb_get_string_descriptor_ascii(devHandle, desc.iProduct, strDesc, 256);
printf ("Product: %s\n", strDesc);
printf("\n\n");
}

Related

C/C++ Socket UDP Client Data Sending -> Keep sending only one peer

i faced a problem with Multi-UDP Socket.
Now I have a PC(192.168.58.200), and 3 MPU(STM32F4)(192.168.85.100~102).
and I Conncected RS232 With MPU.
When MPU got a messasge, it returns just 'X', and print out same thing with RS232, so i can distinguish when PC can not send message and when MPU can get a message but PC can not recieve the message.
below is my code, Especially "UdpClient[c].Write( TempStr, strlen(TempStr));" doesnt work.
when it send mesage, only one MPU can get a message, and keep reciving 30~40 sec, some times changed other MPU.
1:1 is fine, but problem is more 2 Peer. please share your experiences.
// udpclient.cpp
#include <stdio.h>
#include "UDPCLIENT.h"
#include "UDPServer.h"
struct sPeer
{
char IP[64];
int Port;
};
#define CUR_MPU 3
#define MAX_MPU 16
sPeer Peer[MAX_MPU];
unsigned long _stdcall ReadThread(void *Param)
{
UDPSERVERSOCKET UDPSocket;
int ID = (int)Param;
printf("Server ID %d\n", ID);
UDPSocket.Open(Peer[ID].Port);
while (1)
{
char ReadBuffer[1024];
char Addr[32];
UDPSocket.Read(Addr, ReadBuffer, 1024);
printf("%s>%s\n", Addr, ReadBuffer);
}
UDPSocket.Close();
return 0;
}
int main()
{
sprintf(Peer[0].IP, "192.168.58.100"); Peer[0].Port = 7726;
sprintf(Peer[1].IP, "192.168.58.101"); Peer[1].Port = 7727;
sprintf(Peer[2].IP, "192.168.58.102"); Peer[2].Port = 7728;
///////////////////////쓰레드를 연다./////////////////
for (int c = 0; c < CUR_MPU; c++)
{
DWORD ID;
HANDLE thread01 = CreateThread( NULL,//보안 속성
0,//스택의 크기
ReadThread,//함수
(void *)c,//인자
0,//생성플러그
&ID);// 아이디
}
UDPCLIENTSOCKET UdpClient[CUR_MPU];
for (int c = 0; c < CUR_MPU; c++)
{
UdpClient[c].Open(Peer[c].IP, Peer[c].Port);
}
while (1)
{
char TempStr[1024];
printf("보낼 메시지 ---");
scanf("%s", TempStr);
for (int c = 0; c < CUR_MPU; c++)
{
UdpClient[c].Write( TempStr, strlen(TempStr));
}
}
for (int c = 0; c < CUR_MPU; c++)
UdpClient[c].Close();
return 0;
}
Cleint.cpp
#include "UDPCLIENT.h"
int UDPCLIENTSOCKET::Open(char *Address , int Port)
{
unsigned int addr;
int nRtn = WSAStartup(MAKEWORD(1, 1), &wsaData);
if (nRtn != 0) {
perror("WSAStartup 오류\n");
return -1;
}
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0) {
perror("소켓 오류\n");
WSACleanup();
return -2;
}
lpHostEnt = gethostbyname(Address);
if (lpHostEnt == NULL) {
addr = inet_addr(Address);
lpHostEnt = gethostbyaddr((char *)&addr, 4, AF_INET);
if (lpHostEnt == NULL) {
perror("서버를 찾을 수 없습니다.\n");
_getch();
return -3;
}
}
memset(&addrin, 0, sizeof(addrin));
memcpy(&(addrin.sin_addr),
lpHostEnt->h_addr_list[0],
lpHostEnt->h_length);
addrin.sin_port = htons(Port);
addrin.sin_family = AF_INET;
//addrin.sin_addr.s_addr =
// *((unsigned long *)lpHostEnt->h_addr);
return 1;
}
void UDPCLIENTSOCKET::Close()
{
closesocket(s);
WSACleanup();
}
int UDPCLIENTSOCKET::Write(char *Address, int Port, char *Buffer, int Size)
{
unsigned int addr;
lpHostEnt = gethostbyname(Address);
if (lpHostEnt == NULL) {
addr = inet_addr(Address);
lpHostEnt = gethostbyaddr((char *)&addr, 4, AF_INET);
if (lpHostEnt == NULL) {
perror("서버를 찾을 수 없습니다.\n");
_getch();
return -3;
}
}
memset(&addrin, 0, sizeof(addrin));
memcpy(&(addrin.sin_addr),
lpHostEnt->h_addr_list[0],
lpHostEnt->h_length);
addrin.sin_port = htons(Port);
addrin.sin_family = AF_INET;
int nRtn = sendto(s, Buffer, Size, 0,
(LPSOCKADDR)&addrin, sizeof(addrin));
return nRtn;
}
int UDPCLIENTSOCKET::Write(char *Buffer, int Size)
{
int nRtn = sendto(s, Buffer, Size, 0,
(LPSOCKADDR)&addrin, sizeof(addrin));
return nRtn;
}
Server.cpp
#include "UDPServer.h"
int UDPSERVERSOCKET::Open(u_short uport)
{
int nRtn;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
perror("WSAStartup Error\n");
return -1;
}
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0) {
perror("socket 오류\n");
WSACleanup();
return -2;
}
memset(&addrin, 0, sizeof(addrin));
addrin.sin_port = htons(uport);
addrin.sin_family = AF_INET;
addrin.sin_addr.s_addr = htonl(INADDR_ANY);
nRtn = bind(s, (LPSOCKADDR)&addrin, (int)sizeof(addrin));
if (nRtn == SOCKET_ERROR) {
perror("bind 오류\n");
closesocket(s);
WSACleanup();
return -3;
}
return 1;
}
int UDPSERVERSOCKET::Read(char *Addr, char *Buffer, int Length)
{
int fromlen = (int)sizeof(from);
int nRtn = recvfrom(s,
Buffer,
Length -1,
0,
(SOCKADDR *)&from,
&fromlen);
if (nRtn == SOCKET_ERROR)
{
Addr[0] = 0;
perror("recvform 오류\n");
closesocket(s);
WSACleanup();
return -4;
}
strcpy(Addr, inet_ntoa(from.sin_addr));
Buffer[nRtn] = '\0';
return 1;
}
int UDPSERVERSOCKET::Close()
{
closesocket(s);
WSACleanup();
printf("WSACleanup 완료\n");
return 1;
}
void UDPSERVERSOCKET::ShowErrorMessage(int i)
{
}
void UDPSERVERSOCKET::ReturnClientIP(char *Buffer)
{
}

encode .wav file using ffmpeg in objective c or c

I have to encode .wav file and write it into same file,or other file using
ffmpeg library,here is my code for encoding
-(void)audioencode:(const char *)fileName
{
AVFrame *frame;
AVPacket pkt;
int i, j, k, ret, got_output;
int buffer_size;
FILE *f;
uint16_t *samples;
const char *format_name = "wav",
const char *file_url = "/Users/xxxx/Downloads/simple-drum-beat.wav";
avcodec_register_all();
av_register_all();
AVOutputFormat *format = NULL;
for (AVOutputFormat *formatIter = av_oformat_next(NULL); formatIter != NULL; formatIter = av_oformat_next(formatIter)
{
int hasEncoder = NULL != avcodec_find_encoder(formatIter->audio_codec);
if (0 == strcmp(format_name, formatIter->name)) {
format = formatIter;
break;
}
}
AVCodec *codec = avcodec_find_encoder(format->audio_codec);
NSLog(#"tet test tststs");
AVCodecContext *c;
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate audio codec context\n");
exit(1);
}
c->sample_fmt = AV_SAMPLE_FMT_S16;
if (!check_sample_fmt(codec, c->sample_fmt)) {
fprintf(stderr, "Encoder does not support sample format %s",
av_get_sample_fmt_name(c->sample_fmt));
exit(1);
}
c->bit_rate = 64000;//705600;
c->sample_rate = select_sample_rate(codec);
c->channel_layout = select_channel_layout(codec);
c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
c->frame_size = av_get_audio_frame_duration(c, 16);
int bits_per_sample = av_get_bits_per_sample(c->codec_id);
int frameSize = av_get_audio_frame_duration(c,16);
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
f = fopen(fileName, "wb");
if (!f) {
fprintf(stderr, "Could not open %s\n", fileName);
exit(1);
}
/* frame containing input raw audio */
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate audio frame\n");
exit(1);
}
frame->nb_samples = frameSize/*c->frame_size*/;
frame->format = c->sample_fmt;
frame->channel_layout = c->channel_layout;
buffer_size = av_samples_get_buffer_size(NULL, c->channels,frameSize /*c->frame_size*/,
c->sample_fmt, 0);
samples = av_malloc(buffer_size);
if (!samples) {
fprintf(stderr, "Could not allocate %d bytes for samples buffer\n",
buffer_size);
exit(1);
}
/* setup the data pointers in the AVFrame */
ret = avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
(const uint8_t*)samples, buffer_size, 0);
if (ret < 0) {
fprintf(stderr, "Could not setup audio frame\n");
exit(1);
}
float t, tincr;
/* encode a single tone sound */
t = 0;
tincr = 2 * M_PI * 440.0 / c->sample_rate;
for(i=0;i<800;i++) {
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
for (j = 0; j < frameSize/*c->frame_size*/; j++) {
samples[2*j] = (int)(sin(t) * 10000);
for (k = 1; k < c->channels; k++)
samples[2*j + k] = samples[2*j];
t += tincr;
}
/* encode the samples */
ret = avcodec_encode_audio2(c, &pkt, frame, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding audio frame\n");
exit(1);
}
if (got_output) {
fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
}
but after encoded file size is zero,
Please suggest what m doing wrong,any help will be appreciate, thanks in advance

How do I read data from a pendrive through USB using libusb on Windows using the C programming language

I am trying to read data from a pendrive connected through USB on Windows using libusb and C-programming. I am able to list out my USB connections, but I couldn't connect to one and transfer data from the USB in to my computer.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libusb.h"
#define BULK_EP_OUT 0x63
#define BULK_EP_IN 0x08
int interface_ref = 0;
int alt_interface, interface_number;
int print_configuration(struct libusb_device_handle *hDevice, struct libusb_config_descriptor *config)
{
char *data;
int index;
data = (char *)malloc(512);
memset(data, 0, 512);
index = config->iConfiguration;
libusb_get_string_descriptor_ascii(hDevice, index, data, 512);
printf("\nInterface Descriptors: ");
printf("\n\tNumber of Interfaces: %d", config->bNumInterfaces);
printf("\n\tLength: %d", config->bLength);
printf("\n\tDesc_Type: %d", config->bDescriptorType);
printf("\n\tConfig_index: %d", config->iConfiguration);
printf("\n\tTotal length: %lu", config->wTotalLength);
printf("\n\tConfiguration Value: %d", config->bConfigurationValue);
printf("\n\tConfiguration Attributes: %d", config->bmAttributes);
printf("\n\tMaxPower(mA): %d\n", config->MaxPower);
free(data);
data = NULL;
return 0;
}
struct libusb_endpoint_descriptor* active_config(struct libusb_device *dev, struct libusb_device_handle *handle)
{
struct libusb_device_handle *hDevice_req;
struct libusb_config_descriptor *config;
struct libusb_endpoint_descriptor *endpoint;
int altsetting_index, interface_index=0, ret_active;
int i, ret_print;
hDevice_req = handle;
ret_active = libusb_get_active_config_descriptor(dev, &config);
ret_print = print_configuration(hDevice_req, config);
for (interface_index=0;interface_index<config->bNumInterfaces;interface_index++)
{
const struct libusb_interface *iface = &config->interface[interface_index];
for (altsetting_index=0; altsetting_index<iface->num_altsetting; altsetting_index++)
{
const struct libusb_interface_descriptor *altsetting = &iface->altsetting[altsetting_index];
int endpoint_index;
for(endpoint_index=0; endpoint_index<altsetting->bNumEndpoints; endpoint_index++)
{
const struct libusb_endpoint_desriptor *ep = &altsetting->endpoint[endpoint_index];
endpoint = ep;
alt_interface = altsetting->bAlternateSetting;
interface_number = altsetting->bInterfaceNumber;
}
printf("\nEndPoint Descriptors: ");
printf("\n\tSize of EndPoint Descriptor: %d", endpoint->bLength);
printf("\n\tType of Descriptor: %d", endpoint->bDescriptorType);
printf("\n\tEndpoint Address: 0x0%x", endpoint->bEndpointAddress);
printf("\n\tMaximum Packet Size: %x", endpoint->wMaxPacketSize);
printf("\n\tAttributes applied to Endpoint: %d", endpoint->bmAttributes);
printf("\n\tInterval for Polling for data Tranfer: %d\n", endpoint->bInterval);
}
}
libusb_free_config_descriptor(NULL);
return endpoint;
}
int main(void)
{
int r = 1, found1;
struct libusb_device **devs;
struct libusb_device_handle *handle = NULL, *hDevice_expected = NULL;
struct libusb_device *dev, *dev_expected;
struct libusb_device_descriptor desc;
struct libusb_endpoint_descriptor *epdesc;
struct libusb_interface_descriptor *intdesc;
libusb_context *context = NULL;
ssize_t cnt;
int e = 0, config2;
int i = 0, index;
char str1[64], str2[64];
char found = 0;
// Init libusb
r = libusb_init(NULL);
if(r < 0)
{
printf("\nFailed to initialise libusb\n");
return 1;
}
else
printf("\nInit successful!\n");
// Get a list of USB devices
cnt = libusb_get_device_list(NULL, &devs);
if (cnt < 0)
{
printf("\nThere are no USB devices on the bus\n");
return -1;
}
printf("\nDevice count: %d\n-------------------------------\n", cnt);
while ((dev = devs[i++]) > 0)
{
r = libusb_get_device_descriptor(dev, &desc);
if (r < 0)
{
printf("Failed to get device descriptor\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
e = libusb_open(dev, &handle);
if (e < 0)
{
printf("Error opening device\n");
printf(e);
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
printf("\nDevice Descriptors: ");
printf("\n\tVendor ID: %x", desc.idVendor);
printf("\n\tProduct ID: %x", desc.idProduct);
printf("\n\tSerial Number: %x", desc.iSerialNumber);
printf("\n\tSize of Device Descriptor: %d", desc.bLength);
printf("\n\tType of Descriptor: %d", desc.bDescriptorType);
printf("\n\tUSB Specification Release Number: %d", desc.bcdUSB);
printf("\n\tDevice Release Number: %d", desc.bcdDevice);
printf("\n\tDevice Class: %d", desc.bDeviceClass);
printf("\n\tDevice Sub-Class: %d", desc.bDeviceSubClass);
printf("\n\tDevice Protocol: %d", desc.bDeviceProtocol);
printf("\n\tMax. Packet Size: %d", desc.bMaxPacketSize0);
printf("\n\tNumber of Configurations: %d\n", desc.bNumConfigurations);
e = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, (unsigned char*) str1, sizeof(str1));
if (e < 0)
{
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
printf("\nManufactured: %s", str1);
e = libusb_get_string_descriptor_ascii(handle, desc.iProduct, (unsigned char*) str2, sizeof(str2));
if(e < 0)
{
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
printf("\nProduct: %s", str2);
printf("\n----------------------------------------");
if(desc.idVendor == 0x0781 && desc.idProduct == 0x5567)
{
found1 = 1;
break;
}
}//end of while
if (found1 == 0)
{
printf("\nDevice NOT found\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return 1;
}
else
{
printf("\nDevice found");
dev_expected = dev;
hDevice_expected = handle;
}
e = libusb_get_configuration(handle, &config2);
if (e!=0)
{
printf("\n***Error in libusb_get_configuration\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
printf("\nConfigured value: %d", config2);
if (config2 != 1)
{
libusb_set_configuration(handle, 1);
if(e!=0)
{
printf("Error in libusb_set_configuration\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
else
printf("\nDevice is in configured state!");
}
libusb_free_device_list(devs, 1);
if(libusb_kernel_driver_active(handle, 0) == 1)
{
printf("\nKernel Driver Active");
if(libusb_detach_kernel_driver(handle, 0) == 0)
printf("\nKernel Driver Detached!");
else
{
printf("\nCouldn't detach kernel driver!\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
}
e = libusb_claim_interface(handle, 0);
if (e < 0)
{
printf("\nCannot Claim Interface");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
else
printf("\nClaimed Interface\n");
active_config(dev_expected, hDevice_expected);
char *my_string, *my_string1;
int transferred = 0;
int received = 0;
int length = 0;
int nbytes = 256;
my_string = (char *)malloc(nbytes + 1);
my_string1 = (char *)malloc(nbytes + 1);
memset(my_string, '\0', 64);
memset(my_string1, '\0', 64);
strcpy(my_string, "Prasad Divesd");
length = strlen(my_string);
printf("\nTo be sent: %s", my_string);
for(i = 0; i < length; i++)
{
e = libusb_bulk_transfer(handle, BULK_EP_OUT, my_string1, 64, &received, 0); //64: Max Packet Length
if(e == 0)
{
printf("\nReceived: ");
printf("%c", my_string1[i]);
_sleep(1);
}
else
{
printf("\nError in read! e = %d and received = %d\n", e, received);
return -1;
}
}
e = libusb_release_interface(handle, 0);
libusb_close(handle);
libusb_exit(NULL);
printf("\n");
return 0;
}
The code from Read/write on a pen drive using libusb: libusb_bulk_transfer() is for Linux. The sequence below is to detach the kernel driver in Linux.
This is done to be able write a bulk transfer to the USB mass storage device (pendrive). In Linux this is necessary, in Windows not because in Windows libusb has its own driver:
if(libusb_kernel_driver_active(handle, 0) == 1)
{
printf("\nKernel Driver Active");
if(libusb_detach_kernel_driver(handle, 0) == 0)
printf("\nKernel Driver Detached!");
else
{
printf("\nCouldn't detach kernel driver!\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
}
So you have to delete at least this code.
Then notice that libusb on Windows has some limitations, see https://github.com/libusb/libusb/wiki/Windows.
If you want to debug programs use a debugger like WinDbg (Viewing the Call Stack in WinDbg) and get a stack trace (Windows Debuggers: Part 1: A WinDbg Tutorial and Viewing the Call Stack in WinDbg)
For more information on USB, see USB in a NutShell.
Beside this the code you posted should work (when removing the Linux-specific lines, etc.).

Read/write on a pen drive using libusb: libusb_bulk_transfer()

I am trying to perform read and write operations on a pen drive.
Details: Vendor ID: 8564 and Product ID: 1000. It is a Transcend JetFlash mass storage device.
I am keen to know that whether it is possible to achieve a read/write on a pen drive. If it is, then is it going to happen the way I have tried in the code provided below.
I have learnt the methods to get the device id, product id and endpoint addresses. This is what I have implemented.
Here the device is getting acknowledged and opened. And, even the interface claims it is successful.
But bulk transfer functions return -1.
What is the explanation?
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include </usr/include/libusb-1.0/libusb.h>
#define BULK_EP_OUT 0x82
#define BULK_EP_IN 0x02
int main(void)
{
int r = 0, e = 0;
struct libusb_device_handle *handle = NULL;
struct libusb_device **devs;
struct libusb_device *dev;
struct libusb_device_descriptor desc;
char str1[256], str2[256];
/* Init libusb */
r = libusb_init(NULL);
if (r < 0)
{
printf("\nfailed to initialise libusb\n");
return 1;
}
handle = libusb_open_device_with_vid_pid(NULL, 0x8564, 0x1000);
if(handle == NULL)
{
printf("\nError in device opening!");
}
else
printf("\nDevice Opened");
// Tell libusb to use the CONFIGNUM configuration of the device
libusb_set_configuration(handle, 1);
if(libusb_kernel_driver_active(handle, 0) == 1)
{
printf("\nKernel Driver Active");
if(libusb_detach_kernel_driver(handle, 0) == 0)
printf("\nKernel Driver Detached!");
}
e = libusb_claim_interface(handle, 0);
if(e < 0)
{
printf("\nCannot Claim Interface");
}
else
printf("\nClaimed Interface");
/* Communicate */
int bytes_read;
int nbytes = 256;
unsigned char *my_string, *my_string1;
int transferred = 0;
my_string = (unsigned char *) malloc (nbytes + 1);
my_string1 = (unsigned char *) malloc (nbytes + 1);
strcpy(my_string, "divesd");
printf("\nTo be sent : %s", my_string);
e = libusb_bulk_transfer(handle, BULK_EP_OUT, my_string, bytes_read, &transferred, 5000);
printf("\nXfer returned with %d", e);
printf("\nSent %d bytes with string: %s\n", transferred, my_string);
libusb_bulk_transfer(handle, BULK_EP_IN, my_string1, 256, &transferred, 5000);
printf("\nXfer returned with %d", e); //It returns -1... This is an error, I guess.
printf("\nReceived %d bytes with string: %s\n", transferred, my_string1);
e = libusb_release_interface(handle, 0);
libusb_close(handle);
libusb_exit(NULL);
return 0;
}
Try the code given below and it should work on LPC2148. I have tested this with an LPC2148 configured to receive an interrupt from USB after a write happens (from user-space) and the RTC starts running.
Answering to your question whether it involves a kernel driver in read/write or not: As far as I have studied, you have to detach the kernel driver and claim the interface using libusb APIs. Though I am not sure whether it can be done without detaching it or not.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include </usr/local/include/libusb-1.0/libusb.h>
#define BULK_EP_OUT 0x82
#define BULK_EP_IN 0x08
int interface_ref = 0;
int alt_interface, interface_number;
int print_configuration(struct libusb_device_handle *hDevice, struct libusb_config_descriptor *config)
{
char *data;
int index;
data = (char *)malloc(512);
memset(data, 0, 512);
index = config->iConfiguration;
libusb_get_string_descriptor_ascii(hDevice, index, data, 512);
printf("\nInterface Descriptors: ");
printf("\n\tNumber of Interfaces: %d", config->bNumInterfaces);
printf("\n\tLength: %d", config->bLength);
printf("\n\tDesc_Type: %d", config->bDescriptorType);
printf("\n\tConfig_index: %d", config->iConfiguration);
printf("\n\tTotal length: %lu", config->wTotalLength);
printf("\n\tConfiguration Value: %d", config->bConfigurationValue);
printf("\n\tConfiguration Attributes: %d", config->bmAttributes);
printf("\n\tMaxPower(mA): %d\n", config->MaxPower);
free(data);
data = NULL;
return 0;
}
struct libusb_endpoint_descriptor* active_config(struct libusb_device *dev, struct libusb_device_handle *handle)
{
struct libusb_device_handle *hDevice_req;
struct libusb_config_descriptor *config;
struct libusb_endpoint_descriptor *endpoint;
int altsetting_index, interface_index=0, ret_active;
int i, ret_print;
hDevice_req = handle;
ret_active = libusb_get_active_config_descriptor(dev, &config);
ret_print = print_configuration(hDevice_req, config);
for (interface_index=0;interface_index<config->bNumInterfaces;interface_index++)
{
const struct libusb_interface *iface = &config->interface[interface_index];
for (altsetting_index=0; altsetting_index<iface->num_altsetting; altsetting_index++)
{
const struct libusb_interface_descriptor *altsetting = &iface->altsetting[altsetting_index];
int endpoint_index;
for(endpoint_index=0; endpoint_index<altsetting->bNumEndpoints; endpoint_index++)
{
const struct libusb_endpoint_desriptor *ep = &altsetting->endpoint[endpoint_index];
endpoint = ep;
alt_interface = altsetting->bAlternateSetting;
interface_number = altsetting->bInterfaceNumber;
}
printf("\nEndPoint Descriptors: ");
printf("\n\tSize of EndPoint Descriptor: %d", endpoint->bLength);
printf("\n\tType of Descriptor: %d", endpoint->bDescriptorType);
printf("\n\tEndpoint Address: 0x0%x", endpoint->bEndpointAddress);
printf("\n\tMaximum Packet Size: %x", endpoint->wMaxPacketSize);
printf("\n\tAttributes applied to Endpoint: %d", endpoint->bmAttributes);
printf("\n\tInterval for Polling for data Tranfer: %d\n", endpoint->bInterval);
}
}
libusb_free_config_descriptor(NULL);
return endpoint;
}
int main(void)
{
int r = 1;
struct libusb_device **devs;
struct libusb_device_handle *handle = NULL, *hDevice_expected = NULL;
struct libusb_device *dev, *dev_expected;
struct libusb_device_descriptor desc;
struct libusb_endpoint_descriptor *epdesc;
struct libusb_interface_descriptor *intdesc;
ssize_t cnt;
int e = 0, config2;
int i = 0, index;
char str1[64], str2[64];
char found = 0;
// Init libusb
r = libusb_init(NULL);
if(r < 0)
{
printf("\nFailed to initialise libusb\n");
return 1;
}
else
printf("\nInit successful!\n");
// Get a list of USB devices
cnt = libusb_get_device_list(NULL, &devs);
if (cnt < 0)
{
printf("\nThere are no USB devices on the bus\n");
return -1;
}
printf("\nDevice count: %d\n-------------------------------\n", cnt);
while ((dev = devs[i++]) != NULL)
{
r = libusb_get_device_descriptor(dev, &desc);
if (r < 0)
{
printf("Failed to get device descriptor\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
e = libusb_open(dev, &handle);
if (e < 0)
{
printf("Error opening device\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
printf("\nDevice Descriptors: ");
printf("\n\tVendor ID: %x", desc.idVendor);
printf("\n\tProduct ID: %x", desc.idProduct);
printf("\n\tSerial Number: %x", desc.iSerialNumber);
printf("\n\tSize of Device Descriptor: %d", desc.bLength);
printf("\n\tType of Descriptor: %d", desc.bDescriptorType);
printf("\n\tUSB Specification Release Number: %d", desc.bcdUSB);
printf("\n\tDevice Release Number: %d", desc.bcdDevice);
printf("\n\tDevice Class: %d", desc.bDeviceClass);
printf("\n\tDevice Sub-Class: %d", desc.bDeviceSubClass);
printf("\n\tDevice Protocol: %d", desc.bDeviceProtocol);
printf("\n\tMax. Packet Size: %d", desc.bMaxPacketSize0);
printf("\n\tNumber of Configurations: %d\n", desc.bNumConfigurations);
e = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, (unsigned char*) str1, sizeof(str1));
if (e < 0)
{
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
printf("\nManufactured: %s", str1);
e = libusb_get_string_descriptor_ascii(handle, desc.iProduct, (unsigned char*) str2, sizeof(str2));
if(e < 0)
{
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
printf("\nProduct: %s", str2);
printf("\n----------------------------------------");
if(desc.idVendor == 0xffff && desc.idProduct == 0x4)
{
found = 1;
break;
}
}//end of while
if(found == 0)
{
printf("\nDevice NOT found\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return 1;
}
else
{
printf("\nDevice found");
dev_expected = dev;
hDevice_expected = handle;
}
e = libusb_get_configuration(handle, &config2);
if(e!=0)
{
printf("\n***Error in libusb_get_configuration\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
printf("\nConfigured value: %d", config2);
if(config2 != 1)
{
libusb_set_configuration(handle, 1);
if(e!=0)
{
printf("Error in libusb_set_configuration\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
else
printf("\nDevice is in configured state!");
}
libusb_free_device_list(devs, 1);
if(libusb_kernel_driver_active(handle, 0) == 1)
{
printf("\nKernel Driver Active");
if(libusb_detach_kernel_driver(handle, 0) == 0)
printf("\nKernel Driver Detached!");
else
{
printf("\nCouldn't detach kernel driver!\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
}
e = libusb_claim_interface(handle, 0);
if(e < 0)
{
printf("\nCannot Claim Interface");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
else
printf("\nClaimed Interface\n");
active_config(dev_expected, hDevice_expected);
// Communicate
char *my_string, *my_string1;
int transferred = 0;
int received = 0;
int length = 0;
my_string = (char *)malloc(nbytes + 1);
my_string1 = (char *)malloc(nbytes + 1);
memset(my_string, '\0', 64);
memset(my_string1, '\0', 64);
strcpy(my_string, "Prasad Divesd");
length = strlen(my_string);
printf("\nTo be sent: %s", my_string);
e = libusb_bulk_transfer(handle, BULK_EP_IN, my_string, length, &transferred, 0);
if(e == 0 && transferred == length)
{
printf("\nWrite successful!");
printf("\nSent %d bytes with string: %s\n", transferred, my_string);
}
else
printf("\nError in write! e = %d and transferred = %d\n", e, transferred);
sleep(3);
i = 0;
for(i = 0; i < length; i++)
{
e = libusb_bulk_transfer(handle, BULK_EP_OUT, my_string1, 64, &received, 0); //64: Max Packet Length
if(e == 0)
{
printf("\nReceived: ");
printf("%c", my_string1[i]); //Will read a string from LPC2148
sleep(1);
}
else
{
printf("\nError in read! e = %d and received = %d\n", e, received);
return -1;
}
}
e = libusb_release_interface(handle, 0);
libusb_close(handle);
libusb_exit(NULL);
printf("\n");
return 0;
}

Getting the MAC Address in Objective-C

How do I get the MAC address of the computer in Objective-C? I was using the following code but it started crashing once I switched to using the LLVM compiler. Can anyone tell me how to fix this code or give me new code that works? I found a way to do it in 10.6+, but I need it to work with 10.5 too.
void GetHWAddresses()
{
struct ifconf ifc;
struct ifreq *ifr;
int i, sockfd;
char buffer[BUFFERSIZE], *cp, *cplim;
char temp[80];
for (i=0; i<MAXADDRS; ++i)
{
hw_addrs[i] = NULL;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror("socket failed");
return;
}
ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;
if (ioctl(sockfd, SIOCGIFCONF, (char *)&ifc) < 0)
{
perror("ioctl error");
close(sockfd);
return;
}
ifr = ifc.ifc_req;
cplim = buffer + ifc.ifc_len;
for (cp=buffer; cp < cplim; )
{
ifr = (struct ifreq *)cp;
if (ifr->ifr_addr.sa_family == AF_LINK)
{
struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr;
int a,b,c,d,e,f;
int i;
strcpy(temp, (char *)ether_ntoa(LLADDR(sdl)));
sscanf(temp, "%x:%x:%x:%x:%x:%x", &a, &b, &c, &d, &e, &f);
sprintf(temp, "%02X:%02X:%02X:%02X:%02X:%02X",a,b,c,d,e,f);
for (i=0; i<MAXADDRS; ++i)
{
if ((if_names[i] != NULL) && (strcmp(ifr->ifr_name, if_names[i]) == 0))
{
if (hw_addrs[i] == NULL)
{
hw_addrs[i] = (char *)malloc(strlen(temp)+1);
strcpy(hw_addrs[i], temp);
break;
}
}
}
}
cp += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len);
}
close(sockfd);
}
Apple actually have some example code for getting the MAC address from the IO registry