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 <cstddef> 17 #include <cstdint> 18 19 #include "pw_bytes/span.h" 20 #include "pw_checksum/crc32.h" 21 #include "pw_hdlc/internal/protocol.h" 22 #include "pw_status/status.h" 23 #include "pw_stream/stream.h" 24 25 namespace pw::hdlc::internal { 26 27 // Encodes and writes HDLC frames. 28 class Encoder { 29 public: Encoder(stream::Writer & output)30 constexpr Encoder(stream::Writer& output) : writer_(output) {} 31 32 // Writes the header for an I-frame. After successfully calling 33 // StartInformationFrame, WriteData may be called any number of times. StartInformationFrame(uint64_t address)34 Status StartInformationFrame(uint64_t address) { 35 return StartFrame(address, kUnusedControl); 36 } 37 38 // Writes the header for an U-frame. After successfully calling 39 // StartUnnumberedFrame, WriteData may be called any number of times. StartUnnumberedFrame(uint64_t address)40 Status StartUnnumberedFrame(uint64_t address) { 41 return StartFrame(address, UFrameControl::UnnumberedInformation().data()); 42 } 43 44 // Writes data for an ongoing frame. Must only be called after a successful 45 // StartInformationFrame call, and prior to a FinishFrame() call. 46 Status WriteData(ConstByteSpan data); 47 48 // Finishes a frame. Writes the frame check sequence and a terminating flag. 49 Status FinishFrame(); 50 51 private: 52 // Indicates this an information packet with sequence numbers set to 0. 53 static constexpr std::byte kUnusedControl = std::byte{0}; 54 55 Status StartFrame(uint64_t address, std::byte control); 56 57 stream::Writer& writer_; 58 checksum::Crc32 fcs_; 59 }; 60 61 } // namespace pw::hdlc::internal 62