Skip to content

Commit

Permalink
Replace @hibas123/nodelogging with winston logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Patrick-Remy committed Jan 31, 2021
1 parent 6be28ea commit 41b765b
Show file tree
Hide file tree
Showing 5 changed files with 283 additions and 64 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ Options:

```javascript
{
verbose: 1, //Verbosity, default 0
log: { level: 'info' }, // Winston logger options
oem: 0, //OEM Code from artisticlicense, default to dmxnet OEM.
sName: "Text", // 17 char long node description, default to "dmxnet"
lName: "Long description", // 63 char long node description, default to "dmxnet - OpenSource ArtNet Transceiver"
Expand Down
6 changes: 3 additions & 3 deletions lib.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Socket } from 'dgram'
import { EventEmitter } from 'events'
import { NetworkInterfaceInfo } from 'os'
import { Logger, LoggerOptions } from 'winston'

export interface NetworkInterface {
ip: NetworkInterfaceInfo['address']
Expand Down Expand Up @@ -41,7 +42,6 @@ declare class sender {
constructor(opt: SenderOptions | undefined, parent: dmxnet)
parent: dmxnet
socket_ready: boolean
verbose: DmxnetOptions['verbose']
values: number[]
ArtDmxSeq: number
socket: Socket
Expand Down Expand Up @@ -103,7 +103,6 @@ declare class receiver extends EventEmitter {
*/
constructor(opt: ReceiverOptions | undefined, parent: dmxnet)
parent: dmxnet
verbose: DmxnetOptions['verbose']
values: number[]
subuninet: number
/**
Expand All @@ -115,7 +114,7 @@ declare class receiver extends EventEmitter {
}

export interface DmxnetOptions {
verbose?: number
log?: LoggerOptions
oem?: number
listen?: number
sName?: string
Expand All @@ -133,6 +132,7 @@ declare class dmxnet {
* @param {DmxnetOptions} [options] - Options for the whole instance
*/
constructor(options?: DmxnetOptions)
logger: Logger
port: DmxnetOptions['listen']
interfaces: Record<string, NetworkInterfaceInfo[]>
ip4: NetworkInterface[]
Expand Down
103 changes: 52 additions & 51 deletions lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,7 @@ var EventEmitter = require('events');
var jspack = require('jspack').jspack;
const os = require('os');
const Netmask = require('netmask').Netmask;
// Require Logging
const LoggingBase = require('@hibas123/nodelogging').LoggingBase;
// Init Logger
const log = new LoggingBase({
name: 'dmxnet',
});
const winston = require('winston');

// ArtDMX Header for jspack
var ArtDmxHeaderFormat = '!7sBHHBBBBH';
Expand All @@ -26,24 +21,33 @@ class dmxnet {
*/
constructor(options) {
// Parse all options and set defaults
this.verbose = options.verbose || 0;
this.oem = options.oem || 0x2908; // OEM code hex
this.port = options.listen || 6454; // Port listening for incoming data
this.sName = options.sName || 'dmxnet'; // Shortname
this.lName = options.lName ||
'dmxnet - OpenSource ArtNet Transceiver'; // Longname
this.hosts = options.hosts || []
// Set log levels
if (this.verbose > 0) {
// ToDo: Set Log Level
if (this.verbose > 1) {
// ToDo: Set Log Level Debug
}
} else {
// ToDo: Set Log Level
}

// Init Logger
this.logOptions = Object.assign(
{
level: 'info',
format: winston.format.combine(
winston.format.splat(),
winston.format.timestamp(),
winston.format.label({ label: 'dmxnet' }),
winston.format.printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`;
}),
),
transports: [new winston.transports.Console()]
},
options.log
);
this.logger = new winston.createLogger(this.logOptions);

this.hosts = options.hosts || [];
// Log started information
log.log('started with options ' + JSON.stringify(options));
this.logger.info('started with options: %o', options);

// Get all network interfaces
this.interfaces = os.networkInterfaces();
Expand All @@ -65,7 +69,7 @@ class dmxnet {
}
});
});
log.debug('Interfaces: ' + JSON.stringify(this.ip4));
this.logger.verbose('Interfaces: %o', this.ip4);
// init artPollReplyCount
this.artPollReplyCount = 0;
// Array containing reference to foreign controllers
Expand Down Expand Up @@ -98,7 +102,7 @@ class dmxnet {
});
// Start listening
this.listener4.bind(this.port);
log.log('Listening on port ' + this.port);
this.logger.info('Listening on port ' + this.port);
// Open Socket for sending broadcast data
this.socket = dgram.createSocket('udp4');
this.socket.bind(() => {
Expand All @@ -108,7 +112,7 @@ class dmxnet {
// Periodically check Controllers
setInterval(() => {
if (this.controllers) {
log.debug('Check controller alive, count ' + this.controllers.length);
this.logger.verbose('Check controller alive, count ' + this.controllers.length);
for (var index = 0; index < this.controllers.length; index++) {
if ((new Date().getTime() -
new Date(this.controllers[index].last_poll).getTime()) >
Expand Down Expand Up @@ -151,7 +155,7 @@ class dmxnet {
* Builds and sends an ArtPollReply-Packet
*/
ArtPollReply() {
log.debug('Send ArtPollReply');
this.logger.silly('Send ArtPollReply');

this.ip4.forEach((ip) => {
// BindIndex handles all the different "instance".
Expand Down Expand Up @@ -210,7 +214,7 @@ class dmxnet {
client.send(udppacket, 0, udppacket.length, 6454, broadcastip,
(err) => {
if (err) throw err;
log.log('ArtPollReply frame sent');
this.logger.debug('ArtPollReply frame sent');
});
});
// Send one package for every receiver
Expand Down Expand Up @@ -259,7 +263,7 @@ class dmxnet {
client.send(udppacket, 0, udppacket.length, 6454, broadcastip,
(err) => {
if (err) throw err;
log.log('ArtPollReply frame sent');
this.logger.debug('ArtPollReply frame sent');
});
});
if ((this.senders.length + this.receivers.length) < 1) {
Expand Down Expand Up @@ -297,13 +301,13 @@ class dmxnet {
// BindIndex, Status2
1, 0b00001110,
]));
log.debug('Packet content: ' + udppacket.toString('hex'));
this.logger.debug('Packet content: ' + udppacket.toString('hex'));
// Send UDP
var client = this.socket;
client.send(udppacket, 0, udppacket.length, 6454, broadcastip,
(err) => {
if (err) throw err;
log.log('ArtPollReply frame sent');
this.logger.debug('ArtPollReply frame sent');
});
}
});
Expand Down Expand Up @@ -337,7 +341,6 @@ class sender {
this.subuni = options.subuni;
this.ip = options.ip || '255.255.255.255';
this.port = options.port || 6454;
this.verbose = this.parent.verbose;
this.base_refresh_interval = options.base_refresh_interval || 1000;

// Validate Input
Expand All @@ -353,10 +356,7 @@ class sender {
if ((this.net < 0) || (this.subnet < 0) || (this.universe < 0)) {
throw new Error('Subnet, Net or Universe must be 0 or bigger!');
}
if (this.verbose > 0) {
log.log('new dmxnet sender started with params: ' +
JSON.stringify(options));
}
this.parent.logger.info('new dmxnet sender started with params: %o', options);
// init dmx-value array
this.values = [];
// fill all 512 channels
Expand Down Expand Up @@ -413,13 +413,13 @@ class sender {
// Increase Sequence Counter
this.ArtDmxSeq++;

log.debug('Packet content: ' + udppacket.toString('hex'));
this.parent.logger.debug('Packet content: ' + udppacket.toString('hex'));
// Send UDP
var client = this.socket;
client.send(udppacket, 0, udppacket.length, this.port, this.ip,
(err) => {
if (err) throw err;
log.log('ArtDMX frame sent to ' + this.ip + ':' + this.port);
this.parent.logger.silly('ArtDMX frame sent to ' + this.ip + ':' + this.port);
});
}
}
Expand Down Expand Up @@ -550,7 +550,6 @@ class receiver extends EventEmitter {
this.subnet = options.subnet || 0;
this.universe = options.universe || 0;
this.subuni = options.subuni;
this.verbose = this.parent.verbose;

// Validate Input
if (this.net > 127) {
Expand All @@ -565,10 +564,7 @@ class receiver extends EventEmitter {
if ((this.net < 0) || (this.subnet < 0) || (this.universe < 0)) {
throw new Error('Subnet, Net or Universe must be 0 or bigger!');
}
if (this.verbose > 0) {
log.log('new dmxnet sender started with params: ' +
JSON.stringify(options));
}
this.parent.logger.info('new dmxnet sender started with params %o', options);
// init dmx-value array
this.values = [];
// fill all 512 channels
Expand Down Expand Up @@ -596,47 +592,52 @@ class receiver extends EventEmitter {
}

// Parser & receiver
/**
* @param {Buffer} msg - Message buffer to parse
* @param {dgram.RemoteInfo} rinfo - Remote info
* @param {dmxnet} parent - Instance of the dmxnet parent
*/
var dataParser = function (msg, rinfo, parent) {
log.debug(`got UDP from ${rinfo.address}:${rinfo.port}`);
parent.logger.silly(`got UDP from ${rinfo.address}:${rinfo.port}`);
if (rinfo.size < 10) {
log.debug('Payload to short');
parent.logger.silly('Payload to short');
return;
}
// Check first 8 bytes for the "Art-Net" - String
if (String(jspack.Unpack('!8s', msg)) !== 'Art-Net\u0000') {
log.debug('Invalid header');
parent.logger.silly('Invalid header');
return;
}
var opcode = parseInt(jspack.Unpack('B', msg, 8), 10);
opcode += parseInt(jspack.Unpack('B', msg, 9), 10) * 256;
if (!opcode || opcode === 0) {
log.debug('Invalid OpCode');
parent.logger.silly('Invalid OpCode');
return;
}
switch (opcode) {
case 0x5000:
log.debug('detected ArtDMX');
parent.logger.debug('detected ArtDMX');
var universe = parseInt(jspack.Unpack('H', msg, 14), 10);
var data = [];
for (var ch = 1; ch <= msg.length - 18; ch++) {
data.push(msg.readUInt8(ch + 17, true));
}
log.debug('Received frame for SubUniNet 0x' + universe.toString(16));
parent.logger.debug('Received frame for SubUniNet 0x' + universe.toString(16));
if (parent.receiversSubUni[universe]) {
parent.receiversSubUni[universe].receive(data);
}
break;
case 0x2000:
if (rinfo.size < 14) {
log.debug('ArtPoll to small');
parent.logger.silly('ArtPoll to small');
return;
}
log.debug('detected ArtPoll');
parent.logger.debug('detected ArtPoll');
// Parse Protocol version
var proto = parseInt(jspack.Unpack('B', msg, 10), 10);
proto += parseInt(jspack.Unpack('B', msg, 11), 10) * 256;
if (!proto || proto < 14) {
log.debug('Invalid OpCode');
parent.logger.silly('Invalid OpCode');
return;
}
// Parse TalkToMe
Expand Down Expand Up @@ -664,18 +665,18 @@ var dataParser = function (msg, rinfo, parent) {
parent.controllers.push(ctrl);
}
parent.ArtPollReply();
log.debug('Controllers: ' + JSON.stringify(parent.controllers));
parent.logger.debug('Controllers: %o', parent.controllers);
break;
case 0x2100:
// ToDo
log.debug('detected ArtPollReply');
parent.logger.debug('detected ArtPollReply');
break;
default:
log.debug('OpCode not implemented');
parent.logger.silly('OpCode not implemented');
}

};
// Export dmxnet
module.exports = {
dmxnet,
};
};
Loading

0 comments on commit 41b765b

Please sign in to comment.