M5Unit-RS485 0.2.0 git rev:0956c20
Loading...
Searching...
No Matches
rs485_component.hpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD
3 *
4 * SPDX-License-Identifier: MIT
5 */
18#ifndef M5_UNIT_RS485_RS485_COMPONENT_HPP
19#define M5_UNIT_RS485_RS485_COMPONENT_HPP
20
21#include <M5UnitComponent.hpp>
22#include <m5_utility/stl/byteswap.hpp>
23#include <m5_utility/stl/endianness.hpp>
24#include <cstring>
25#include <memory>
26#include <type_traits>
27
28namespace m5 {
29namespace unit {
30
31class AdapterUART; // forward decl: framework-agnostic UART adapter
32
37class RS485Component : public Component {
38public:
40 struct ISerial {
41 virtual ~ISerial() = default;
42 virtual int available() = 0;
43 virtual int availableForWrite() = 0;
44 virtual int peek() = 0;
45 virtual int read() = 0;
46 virtual size_t read(uint8_t *buf, const size_t len) = 0;
47 virtual size_t readBytes(uint8_t *buf, const size_t len) = 0;
48 /*
49 Read with an explicit timeout instead of the backend's sticky timeout state. Required by
50 the ESP-IDF backend, where uart_read_bytes() takes ticks_to_wait as an argument and there
51 is no HardwareSerial object holding a timeout to inherit.
52 */
53 virtual size_t readBytes(uint8_t *buf, const size_t len, const uint32_t timeout_ms) = 0;
54 virtual void flush() = 0;
55 virtual void flush(const bool txOnly) = 0;
56 virtual size_t write(const uint8_t *buf, const size_t len) = 0;
57 virtual size_t write(const uint8_t b) = 0;
58 virtual uint32_t baudRate() const = 0;
59 // Called on the backend when its owning component has been moved. A backend that holds a
60 // pointer back to its owner (see UnitSIT3088) overrides this to follow the move; one that
61 // does not needs no implementation, which is why this is not pure. It runs inside the
62 // component's noexcept move, hence noexcept: an override may only store the pointer, not
63 // act on the owner, which is not fully constructed yet when a move constructor calls this.
64 virtual void rebind(RS485Component *owner) noexcept
65 {
66 (void)owner;
67 }
68 };
70
72 virtual ~RS485Component() = default;
73
78 RS485Component(const RS485Component &) = delete;
80
87
92 virtual bool begin() override;
93
98 struct config_t {
99 bool flushRX{true};
100 };
101
104
108 inline config_t config() const
109 {
110 return _cfg;
111 }
116 inline void config(const config_t &cfg)
117 {
118 _cfg = cfg;
119 }
121
129 inline operator bool() const
130 {
131 return isRegistered();
132 }
140 inline uint32_t baudRate() const
141 {
142 return _serial->baudRate();
143 }
148 inline int available()
149 {
150 return _serial->available();
151 }
156 inline int availableForWrite()
157 {
158 return _serial->availableForWrite();
159 }
164 inline int peek()
165 {
166 return _serial->peek();
167 }
172 inline int read()
173 {
174 return _serial->read();
175 }
182 inline size_t read(uint8_t *buffer, const size_t size)
183 {
184 return _serial->read(buffer, size);
185 }
192 inline size_t read(char *buffer, const size_t size)
193 {
194 return read(reinterpret_cast<uint8_t *>(buffer), size);
195 }
202 size_t readBytes(uint8_t *buffer, const size_t length)
203 {
204 return _serial->readBytes(buffer, length);
205 }
212 inline size_t readBytes(char *buffer, const size_t length)
213 {
214 return readBytes(reinterpret_cast<uint8_t *>(buffer), length);
215 }
225 inline size_t readBytes(uint8_t *buffer, const size_t length, const uint32_t timeout_ms)
226 {
227 return _serial->readBytes(buffer, length, timeout_ms);
228 }
236 inline size_t readBytes(char *buffer, const size_t length, const uint32_t timeout_ms)
237 {
238 return readBytes(reinterpret_cast<uint8_t *>(buffer), length, timeout_ms);
239 }
243 inline void flush()
244 {
245 _serial->flush();
246 }
251 inline void flush(const bool txOnly)
252 {
253 _serial->flush(txOnly);
254 }
262 size_t write(const uint8_t d);
270 size_t write(const uint8_t *buffer, const size_t size);
278 size_t write(const char *buffer, const size_t size);
285 size_t write(const char *s);
286
294 template <typename Size,
295 typename std::enable_if<!std::is_integral<Size>::value || std::is_same<Size, char>::value ||
296 std::is_same<Size, signed char>::value || std::is_same<Size, bool>::value,
297 int>::type = 0>
298 size_t write(const uint8_t *buffer, const Size size) = delete;
306 // When the deprecated write(s, wait) overload is removed, add std::is_same<Size, bool> here too,
307 // or write(s, true) would silently become a one-byte write. The static_assert on
308 // deprecated_wait_form in test/write_overload_resolution_test.cpp fails on that day.
309 template <typename Size,
310 typename std::enable_if<!std::is_integral<Size>::value || std::is_same<Size, char>::value ||
311 std::is_same<Size, signed char>::value,
312 int>::type = 0>
313 size_t write(const char *buffer, const Size size) = delete;
315
318
325 template <typename Wait, typename std::enable_if<std::is_same<Wait, bool>::value, int>::type = 0>
326 [[deprecated("write() no longer waits for TX; call flush() after writing")]] size_t write(const uint8_t d,
327 const Wait wait)
328 {
329 return wait ? write_waiting(&d, 1) : write(d);
330 }
339 [[deprecated("write() no longer waits for TX; call flush() after writing")]] inline size_t write(
340 const uint8_t *buffer, const size_t size, const bool wait)
341 {
342 return wait ? write_waiting(buffer, size) : write(buffer, size);
343 }
352 [[deprecated("write() no longer waits for TX; call flush() after writing")]] inline size_t write(const char *buffer,
353 const size_t size,
354 const bool wait)
355 {
356 return wait ? write_waiting(reinterpret_cast<const uint8_t *>(buffer), size) : write(buffer, size);
357 }
367 template <typename Wait, typename std::enable_if<std::is_same<Wait, bool>::value, int>::type = 0>
368 [[deprecated("write() no longer waits for TX; call flush() after writing")]] size_t write(const char *s,
369 const Wait wait)
370 {
371 if (!wait) {
372 return write(s);
373 }
374 return write_waiting(reinterpret_cast<const uint8_t *>(s), s ? std::strlen(s) : 0);
375 }
377
380
398 template <typename T, bool LittleEndian = true>
399 bool readValue(T &value)
400 {
401 static_assert(std::is_trivially_copyable<T>::value && std::is_standard_layout<T>::value,
402 "readValue requires trivially copyable, standard-layout types only");
403 static_assert(sizeof(T) <= 256, "readValue reads T through a stack buffer; sizeof(T) must be <= 256");
404 value = T{};
405 uint8_t buf[sizeof(T)]{};
406 size_t got = _serial->readBytes(buf, sizeof(T));
407 if (got != sizeof(T)) {
408 return false;
409 }
410 std::memcpy(&value, buf, sizeof(T));
411 if (LittleEndian != m5::endian::little) {
412 value = byteswap_if_needed(value);
413 }
414 return true;
415 }
433 template <typename T, bool LittleEndian = true>
434 bool writeValue(const T value)
435 {
436 static_assert(std::is_trivially_copyable<T>::value && std::is_standard_layout<T>::value,
437 "writeValue requires trivially copyable, standard-layout types only");
438 static_assert(sizeof(T) <= 256, "writeValue writes T through a stack buffer; sizeof(T) must be <= 256");
439 T tmp = value;
440 if (LittleEndian != m5::endian::little) {
441 tmp = byteswap_if_needed(tmp);
442 }
443 uint8_t buf[sizeof(T)]{};
444 std::memcpy(buf, &tmp, sizeof(T));
445 return write_waiting(buf, sizeof(T)) == sizeof(T);
446 }
448
449protected:
451 explicit RS485Component(const uint8_t addr);
452
469 RS485Component(RS485Component &&other) noexcept;
470
479 RS485Component &operator=(RS485Component &&other) noexcept;
480
481 // Writes bytes and waits for the transmission to complete
482 size_t write_waiting(const uint8_t *buffer, const size_t size);
483
484 inline ISerial *iserial()
485 {
486 return _serial.get();
487 }
488
495 void install_serial(std::unique_ptr<ISerial> serial);
496
506 virtual std::unique_ptr<ISerial> make_serial(AdapterUART *ad);
507
508 // 2-way byteswap dispatch tags: types m5::stl::byteswap_value accepts, and other (aggregate).
510 };
512 };
513
514 template <typename T>
516 using type = typename std::conditional<std::is_integral<T>::value || std::is_enum<T>::value ||
517 std::is_floating_point<T>::value,
519 };
520
521 template <typename T>
522 static T byteswap_if_needed(T v)
523 {
524 return byteswap_if_needed_impl(v, typename byteswap_tag_of<T>::type{});
525 }
526
527 // Integral / enum / floating-point: delegated to m5::stl::byteswap_value.
528 template <typename T>
529 static T byteswap_if_needed_impl(T v, byteswap_value_tag)
530 {
531 return m5::stl::byteswap_value(v);
532 }
533
534 // Aggregate / struct: byte-reverse of the whole object is not meaningful; return as-is.
535 // m5::stl::byteswap_value deletes these, so the dispatch must keep them out of it.
536 template <typename T>
537 static T byteswap_if_needed_impl(T v, byteswap_none_tag)
538 {
539 return v;
540 }
541
542 config_t _cfg{};
543
544private:
545 // The fallback backend lives in static storage and must outlive every component, while a
546 // backend handed over by install_serial() is owned. One pointer carries both, so that no
547 // Serial-compatible method has to test for null and moving a component needs no allocation.
548 struct SerialDeleter {
549 // No default member initializer: that would stop SerialDeleter being an aggregate in
550 // C++11, and with it the SerialDeleter{true} / SerialDeleter{false} initializations.
551 // Value-initializing the pointer (SerialPtr _serial{}) already zeroes this.
552 bool owned;
553 inline void operator()(ISerial *serial) const
554 {
555 if (owned) {
556 delete serial;
557 }
558 }
559 };
560 using SerialPtr = std::unique_ptr<ISerial, SerialDeleter>;
561
562 // Tells an owned backend which component it belongs to now.
563 void rebind_serial() noexcept;
564
565 SerialPtr _serial{};
566};
567
568} // namespace unit
569} // namespace m5
570#endif
Non-instantiable base class for RS-485 transceiver units.
Definition rs485_component.hpp:37
size_t write(const uint8_t *buffer, const Size size)=delete
Deleted: the second argument of write() is a byte count.
int available()
Returns the number of available bytes to read.
Definition rs485_component.hpp:148
uint32_t baudRate() const
Returns the baud rate the serial port is running at.
Definition rs485_component.hpp:140
size_t readBytes(uint8_t *buffer, const size_t length)
Reads bytes with timeout defined by underlying Serial.
Definition rs485_component.hpp:202
size_t write(const char *buffer, const size_t size, const bool wait)
Writes bytes from buffer, optionally waiting for the transmission to complete.
Definition rs485_component.hpp:352
virtual ~RS485Component()=default
Destructor.
size_t read(uint8_t *buffer, const size_t size)
Reads up to size bytes into buffer.
Definition rs485_component.hpp:182
bool readValue(T &value)
Read a trivially copyable value.
Definition rs485_component.hpp:399
size_t write(const uint8_t d)
Writes one byte.
Definition rs485_component.cpp:179
int peek()
Peeks the next incoming byte without removing it.
Definition rs485_component.hpp:164
bool writeValue(const T value)
Write a trivially copyable value.
Definition rs485_component.hpp:434
void install_serial(std::unique_ptr< ISerial > serial)
Installs a serial backend, taking over ownership and replacing the current one.
Definition rs485_component.cpp:90
size_t readBytes(char *buffer, const size_t length)
Reads bytes with timeout defined by underlying Serial.
Definition rs485_component.hpp:212
int read()
Reads one byte.
Definition rs485_component.hpp:172
virtual bool begin() override
Begin using the registered UART adapter.
Definition rs485_component.cpp:145
size_t read(char *buffer, const size_t size)
Reads up to size bytes into buffer.
Definition rs485_component.hpp:192
size_t write(const char *buffer, const Size size)=delete
Deleted: the second argument of write() is a byte count.
void flush()
Flushes the serial port.
Definition rs485_component.hpp:243
RS485Component(const RS485Component &)=delete
Deleted: a component owns its serial backend, so it cannot be copied.
size_t write(const char *s, const Wait wait)
Writes a null-terminated string, optionally waiting for the transmission to complete.
Definition rs485_component.hpp:368
int availableForWrite()
Returns the number of bytes that can be written without blocking.
Definition rs485_component.hpp:156
size_t readBytes(uint8_t *buffer, const size_t length, const uint32_t timeout_ms)
Reads bytes with an explicit timeout.
Definition rs485_component.hpp:225
size_t readBytes(char *buffer, const size_t length, const uint32_t timeout_ms)
Reads bytes with an explicit timeout.
Definition rs485_component.hpp:236
void config(const config_t &cfg)
Sets the configuration.
Definition rs485_component.hpp:116
config_t config() const
Gets the configuration.
Definition rs485_component.hpp:108
size_t write(const uint8_t d, const Wait wait)
Writes one byte, optionally waiting for the transmission to complete.
Definition rs485_component.hpp:326
void flush(const bool txOnly)
Flushes the serial port.
Definition rs485_component.hpp:251
virtual std::unique_ptr< ISerial > make_serial(AdapterUART *ad)
Factory hook: build the concrete ISerial to be used by begin().
Definition rs485_component.cpp:126
RS485Component & operator=(const RS485Component &)=delete
Deleted: a component owns its serial backend, so it cannot be copied.
size_t write(const uint8_t *buffer, const size_t size, const bool wait)
Writes bytes from buffer, optionally waiting for the transmission to complete.
Definition rs485_component.hpp:339
Top level namespace of M5Stack.
Unit-related namespace.
Definition rs485_component.hpp:511
Definition rs485_component.hpp:515
Definition rs485_component.hpp:509
Settings for begin.
Definition rs485_component.hpp:98
bool flushRX
Flush RX buffer on begin?
Definition rs485_component.hpp:99