1 // Copyright 2020 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include <cstdint> 17 18 #include "pw_result/result.h" 19 #include "pw_span/span.h" 20 #include "pw_stream/stream.h" 21 22 namespace pw::stream { 23 24 /// `pw::stream::NonSeekableReaderWriter` implementation for UARTs on Linux. 25 class UartStreamLinux : public NonSeekableReaderWriter { 26 public: 27 constexpr UartStreamLinux() = default; 28 29 // UartStream objects are moveable but not copyable. 30 UartStreamLinux& operator=(UartStreamLinux&& other) { 31 fd_ = other.fd_; 32 other.fd_ = kInvalidFd; 33 return *this; 34 } UartStreamLinux(UartStreamLinux && other)35 UartStreamLinux(UartStreamLinux&& other) noexcept : fd_(other.fd_) { 36 other.fd_ = kInvalidFd; 37 } 38 UartStreamLinux(const UartStreamLinux&) = delete; 39 UartStreamLinux& operator=(const UartStreamLinux&) = delete; 40 ~UartStreamLinux()41 ~UartStreamLinux() override { Close(); } 42 43 /// Open a UART device using the specified baud rate. 44 /// 45 /// @param[in] path Path to the TTY device. 46 /// @param[in] baud_rate Baud rate to use for the device. 47 /// 48 /// @returns @rst 49 /// 50 /// .. pw-status-codes:: 51 /// 52 /// OK: The device was successfully opened and configured. 53 /// 54 /// INVALID_ARGUMENT: An unsupported baud rate was supplied. 55 /// 56 /// FAILED_PRECONDITION: A device was already open. 57 /// 58 /// UNKNOWN: An error was returned by the operating system. 59 /// 60 /// @endrst 61 Status Open(const char* path, uint32_t baud_rate); 62 void Close(); 63 64 private: 65 static constexpr int kInvalidFd = -1; 66 67 Status DoWrite(ConstByteSpan data) override; 68 StatusWithSize DoRead(ByteSpan dest) override; 69 70 int fd_ = kInvalidFd; 71 }; 72 73 } // namespace pw::stream 74