1 // Copyright 2023 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
15 #include "pw_stream_uart_mcuxpresso/stream.h"
16
17 namespace pw::stream {
18
~UartStreamMcuxpresso()19 UartStreamMcuxpresso::~UartStreamMcuxpresso() {
20 USART_RTOS_Deinit(&handle_);
21 element_controller_.Release().IgnoreError();
22 }
23
Init(uint32_t srcclk)24 Status UartStreamMcuxpresso::Init(uint32_t srcclk) {
25 config_.srcclk = srcclk;
26
27 PW_TRY(element_controller_.Acquire());
28
29 if (USART_RTOS_Init(&handle_, &uart_handle_, &config_) != kStatus_Success) {
30 element_controller_.Release().IgnoreError();
31 return Status::Internal();
32 }
33
34 return OkStatus();
35 }
36
DoRead(ByteSpan data)37 StatusWithSize UartStreamMcuxpresso::DoRead(ByteSpan data) {
38 size_t read = 0;
39 if (const auto status =
40 USART_RTOS_Receive(&handle_,
41 reinterpret_cast<uint8_t*>(data.data()),
42 data.size(),
43 &read);
44 status != kStatus_Success) {
45 USART_TransferAbortReceive(base_, &uart_handle_);
46 return StatusWithSize(Status::Internal(), 0);
47 }
48
49 return StatusWithSize(read);
50 }
51
DoWrite(ConstByteSpan data)52 Status UartStreamMcuxpresso::DoWrite(ConstByteSpan data) {
53 if (USART_RTOS_Send(
54 &handle_,
55 reinterpret_cast<uint8_t*>(const_cast<std::byte*>(data.data())),
56 data.size()) != kStatus_Success) {
57 return Status::Internal();
58 }
59 return OkStatus();
60 }
61
62 } // namespace pw::stream
63