I3MUP1+Exercise+10

toc =Exercise 10: GenericDevice= //Create a common class that://
 * //Abstracts access to file IO to devices, this means that it wraps the//
 * //Open, close, read and write Posix functions//

//The abstracted class can be inherited to concrete devices such as,// //ADC, DAC, GPIO etc. Custom initialization, read-/write access can be// //Implemented in daughter classes.//

Nedenfor ses den implementerede GenericDevice. Kommentare til koden kan findes i kodeblokken.

code format="cpp" // The constructor is called by setting the appropriate filename and the method of which you wish to open the device. GenericDevice::GenericDevice(std::string fileName, OpenMethod parameters) {   this->fileName = fileName; this->parameters = parameters; }

// If the destructor is called, the device and file object is closed. GenericDevice::~GenericDevice {   closeDevice; fileDescriptor.close; }

void GenericDevice::writeDevice {   char writeValue[8]; // sprintf writes into the array pointed by writeValue consisting of a sequence of data. sprintf(writeValue, "%i", value); // write writes the block of data pointed to by writeValue. fileDescriptor.write(writeValue, sizeof(writeValue)); }

void GenericDevice::closeDevice {   // Closes the file associated with the object. fileDescriptor.close; }

int GenericDevice::getValue {   return value; }

void GenericDevice::setValue(int value) {   this->value = value; }

bool GenericDevice::openDevice {   // The nodes are found in /dev/ std::string nodePath = "/dev/" + fileName;

// Opens the file in the mode appointed by 'parameters'. fileDescriptor.open(nodePath.c_str, translateEnum(parameters));

if (!fileDescriptor.is_open) {       printf("Failed to open %s\n", nodePath.c_str); return false; }   return true; }

void GenericDevice::readDevice {

char readValue[13]; fileDescriptor.read(readValue, sizeof(readValue)); // Reads the data from readValue and outputs it   sscanf(readValue, "%i", &value); }

// This method translated the enum into the appropriate fstream mode. std::_Ios_Openmode GenericDevice::translateEnum(OpenMethod openMethod) {   if (openMethod == READ) return std::fstream::in; else if (openMethod == WRITE) return std::fstream::out; else if (openMethod == READWRITE) return (std::fstream::in | std::fstream::out); else return std::fstream::in; // if all else fails, at least make sure they dont ruin anything! } code