The main purpose of this library is create a small and reusable serialization engine able to manage serial message protocol. The use of property decorators has allowed to reduce serialization/deserialization to a loop around properties metadata obtained at initialization time. The module has two model: one for data and another one for messages.
Data model is made to allow data (de)serialization, message module to allow to send/receive datas. Both work with buffer (byte array) and Message model is a specialization of Data model.
The main dependencie of this module is typescript compiler tsc.
npm install -g typescript
Include the lib in your project simply run:
npm install byte-serializer
After the library were added in your project, you have to import some modules dependencies:
To create a serializable payload you have to extends imported type serializable and then use decorators contained in SerializerInfo to define position, length, type and data specification of properties you have inside.
A serializable payload is just an object that can be serialized in a byte array (buffer). If you want to send, or receive, the paylod you have to add some metadatas such as start byte, expected length (or just length), id, crc and abviously data. You can choose to add a end byte to mark the end of message. For this pourpose you have to extend abstract class Message.
import {Serializable, SerializerInfo, BitOrder, NumberType, TextEncoding} from 'byte-serializer'
export class DataExample extends Serializable {
@SerializerInfo.position(0)
@SerializerInfo.length(4)
@SerializerInfo.bitOrder(BitOrder.BE)
@SerializerInfo.numberType(NumberType.Int32)
public Pippo:number;
@SerializerInfo.position(4)
@SerializerInfo.length(2)
@SerializerInfo.bitOrder(BitOrder.BE)
@SerializerInfo.numberType(NumberType.Int16)
public Pluto :number;
@SerializerInfo.position(6)
@SerializerInfo.length(10)
@SerializerInfo.textEncoding(TextEncoding.ASCII)
public Text :string;
}
Use the constructor to initialize data.
let data = new DataExample();
data.Number1 = 50;
data.Number2 = 2000;
data.Text = "A long string"; // More the 10 chars
let payload = data.serialize();
let newData = new DataExample();
newData.deserialize(payload);