Jamie Smith / Mbed OS CC1200-Examples

Dependencies:   CC1200

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SerialStream.h Source File

SerialStream.h

00001 #ifndef SERIALSTREAM_H
00002 #define SERIALSTREAM_H
00003 
00004 #include <mbed.h>
00005 #include <platform/Stream.h>
00006 
00007 /**
00008  * SerialStream
00009  * Bringing MBed serial ports back like it's 1999... or at least 2019.
00010  *
00011  * This class adapts an MBed 6.0 serial port class into a Stream instance.
00012  * This lets you do two useful things with it:
00013  * - Call printf() and scanf() on it
00014  * - Pass it to code that expects a Stream to print things on.
00015  *
00016  */
00017 template<class SerialClass>
00018 class SerialStream : public Stream
00019 {
00020     SerialClass & serialClass;
00021 
00022 public:
00023 
00024     /**
00025      * Create a SerialStream from a serial port.
00026      * @param _serialClass BufferedSerial or UnbufferedSerial instance
00027      * @param name The name of the stream associated with this serial port (optional)
00028      */
00029     SerialStream(SerialClass & _serialClass, const char *name = nullptr):
00030     Stream(name),
00031     serialClass(_serialClass)
00032     {
00033     }
00034 
00035 
00036 private:
00037 
00038     // override Stream::read() and write() to call serial class directly.
00039     // This avoids the overhead of feeding in individual characters.
00040     virtual ssize_t write(const void *buffer, size_t length)
00041     {
00042         return serialClass.write(buffer, length);
00043     }
00044 
00045     virtual ssize_t read(void *buffer, size_t length)
00046     {
00047         return serialClass.read(buffer, length);
00048     }
00049 
00050     // Dummy implementations -- these will never be called because we override write() and read() instead.
00051     // but we have to override them since they're pure virtual.
00052     virtual int _putc(int c) { return 0; }
00053     virtual int _getc() { return 0; }
00054 };
00055 
00056 #endif //SERIALSTREAM_H