1 // Copyright 2021 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_sys_io/sys_io.h" 16 17 #include <zephyr/console/console.h> 18 #include <zephyr/init.h> 19 #include <zephyr/kernel.h> 20 #include <zephyr/usb/usb_device.h> 21 sys_io_init(void)22static int sys_io_init(void) { 23 int err; 24 25 if (IS_ENABLED(CONFIG_PIGWEED_SYS_IO_USB)) { 26 err = usb_enable(nullptr); 27 if (err) { 28 return err; 29 } 30 } 31 err = console_init(); 32 return err; 33 } 34 35 SYS_INIT(sys_io_init, APPLICATION, CONFIG_PIGWEED_SYS_IO_INIT_PRIORITY); 36 37 namespace pw::sys_io { 38 ReadByte(std::byte * dest)39Status ReadByte(std::byte* dest) { 40 if (dest == nullptr) { 41 return Status::InvalidArgument(); 42 } 43 44 const int c = console_getchar(); 45 *dest = static_cast<std::byte>(c); 46 47 return c < 0 ? Status::FailedPrecondition() : OkStatus(); 48 } 49 TryReadByte(std::byte * dest)50Status TryReadByte(std::byte* dest) { 51 if (dest == nullptr) { 52 return Status::InvalidArgument(); 53 } 54 55 uint8_t byte; 56 int result = console_read(nullptr, &byte, 1); 57 58 if (result >= 0) { 59 *dest = static_cast<std::byte>(byte); 60 return OkStatus(); 61 } 62 63 return Status::Unavailable(); 64 } 65 WriteByte(std::byte b)66Status WriteByte(std::byte b) { 67 return console_putchar(static_cast<char>(b)) < 0 68 ? Status::FailedPrecondition() 69 : OkStatus(); 70 } 71 WriteLine(std::string_view s)72StatusWithSize WriteLine(std::string_view s) { 73 size_t chars_written = 0; 74 StatusWithSize size_result = WriteBytes(as_bytes(span(s))); 75 if (!size_result.ok()) { 76 return size_result; 77 } 78 chars_written += size_result.size(); 79 80 // Write trailing newline character. 81 Status result = WriteByte(static_cast<std::byte>('\n')); 82 if (result.ok()) { 83 chars_written++; 84 } 85 86 return StatusWithSize(result, chars_written); 87 } 88 89 } // namespace pw::sys_io 90