How to use IOServiceOpenAsFileDescriptor? - c++

I have a USB device attached. I decided to try to write some code where I open the USB device as a FileDescriptor like on Linux where I can use ioctl function on the fd to send commands.
I ended up with the following:
CFMutableDictionaryRef matches = IOServiceMatching(kIOUSBDeviceClassName);
if (!matches)
{
std::cerr<<human_error_string(kIOReturnError)<<"\n";
return;
}
io_iterator_t deviceIterator;
kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matches, &deviceIterator);
if (kr != kIOReturnSuccess)
{
std::cerr<<human_error_string(kr)<<"\n";
return;
}
io_service_t service = IO_OBJECT_NULL;
while((service = IOIteratorNext(deviceIterator)))
{
int32_t fd = IOServiceOpenAsFileDescriptor(service, O_RDWR) //doesn't work! Returns: -1
IOObjectRelease(service);
}
IOObjectRelease(deviceIterator);
However, the FD is always -1.. Any ideas why?

As far as I'm aware, there isn't any kind of file descriptor based API for USB on macOS. You need to go through the IOUSB based APIs. There's some example code here.
If you want to share as much code as possible between Linux an macOS, you can use libusb which wraps both Apple's IOKit API and Linux's ioctl based USB API.
I have to admit I'm not exactly sure what IOServiceOpenAsFileDescriptor is intended for. The source code in IOKitLib is not terribly enlightening, as it simply connects to an XPC service and the file descriptor is expected in the XPC reply. I assume the service is implemented in a system daemon that isn't open source or documented.
Perhaps IOServiceOpenAsFileDescriptor is for accessing block devices or serial ports, which have both an IOKit object and a device node file in /dev/. General USB devices do not have a node in the file system.

Related

windows: detect same device on both bluetooth api and setupapi

I'm currently creating a program that's divided in two parts, one where I detect nearby bluetooth devices and connect them to the pc if the name match and the other where I search for the device with setupapi and get an handle for HID comunication.
My problem is that I cannot find anything that tells me that the device I just connected is the same I found in setupapi.
So in the first part I have something like this:
BLUETOOTH_DEVICE_INFO btdi;
//--- Code omitted ---
BluetoothGetDeviceInfo(radio_handle, &btdi);
if(std::wstring(btdi.szName) == /*my name*/)
// Device found! now connect
BluetoothSetServiceState(radio_handle, &btdi, &HumanInterfaceDeviceServiceClass_UUID, BLUETOOTH_SERVICE_ENABLE);
And the setupapi related code:
SP_DEVICE_INTERFACE_DATA device_data;
device_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
//--- Code omitted ---
SetupDiEnumDeviceInterfaces(device_infos, NULL, &hid_guid, index, &device_data);
I was thinking about using the bluetooth address of the device but there seem to be no way to get that from setupapi.
So, to recap, is there any way to get the address of the device from setupi? And, if not, is there any other way to be sure that they're both the same device?
Here I posted the code how to find Wiimote connected as HID using its MAC. You have to rework that code so it can use your HID device (change VID and PID).

How do I open a ttyMFD device on the Intel-Edison [C++]?

I have a /dev/ttyUSB device and a /dev/ttyMFD device that I need to stream to logfiles. For the USB device I could use termios and configure it through that. This was pretty straight forward and there was a bit of documentation for this as well.
I can't seem to find any for the MFD though. Some places call it a MultiFuctionDevice and others call it the Medfield High Speed UART device.
Which is correct in the first place?
And secondly, can I open it in the same way that I open up a regular ttyUSB device?
Here is the snippit I use to open USB devices.
int fd = open(USBDEVICE0, O_RDWR);
struct termios io;
memset(&io, 0, sizeof(io));
io.c_iflag = 0;
io.c_oflag = 0;
io.c_cflag = CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
io.c_lflag = 0;
// TODO -- Since we are operating in non-blocking mode; confirm VMIN and VTIME settings have no effect on duration of the read() call.
io.c_cc[VMIN] = 1;
io.c_cc[VTIME] = 5;
speed_t speedSymbol = B921600;
cfsetospeed(&io, speedSymbol);
cfsetispeed(&io, speedSymbol);
int retVal;
retVal = tcsetattr(fd, TCSANOW, &io);
tcflush(fd, TCIOFLUSH);
usleep(100);
EDIT
For anyone who comes across this, there is one caveat. You must open the device in raw mode and dump everything into a log file. Parsing must be done post. Everything will come out as raw data but if you try to do any kind of configuration, the devices buffer will not be able to capture all the data, hold it, and process it in time before more data comes along.
MFD in Linux kernel is common abbreviation to Multi-Functional Device, Legacy serial driver for Edison abuses that and uses it's own interpretation as you mentioned: Medfield. In the upstream kernel the abbreviation MID is used regarding to Mobile Internet Device. In particular the serial driver is called drivers/tty/serial/8250_mid.c. See https://en.wikipedia.org/wiki/Mobile_Internet_device.
Yes, you may do the same operations as you did on top of /dev/ttyUSBx.

How to enumerate an USB hub that is attached to the first port of root hub on Windows Embedded 7

I am posting here for the first time, I hope this will be clear and readable.
I am currently trying to test the presence of usb devices on an embedded system using a specific HCD and port path programmatically using C++ and Visual Studio 2008.
The idea is to pass in the port number and the hcd value as the parameters of the function, and the function will return a true or false that indicates the connection status.
I have written some code to populate the root hub and prove that the device attached to port 1 of the root hub is a hub using bool DeviceIsHub from usbioctl.h.
However, when I attempt to enumerate the usb hub attached to port 1 of root so that I may test for the connection status of the downstream ports for the presence of device(ports 1 and 2 of this usb hub). It does not seem to know how many downstream ports the usb hub has.
I checked USBVIEW/TreeView, both application tells me that devices are there
but I am not sure what ioctl command code to use such that I can enumerate the downstream ports so I can check the connection status.
The structure of the device based on USB view and USB tree provides the following.
Root hub - it has 7 ports, only the first port is being used.
A USB hub (it has four available ports) is attached to the first port of the root hub.
Two USB devices (USB mouse and USB keyboard) are attached to port 1 and port 2 of the USB hub.
I have tried IOCTL_USB_GET_CONNECTION_INFORMATION, IOCTL_USB_GET_CONNECTION_NAME,
IOCTL_USB_GET_CONNECTION_INFORMATION_EX, IOCTL_USB_PORT_CONNECTOR_PROPERTIES
(which is not supported, it can only be used in windows 8, this is the exact ioctl call they used to enumerate the ports).
Please ignore the MessageBoxes, those are for me to check the control path status and determine which route it was following.
Please find the code that I wrote as I attempt to enumerate/populate the usb hub. I did not include the Root hub code because it would make this snippet too big.
My questions mainly resides in the enumeration process of the secondary USB hub I believe.
I just checked the registry key of the device. it appears that the USB hub is enumerated and present on the device since the information is shown under regedit HKLM->System->CurrentControlSet->Enum->USB. I believe I am not enumerating it correctly within my test application.
Any help would be greatly appreciated.
Update
The part that I am most concerned about is the DeviceIoControl Calls that attempts to get the size and the actual name of that USB hub.
It currently only takes in USB_GET_NODE_INFORMATION. Any other ioctl calls that are intended to retrieve the name of the hub will fail at the first DeviceIoControl where it attempts to get the size of the hub name so that it know how much memory to allocate
for it.
Update Part 2
From observing the usbview open source code, I believe I need to enumerate the host controller and all the devices first before checking for the presence of device. I drew a conclusion such that without doing the enumeration of controller, it only goes so far down the tree (at best second layer, which is where the external hub is attached to in my case).
I am currently attempting to enumerate the other devices and controllers in hope that I can get to the third layer of device. I will keep on updating this thread until either I figure out the problem myself or someone is capable of answering my questions.
//we are connected to the external hub, now we can begin the configuration and enumeration of the external hub.
ULONG kBytes = 0;
USB_HUB_NAME SubHubName;
//Create a Handle for the external hub driver
char Name[16];
wsprintf(Name, "\\\\.\\HCD%d", HcdSub);
HANDLE SubHub = CreateFile(Name,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
//Check to see if the handle was created successfully
if (SubHub == INVALID_HANDLE_VALUE)
{
MessageBox(NULL,"SubHandle Fail ","TEST",MB_OK);
return false;
}
//Query the SUBHUB/External Hub for the structure, this will tell us the number of down stream ports we need to enumerate
ioctlSuccess = DeviceIoControl(SubHub,
IOCTL_USB_GET_NODE_INFORMATION,
0,
0,
&SubHubName,
sizeof(SubHubName),
&kBytes,
NULL);
//If the command failed, close the handle and return false.
if(!ioctlSuccess)
{
CloseHandle(SubHub);
MessageBox(NULL," sub hub size fail ","TEST",MB_OK);
return false;
}
//Prepare to receive the SubHubName
kBytes = SubHubName.ActualLength;
USB_HUB_NAME *subHubNameW = (USB_HUB_NAME *) malloc(sizeof(USB_HUB_NAME) * kBytes);
//Check if the allocation failed, if it did, free the memory allocated and return false.
if (subHubNameW == NULL)
{
free(subHubNameW);
CloseHandle(SubHub);
MessageBox(NULL,"SUBHubNameW=NULL ","TEST",MB_OK);
return false;
}
//Send the command to retrieve the name
ioctlSuccess = DeviceIoControl(SubHub,
IOCTL_USB_GET_NODE_INFORMATION,
NULL,
0,
subHubNameW,
kBytes,
&kBytes,
NULL);
//We no longer need this handle.
CloseHandle(SubHub);
if(!ioctlSuccess)
{
if(subHubNameW !=NULL)
{
free(subHubNameW);
}
MessageBox(NULL,"GET NODE INFO FAIL ","TEST",MB_OK);
return false;
}
//Converts the SubHubNAme from widechar to a cahr.
MessageBox(NULL,"BEGIN CONVERTION","TEST",MB_OK);
kBytes = wcslen(subHubNameW->HubName) + 1;
char *subhubname = (char *) malloc(sizeof(char)*kBytes);
wcstombs(subhubname,subHubNameW->HubName, kBytes);
//we no longer need subHubNameW the information is now in subhubname.
if(subHubNameW !=NULL)
{
free(subHubNameW);
}
//Attempt to open a handle to driver for sub hub.
int SubhdnSize = strlen(subhubname) + sizeof("\\\\.\\");
char *subhubnamelength = (char *) malloc(sizeof(char) * SubhdnSize);
sprintf(subhubnamelength, "\\\\.\\%s", subhubname);
//We no longer need subhubname, so free it.
if(subhubname !=NULL) free(subhubname);
//Attempt to open a handle for enumerating ports on this hub.
HANDLE ExternalHub = CreateFile(subhubnamelength,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
//we no longer need subhubnamelength, so free it if it is not NULL
if(subhubnamelength != NULL) free(subhubnamelength);
//Check and see if the handle was created successfully, if not, return false.
if(ExternalHub == INVALID_HANDLE_VALUE)
{
CloseHandle(ExternalHub);
MessageBox(NULL,"EXT handle fail ","TEST",MB_OK);
return false;
}
}
USB_NODE_CONNECTION_ATTRIBUTES *PortConnection =
(USB_NODE_CONNECTION_ATTRIBUTES *) malloc(sizeof(USB_NODE_CONNECTION_ATTRIBUTES));
PortConnection ->ConnectionIndex = Port;
ioctlSuccess = DeviceIoControl(ExternalHub,
IOCTL_USB_GET_NODE_CONNECTION_ATTRIBUTES,
PortConnection,
sizeof(USB_NODE_CONNECTION_ATTRIBUTES),
PortConnection,
sizeof(USB_NODE_CONNECTION_ATTRIBUTES),
&kBytes,
NULL);
if(!ioctlSuccess)
{
MessageBox(NULL,"DEVICE CONNECTION FAIL ","TEST",MB_OK);
return false;
}
if(PortConnection->ConnectionStatus !=DeviceConnected)
{
printf("The Connection Status Returns: %d",PortConnection->ConnectionStatus);
printf("\n");
return false;
}
Enumerating USB on Windows 7 will fail if UAC is enabled and application doesn't have enough privilege. Windows Embedded 7 may fail also on similar task.
There is also a possibility to enumerate through registry.
You can not enumerate anything possibly. Normally the usb device is either a bus device or a child of a bus device. Sense the bus device is not removable, it is automatically enumerated by acpi.sys the root device during boot, or if a bus device for some other device attached to the root node, then that device has to undergo some event that means it detects the device and then enumerates it, plug and play will automatically look for it's device type's driver and if installed will load it. If the usb say has 4 actual usb connectors, that are controlled from a central device, there could be a usb driver/mini driver pair. In that case the miniport driver is a child of the usb driver and is enumerated by it and attached to it. The miniport's job is to know the actual hardware, and irp's and all other io will come from it's parent. If there are several physical connections there may be additional child drivers. They all operate the hardware and there is a hot plug. When the firmware detects the installation of a usb device it communicates this to the miniport driver and on down the stack to the bus and ultimately it is processed by plug and play. Plug and play will then have the miniport driver enumerate it's device, but it needs to get a hardware id. Then it can find it's driver and load that, then the device is installed and ready for operation.
With out knowing the device stack it is not clear what device it is referring to. Keep in mind the driver stack may not reflect the actual hardware topology. There are also things called logical devices which do not represent any piece of hardware. Any of these would have to be taken into account and you need to know which device corresponds to the end of the node.
Also one little detail. I'm not as familiar with user mode api's and drivers as I am kernel, but it seems wsprintf second argument controls format of the output buffer from the input. It should be %[]%[] were [] is a symbol that represents the format. It would format the first character according to the first symbol then the second character with teh second symbol. Seems you are doing something different.
A final note, it appears the use of wsprintf() is now deprecated instead for other api's.

Blocking Serial Port Read

I have to read many(8) serial devices on my project. They are Pantilt, Camera, GPS, Compass etc. they all are RS232 devices but they have different command structure and behavior. e.g GPS starts sending data as
soon as I open the port. where as PanTilt and Camera only responds when I send specific commands to them.
I use following environment
OS: Ubuntu 11.10
Language: C++
Framework: Qt 4.7
For PanTilt and Camera I want to develop function like this.
int SendCommand(string& command, string& response)
{
port.write(command, strlen(command));
while(1)
{
if(response contains '\n') break;
port.read(response) // Blocking Read
}
return num_of_bytes_read;
}
I want to implement this way as this function will be used as building block for more complex algorithm
like this...
SendCoammd("GET PAN ANGLE", &angle);
if(angle > 60)
SendCommand("STOP PAN", &stopped?);
if(stopped? == true)
SendCommand("REVERSE PAN DIRECTION", &revesed?);
if(reversed? == true)
SendCommand("START PAN", &ok);
To do something like this I need strict synchronous behavior. Anybody has any idea how to approach this?
I found this tutorial very intresting and helpful.
http://www.webalice.it/fede.tft/serial_port/serial_port.html
It shows how boost::asio can be used to perform both sync and async read/write.
Thank You for the help!
what is the problem of using standard file API?
fd = open("/dev/ttyX");
write(fd, command.cstr(), command.size());
vector v(MAX_SIZE);
read(fd,&v[0], MAX_SIZE);
Low-level communication with serial port in Qt can be established with QExtSerialPort library that partially implements QIODevice interface.
The high level protocols you have to implement yourself.

How do I receive raw, layer 2 packets in C/C++?

How do I receive layer 2 packets in POSIXy C++? The packets only have src and dst MAC address, type/length, and custom formatted data. They're not TCP or UDP or IP or IGMP or ARP or whatever - they're a home-brewed format given unto me by the Hardware guys.
My socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW) never returns from its recvfrom().
I can send fine, I just can't receive no matter what options I fling at the network stack.
(Platform is VxWorks, but I can translate POSIX or Linux or whatever...)
receive code (current incarnation):
int s;
if ((s = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) < 0) {
printf("socket create error.");
return -1;
}
struct ifreq _ifr;
strncpy(_ifr.ifr_name, "lltemac0", strlen("lltemac0"));
ioctl(s, IP_SIOCGIFINDEX, &_ifr);
struct sockaddr_ll _sockAttrib;
memset(&_sockAttrib, 0, sizeof(_sockAttrib));
_sockAttrib.sll_len = sizeof(_sockAttrib);
_sockAttrib.sll_family = AF_PACKET;
_sockAttrib.sll_protocol = IFT_ETHER;
_sockAttrib.sll_ifindex = _ifr.ifr_ifindex;
_sockAttrib.sll_hatype = 0xFFFF;
_sockAttrib.sll_pkttype = PACKET_HOST;
_sockAttrib.sll_halen = 6;
_sockAttrib.sll_addr[0] = 0x00;
_sockAttrib.sll_addr[1] = 0x02;
_sockAttrib.sll_addr[2] = 0x03;
_sockAttrib.sll_addr[3] = 0x12;
_sockAttrib.sll_addr[4] = 0x34;
_sockAttrib.sll_addr[5] = 0x56;
int _sockAttribLen = sizeof(_sockAttrib);
char packet[64];
memset(packet, 0, sizeof(packet));
if (recvfrom(s, (char *)packet, sizeof(packet), 0,
(struct sockaddr *)&_sockAttrib, &_sockAttribLen) < 0)
{
printf("packet receive error.");
}
// code never reaches here
I think the way to do this is to write your own Network Service that binds to the MUX layer in the VxWorks network stack. This is reasonably well documented in the VxWorks Network Programmer's Guide and something I have done a number of times.
A custom Network Service can be configured to see all layer 2 packets received on a network interface using the MUX_PROTO_SNARF service type, which is how Wind River's own WDB protocol works, or packets with a specific protocol type.
It is also possible to add a socket interface to your custom Network Service by writing a custom socket back-end that sits between the Network Service and the socket API. This is not required if you are happy to do the application processing in the Network Service.
You haven't said which version of VxWorks you are using but I think the above holds for VxWorks 5.5.x and 6.x
Have you tried setting the socket protocol to htons(ETH_P_ALL) as prescribed in packet(7)? What you're doing doesn't have much to do with IP (although IPPROTO_RAW may be some wildcard value, dunno)
I think this is going to be a bit tougher problem to solve than you expect. Given that it's not IP at all (or apparently any other protocol anything will recognize), I don't think you'll be able to solve your problem(s) entirely with user-level code. On Linux, I think you'd need to write your own device agnostic interface driver (probably using NAPI). Getting it to work under VxWorks will almost certainly be non-trivial (more like a complete rewrite from the ground-up than what most people would think of as a port).
Have you tried confirming via Wireshark that a packet has actually been sent from the other end?
Also, for debugging, ask your hardware guys if they have a debug pin (you can attach to a logic analyzer) that they can assert when it receives a packet. Just to make sure that the hardware is getting the packets fine.
First you need to specify the protocol as ETH_P_ALL so that your interface gets all the packet. Set your socket to be on promiscuous mode. Then bind your RAW socket to an interface before you perform a receive.