IO framework tutorial

Introduction

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.

Creating a device

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.

Reading from the device

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:

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.

Writing to the device

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:

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).

Closing the device

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++.

Generated on Fri Mar 4 22:15:37 2011 for MeRMaID::support by  doxygen 1.6.3