78 lines
2.0 KiB
TypeScript
78 lines
2.0 KiB
TypeScript
'use strict';
|
|
import { BufferLengthError } from './errors/BufferLengthError';
|
|
import { InvalidValueError } from './errors/InvalidValueError';
|
|
import { DPT } from './definitions';
|
|
|
|
export class DPT11 implements DPT {
|
|
id = '11';
|
|
name = '3-byte date value';
|
|
bufferLength = 3;
|
|
|
|
/**
|
|
* Decode a buffer
|
|
*
|
|
* @param buffer the buffer
|
|
* @returns the DPT value
|
|
*/
|
|
decoder(buffer: Buffer): Date {
|
|
if (buffer.length !== this.bufferLength)
|
|
throw new BufferLengthError(`Invalid buffer length ${buffer.length}/${buffer} for DPT8. Expected ${this.bufferLength}.`);
|
|
|
|
const day = buffer[0] & 31; //0b00011111);
|
|
const month = buffer[1] & 15; //0b00001111);
|
|
let year = buffer[2] & 127; //0b01111111);
|
|
year = year + (year > 89 ? 1900 : 2000);
|
|
if (
|
|
day < 1 ||
|
|
day > 31 ||
|
|
month < 1 ||
|
|
month > 12 ||
|
|
year < 1990 ||
|
|
year > 2089
|
|
) {
|
|
throw new InvalidValueError(`${buffer} => ${day}/${month}/${year} is not valid date according to DPT11, setting to 1990/01/01`);
|
|
}
|
|
return new Date(year, month - 1, day);
|
|
};
|
|
|
|
/**
|
|
* Encode a buffer
|
|
*
|
|
* @param value the value to be converted to buffer
|
|
* @returns the buffer
|
|
*/
|
|
encoder(value: Date | string): Buffer {
|
|
switch (typeof value) {
|
|
case 'string':
|
|
case 'number':
|
|
value = new Date(value);
|
|
break;
|
|
case 'object':
|
|
// this expects the month property to be zero-based (January = 0, etc.)
|
|
if (value instanceof Date) break;
|
|
const { year, month, day } = value;
|
|
value = new Date(parseInt(year), parseInt(month), parseInt(day));
|
|
}
|
|
|
|
if (isNaN(value.getDate()))
|
|
throw new InvalidValueError('Must supply a numeric timestamp, Date or String object for DPT11 Date')
|
|
|
|
const year = value.getFullYear();
|
|
return Buffer.from([
|
|
value.getDate(),
|
|
value.getMonth() + 1,
|
|
year - (year >= 2000 ? 2000 : 1900),
|
|
]);
|
|
}
|
|
|
|
|
|
subtypes: {
|
|
// 11.001 date
|
|
'001': {
|
|
name: 'DPT_Date',
|
|
desc: 'Date',
|
|
},
|
|
};
|
|
|
|
}
|