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 15import * as protocol from './protocol'; 16import * as util from './util'; 17 18const FLAG_BYTE = Uint8Array.from([protocol.FLAG]); 19 20export class Encoder { 21 constructor() { 22 // Do nothing. 23 } 24 25 /** Encodes an HDLC UI-frame with a CRC-32 frame check sequence. */ 26 uiFrame(address: number, data: Uint8Array): Uint8Array { 27 const addr = protocol.encodeAddress(address); 28 const frameControl = protocol.UI_FRAME_CONTROL; 29 const start = util.concatenate(addr, frameControl, data); 30 let frame = util.concatenate(start, protocol.frameCheckSequence(start)); 31 32 frame = util.replace(frame, 0x7d, [0x7d, 0x5d]); 33 frame = util.replace(frame, 0x7e, [0x7d, 0x5e]); 34 return util.concatenate(FLAG_BYTE, frame, FLAG_BYTE); 35 } 36} 37