NMEA2000 Library  0.1
Library to handle NMEA 2000 Communication written in C++
N2kStream.cpp
Go to the documentation of this file.
1/*
2N2kStream.cpp
3
4Copyright (c) 2015-2024 Timo Lappalainen, Kave Oy, www.kave.fi
5
6Permission is hereby granted, free of charge, to any person obtaining a copy of
7this software and associated documentation files (the "Software"), to deal in
8the Software without restriction, including without limitation the rights to use,
9copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
10Software, and to permit persons to whom the Software is furnished to do so,
11subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
17INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
18PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
20CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
21OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
23I/O stream used in the NMEA2000 libraries.
24
25*/
26#include "N2kStream.h"
27#include <string.h>
28
29#ifdef ARDUINO
30// Arduino uses its own implementation.
31#else
32size_t N2kStream::print(const char *str) {
33 if(str == 0)
34 return 0;
35
36 return write(reinterpret_cast<const uint8_t*>(str), strlen(str));
37}
38
39#if defined(__AVR__)
40size_t N2kStream::print(const __FlashStringHelper* str) {
41 size_t bytes_written = 0;
42 PGM_P src = (PGM_P) str;
43 for(uint8_t c = pgm_read_byte(src); c != 0; ++src, ++bytes_written)
44 write(&c, 1);
45
46 return bytes_written;
47}
48
49size_t N2kStream::print(const __FlashStringHelper* str) {
50 return print(str) + print("\r\n");
51}
52#endif
53
54
55size_t N2kStream::print(int val, uint8_t radix) {
56
57 if(val == 0) {
58 // 0 is always 0 regardless of radix.
59 return write(reinterpret_cast<const uint8_t*>("0"), 1);
60 }
61
62 // Enough for binary representation.
63 char buf[8 * sizeof(val) + 1];
64 char *ptr = &buf[sizeof(buf) - 1];
65 *ptr = '\0';
66
67 do {
68 *--ptr="0123456789abcdef"[val % radix];
69 val /= radix;
70 } while(val != 0);
71
72 return print(ptr);
73}
74
75size_t N2kStream::println(const char *str) {
76 return print(str) + print("\r\n");
77}
78
79size_t N2kStream::println(int val, uint8_t radix) {
80 return print(val, radix) + print("\r\n");
81}
82
83#endif
#define pgm_read_byte(var)
Definition: N2kDef.h:46
This File contains an I/O stream used in the NMEA2000 libraries.
size_t print(const char *str)
Print string to stream.
Definition: N2kStream.cpp:32
virtual size_t write(const uint8_t *data, size_t size)=0
Write data to stream.
size_t println(const char *str)
Print string and newline to stream.
Definition: N2kStream.cpp:75