Here we will show how to use the IO framework to read and write asynchronously from devices.
Assume the operations are performed inside a service named IOService
.
To create a device handle for the device /dev/motors
with an expected receive byte rate of 100 bytes we do:
CountedPtr<DeviceHandle> device_= IOManager::getInstance()->createDevice("/dev/motors", // the device we want to operate getActiveObject(), // the active object in which IOService is running CountedPtr<DeviceConfigurator>(new DeviceConfigurator), // the standard device configurator 100)) // the expected receive byte rate
Now we have an handle to the device on which we operate to execute read and write operations.
To read from the device we have to create an handler where we will receive the data read from device.
void IOService::readHandler(size_t bytesRead, size_t requestedBytes, const char* data, bool success) { // // process the reply here // }
The values received in this handler are:
bytesRead:
The number of bytes read.requestedBytes:
The number of bytes requested to be read.data:
The data which was read from the device.success:
A boolean flag which tells if the operation was successful. True if it was, False if it wasn't.Then do:
device_->enableRead(CountedPtr<StreamOperationHandlerMethodBase>(new StreamOperationHandlerMethod<IOService>(this, &IOService::readHandler)));
As soon as we enable read operations in the device, we will receive data from it (if there is data available) in chunks of 100
bytes (the value we chose during device creation) or less (in case there are less than 100 bytes available). You can later modify the handler by calling the enableRead
method again.
To write to the device we have to create an handler where we'll receive replies telling us whether that operation was successful or not (as occurs with read operations).
void IOService::writeHandler(size_t bytesWritten, size_t requestedBytes, const char* data, bool success) { // // process reply here // }
The values received in the handler are:
bytesWritten:
Number of bytes writtenrequestedBytes:
The number of bytes requested to be writtendata:
The data which was written to the device.success:
A boolean flag which tells if the operation was successful. True if it was, False if it wasn't.Each time you write to a device you have to state which handler will receive the write reply.
char* data = "Data to be sent to the device"; device_->write(data, strlen(data), CountedPtr<StreamOperationHandlerMethodBase>(new StreamOperationHandlerMethod<IOService>(this, &IOService::writeHandler)));
Note: We just know the data was definitely written the moment we receive a reply acknowledging that operation (and success
flag is true).
To close the device you can do (explicitly):
device_->close()
or you can let the DeviceHandle
be destroyed (destructor called) by normal rules of C++.