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