UNPKG

node-hca

Version:

Node.js client for HCA

116 lines (86 loc) 3.06 kB
'use strict'; var HcaResponse = require('./HcaResponse'); (function() { var parse = function(data) { var params = this.decode(data); var response = new HcaResponse(); response.code = parseInt(params[0]); response.group = params[1]; response.command = params[2]; response.data = params.slice(3); return response; }; var encode = function(parameters) { var separator = ' '; // 4 spaces. var paramCount = parameters.length; var preamble = ''; var preambleLength = paramCount * 4; var data = ''; for (var i = 0; i < paramCount; i++) { var param = parameters[i].toString(); var curLength = preambleLength + separator.length + data.length; data += param; preamble += (curLength + param.length).pad(4); } return preamble + separator + data; }; var decode = function(data) { // This method is a port from C to Javascript. Original HCA sample can be found at: // http://www.hcatech.com/download/V12/Doc/TechNote_ServerProtocol.pdf var iSep = data.indexOf(' '); // 4 spaces; if (iSep == -1) return (null); // Extract the part before the 4 blanks var pspec = data.substr(0, iSep); var sEnd; var text; // Make sure it contains a multiple of 4 characters if ((pspec.length % 4) != 0) return (null); // Determine count of parameters. Each one is defined by 4 characters var ctParams = pspec.length / 4; // Start of the parameter. Moved along as each is extracted var iStart = iSep + 4; var iEnd; var params = []; var paramCount = params; for (var i = 0; i < ctParams; i++) { sEnd = pspec.substr(i * 4, 4); // Extract out the spec for this parameter iEnd = parseInt(sEnd); if (isNaN(iEnd)) // Make into number form. Must convert ok { //delete params; params.length = 0; return (null); } if (iEnd > data.length) // This number tell us the end character. So // make sure we have sufficient in the string { //delete params; params.length = 0; return (null); } // Extract the text for this parameter. Could be a null string if ((iEnd - iStart) == 0) text = ""; else text = data.substr(iStart, iEnd - iStart); params.push(text); paramCount++; iStart = iEnd; } return params; }; Number.prototype.pad = function(size) { var s = String(this); while (s.length < (size || 2)) { s = "0" + s; } return s; }; module.exports = { parse: parse, encode: encode, decode: decode }; })();