#import "serial_io.h" int SerialDevice::numSerialPorts=0; static char msg[256]; static char bsdPaths[MAX_NUM_SERIAL_PORTS][MAXPATHLEN]; static io_iterator_t serialPortIterator; static kern_return_t FindSerialPorts(); static kern_return_t GetSerialPortPaths(); kern_return_t FindSerialPorts(){ kern_return_t kernResult; mach_port_t masterPort; CFMutableDictionaryRef classesToMatch; /*! @function IOMasterPort @abstract Returns the mach port used to initiate communication with IOKit. @discussion Functions that don't specify an existing object require the IOKit master port to be passed. This function obtains that port. @param bootstrapPort Pass MACH_PORT_NULL for the default. @param masterPort The master port is returned. @result A kern_return_t error code. */ kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort); if (KERN_SUCCESS != kernResult){ sprintf(msg,"IOMasterPort returned %d\n", kernResult); Print::outMsg(msg,SERIAL_MSG); } /*! @function IOServiceMatching @abstract Create a matching dictionary that specifies an IOService class match. @discussion A very common matching criteria for IOService is based on its class. IOServiceMatching will create a matching dictionary that specifies any IOService of a class, or its subclasses. The class is specified by C-string name. @param name The class name, as a const C-string. Class matching is successful on IOService's of this class or any subclass. @result The matching dictionary created, is returned on success, or zero on failure. The dictionary is commonly passed to IOServiceGetMatchingServices or IOServiceAddNotification which will consume a reference, otherwise it should be released with CFRelease by the caller. */ // Serial devices are instances of class IOSerialBSDClient classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue); if (classesToMatch == NULL){ sprintf(msg,"IOServiceMatching returned a NULL dictionary.\n"); Print::outMsg(msg,SERIAL_MSG); } else { /*! @function CFDictionarySetValue Sets the value of the key in the dictionary. @param theDict The dictionary to which the value is to be set. If this parameter is not a valid mutable CFDictionary, the behavior is undefined. If the dictionary is a fixed-capacity dictionary and it is full before this operation, and the key does not exist in the dictionary, the behavior is undefined. @param key The key of the value to set into the dictionary. If a key which matches this key is already present in the dictionary, only the value is changed ("add if absent, replace if present"). If no key matches the given key, the key-value pair is added to the dictionary. If added, the key is retained by the dictionary, using the retain callback provided when the dictionary was created. If the key is not of the sort expected by the key retain callback, the behavior is undefined. @param value The value to add to or replace into the dictionary. The value is retained by the dictionary using the retain callback provided when the dictionary was created, and the previous value if any is released. If the value is not of the sort expected by the retain or release callbacks, the behavior is undefined. */ // CFDictionarySetValue(classesToMatch, // CFSTR(kIOSerialBSDTypeKey), // CFSTR(kIOSerialBSDserialType)); CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDRS232Type)); // Each serial device object has a property with key // kIOSerialBSDTypeKey and a value that is one of kIOSerialBSDAllTypes, // kIOSerialBSDserialType, or kIOSerialBSDRS232Type. You can experiment with the // matching by changing the last parameter in the above call to CFDictionarySetValue. // As shipped, this sample is only interested in serials, // so add this property to the CFDictionary we're matching on. // This will find devices that advertise themselves as serials, // such as built-in and USB serials. However, this match won't find serial serials. } /*! @function IOServiceGetMatchingServices @abstract Look up registered IOService objects that match a matching dictionary. @discussion This is the preferred method of finding IOService objects currently registered by IOKit. IOServiceAddNotification can also supply this information and install a notification of new IOServices. The matching information used in the matching dictionary may vary depending on the class of service being looked up. @param masterPort The master port obtained from IOMasterPort(). @param matching A CF dictionary containing matching information, of which one reference is consumed by this function. IOKitLib can contruct matching dictionaries for common criteria with helper functions such as IOServiceMatching, IOOpenFirmwarePathMatching. @param existing An iterator handle is returned on success, and should be released by the caller when the iteration is finished. @result A kern_return_t error code. */ kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, &serialPortIterator); if (KERN_SUCCESS != kernResult){ sprintf(msg,"IOServiceGetMatchingServices returned %d\n", kernResult); Print::outMsg(msg,SERIAL_MSG); } return kernResult; } kern_return_t GetSerialPortPaths(){ io_object_t serialService; kern_return_t kernResult = KERN_FAILURE; // Initialize the returned path /*! @function IOIteratorNext @abstract Returns the next object in an iteration. @discussion This function returns the next object in an iteration, or zero if no more remain or the iterator is invalid. @param iterator An IOKit iterator handle. @result If the iterator handle is valid, the next element in the iteration is returned, otherwise zero is returned. The element should be released by the caller when it is finished. */ int i=0; while (serialService = IOIteratorNext(serialPortIterator)) { CFTypeRef serialNameAsCFString; CFTypeRef bsdPathAsCFString; *bsdPaths[i] = '\0'; /*! @function IORegistryEntryCreateCFProperty @abstract Create a CF representation of a registry entry's property. @discussion This function creates an instantaneous snapshot of a registry entry property, creating a CF container analogue in the caller's task. Not every object available in the kernel is represented as a CF container; currently OSDictionary, OSArray, OSSet, OSSymbol, OSString, OSData, OSNumber, OSBoolean are created as their CF counterparts. @param entry The registry entry handle whose property to copy. @param key A CFString specifying the property name. @param allocator The CF allocator to use when creating the CF container. @param options No options are currently defined. @result A CF container is created and returned the caller on success. The caller should release with CFRelease. */ serialNameAsCFString = IORegistryEntryCreateCFProperty(serialService, CFSTR(kIOTTYDeviceKey), kCFAllocatorDefault, 0); if (serialNameAsCFString) { char serialName[128]; Boolean result; result = CFStringGetCString(serialNameAsCFString, serialName, sizeof(serialName), kCFStringEncodingASCII); CFRelease(serialNameAsCFString); if (result) { sprintf(msg,"Serial stream name: %s, ", serialName); Print::outMsg(msg,SERIAL_MSG); kernResult = KERN_SUCCESS; } } bsdPathAsCFString = IORegistryEntryCreateCFProperty(serialService, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0); if (bsdPathAsCFString) { Boolean result; result = CFStringGetCString(bsdPathAsCFString, bsdPaths[i], MAXPATHLEN, kCFStringEncodingASCII); CFRelease(bsdPathAsCFString); if (result){ sprintf(msg,"BSD path: %s", bsdPaths[i]); Print::outMsg(msg,SERIAL_MSG); i++; } } sprintf(msg,"\n"); Print::outMsg(msg,SERIAL_MSG); /*! @function IOObjectRelease @abstract Releases an object handle previously returned by IOKitLib. @discussion All objects returned by IOKitLib should be released with this function when access to them is no longer needed. Using the object after it has been released may or may not return an error, depending on how many references the task has to the same object in the kernel. @param object The IOKit object to release. @result A kern_return_t error code. */ (void) IOObjectRelease(serialService); // We have sucked this service dry of information so release it now. } SerialDevice::numSerialPorts=i; return kernResult; } kern_return_t SerialDevice::InitializeSerialPorts(){ kern_return_t kernResult; // on PowerPC this is an int (4 bytes) kernResult = FindSerialPorts(); if (KERN_SUCCESS != kernResult){ sprintf(msg,"FindSerialPorts returned %d\n", kernResult); Print::outMsg(msg,SERIAL_MSG); return kernResult; } kernResult =GetSerialPortPaths(); if (KERN_SUCCESS != kernResult){ sprintf(msg,"GetSerialPortPaths returned %d\n", kernResult); Print::outMsg(msg,SERIAL_MSG); } return kernResult; } // Given the path to a serial device, open the device and configure it. // Return the file descriptor associated with the device. int SerialDevice::Open(int port, int baud) { fileDescriptor = -1; struct termios options; bsdPath=bsdPaths[port]; // fileDescriptor = open(bsdPath, O_RDWR); fileDescriptor = open(bsdPath, O_RDWR | O_NOCTTY | O_NDELAY); if (fileDescriptor == -1) { sprintf(msg,"Error opening serial port %s - %s(%d).\n", bsdPath, strerror(errno), errno); Print::outMsg(msg,SERIAL_MSG); goto error; } if (fcntl(fileDescriptor, F_SETFL, 0) == -1) { sprintf(msg,"Error clearing O_NDELAY %s - %s(%d).\n", bsdPath, strerror(errno), errno); Print::outMsg(msg,SERIAL_MSG); goto error; } // Get the current options and save them for later reset if (tcgetattr(fileDescriptor, &gOriginalTTYAttrs) == -1) { sprintf(msg,"Error getting tty attributes %s - %s(%d).\n", bsdPath, strerror(errno), errno); Print::outMsg(msg,SERIAL_MSG); goto error; } // Set raw input, one second timeout // These options are documented in the man page for termios // (in Terminal enter: man termios) // options = gOriginalTTYAttrs; //make raw options.c_cflag=0; options.c_lflag=0; options.c_iflag=0; options.c_oflag=0; options.c_cflag = CS8|CLOCAL|baud; // cfmakeraw(&options); // options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag &= ~CRTSCTS; options.c_cflag |= CS8; options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); options.c_oflag &= ~OPOST; /* XON/XOFF flow control, ignore CR, ignore parity */ // options.c_iflag = IXON|IGNBRK|IGNCR|IGNPAR; options.c_cc[ VMIN ] = 0; options.c_cc[ VTIME ] = 10; // options.c_iflag &=~(IXON | IXOFF | IXANY); // cfsetispeed(&options,baud); // cfsetospeed(&options,baud); cfsetspeed(&options,baud); if(cfgetispeed(&options)!=baud){ sprintf(msg,"Error setting input baud rate\n"); Print::outMsg(msg,SERIAL_MSG); } if(cfgetospeed(&options)!=baud){ sprintf(msg,"Error setting output baud rate\n"); Print::outMsg(msg,SERIAL_MSG); } // Set the options if (tcsetattr(fileDescriptor, TCSANOW, &options) == -1) { sprintf(msg,"Error setting tty attributes %s - %s(%d).\n", bsdPath, strerror(errno), errno); Print::outMsg(msg,SERIAL_MSG); goto error; } //flush tcflush(fileDescriptor,TCIOFLUSH); // Success sprintf(msg,"Opened serial port %s with baudrate %d\n",bsdPath,baud); Print::outMsg(msg,SERIAL_MSG); return fileDescriptor; // Failure path error: if (fileDescriptor != -1) close(fileDescriptor); return -1; } int SerialDevice::readBytes(void *data,long unsigned int numBytes){ ssize_t num; // Number of bytes read char buffer[1000]; num = read(fileDescriptor,buffer, numBytes); if (num == -1){ sprintf(msg,"Error reading from serial port %s - %s(%d).\n",bsdPath, strerror(errno), errno); Print::outMsg(msg,SERIAL_MSG); return num; } buffer[num]='\0'; memcpy(data,buffer,num+1); return num; } int SerialDevice::writeBytes(void *data,unsigned int numBytes){ ssize_t num; // Number of bytes written num = write(fileDescriptor, data, numBytes); if (num == -1){ sprintf(msg,"Error writing to serial port %s - %s(%d).\n",bsdPath, strerror(errno), errno); Print::outMsg(msg,SERIAL_MSG); } return num; } SerialDevice::SerialDevice(){ } SerialDevice::~SerialDevice(){ // Traditionally it is good to reset a serial port back to // the state in which you found it. Let's continue that tradition. if (tcsetattr(fileDescriptor, TCSANOW, &gOriginalTTYAttrs) == -1) { sprintf(msg,"Error resetting tty attributes - %s(%d).\n", strerror(errno), errno); Print::outMsg(msg,SERIAL_MSG); } close(fileDescriptor); }