master
IoTcat 5 years ago
parent 7501895874
commit 2ab9c12b48
  1. 1
      node/node_modules/macfromip/.npmignore
  2. 30
      node/node_modules/macfromip/README.md
  3. 10
      node/node_modules/macfromip/example.js
  4. 160
      node/node_modules/macfromip/macfromip.js
  5. 62
      node/node_modules/macfromip/package.json
  6. 22
      node/node_modules/macfromip/test/test-macfromip.js
  7. 5
      node/package-lock.json
  8. 4
      node/package.json
  9. 885
      node/wiot.js

@ -0,0 +1 @@
npm-debug.log

@ -0,0 +1,30 @@
macfromip
=========
## Synopsis
* Nodejs script;
* Gets a MAC address from a LAN IP address;
* Only works on linux, OSX and win32 platforms;
## Code Example
```
var macfromip = require('macfromip');
macfromip.getMac('192.168.2.169', function(err, data){
if(err){
console.log(err);
}
console.log(data);
});
```
## Installation
```
npm install macfromip
```
## TODO List:
Complete list on [Trello](https://trello.com/b/B1WM4gbZ/macfromip)

@ -0,0 +1,10 @@
var macfromip = require('./macfromip.js');
macfromip.getMac('192.168.2.57', function(err, data){
if(err){
console.log(err);
}
else{
console.log(data);
}
});

@ -0,0 +1,160 @@
/* jshint node: true */
'use strict';
var macfromip = exports;
var cp = require('child_process');
var os = require('os');
var MACADDRESS_LENGTH = 17;
macfromip.isEmpty = function(value){
return ((value === null) || (typeof value === 'undefined') || 0 === value.length);
};
macfromip.isString = function(value){
if(macfromip.isEmpty(value)){
throw new Error('Expected a not null value');
}
if (typeof value === 'string') {
return true;
}
return false;
};
macfromip.isIpAddress = function(ipaddress){
if(!macfromip.isString(ipaddress)){
throw new Error('Expected a string');
}
/* Thanks to http://www.w3resource.com/javascript/form/ip-address-validation.php#sthash.kBJql3HS.dpuf */
if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress.trim())){
return (true);
}
return (false);
};
macfromip.ipIsSelf = function(ipaddress){
var ifaces = os.networkInterfaces();
var selfIps = new Array();
Object.keys(ifaces).forEach(function (ifname) {
var alias = 0;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
selfIps.push(iface.address);
});
});
var index;
for (index = 0; index < selfIps.length; ++index) {
if(selfIps[index] === ipaddress){
return true;
}
}
return false;
};
macfromip.getMacInLinux = function(ipAddress, callback){
// OSX requires -c switch first
var ls = cp.exec('ping -c 1 ' + ipAddress,
function(error, stdout, stderr) {
if (error !== null) {
callback('IP address unreachable', 'exec error: ' + error);
return;
}
if (stderr !== null && stderr !== '') {
callback('IP address unreachable', 'stderr: ' + stderr);
return;
}
var ls2 = cp.exec('arp -a',
function(error2, stdout2, stderr2) {
if (error2 !== null) {
callback('IP address unreachable', 'exec error: ' + error2);
return;
}
if (stderr2 !== null && stderr2 !== '') {
callback('IP address unreachable', 'stderr: ' + stderr2);
return;
}
stdout2 = (stdout2.substring(stdout2.indexOf(ipAddress) + (ipAddress.length + 5))).substring(MACADDRESS_LENGTH, 0);
callback(false, stdout2);
return;
});
});
};
macfromip.getMacInWin32 = function(ipAddress, callback){
var ls = cp.exec('ping ' + ipAddress + ' -n 1',
function(error, stdout, stderr) {
if (error !== null) {
callback('IP address unreachable', 'exec error: ' + error);
return;
}
if (stderr !== null && stderr !== '') {
callback('IP address unreachable', 'stderr: ' + stderr);
return;
}
var ls2 = cp.exec('arp -a',
function(error2, stdout2, stderr2) {
if (error2 !== null) {
callback('IP address unreachable', 'exec error: ' + error2);
return;
}
if (stderr2 !== null && stderr2 !== '') {
callback('IP address unreachable', 'stderr: ' + stderr2);
return;
}
var offset = 22 - ipAddress.length;
stdout2 = (stdout2.substring(stdout2.indexOf(ipAddress) + (ipAddress.length + offset))).substring(MACADDRESS_LENGTH, 0);
callback(false, stdout2);
return;
});
});
};
macfromip.getMac = function(ipAddress, callback) {
if(!macfromip.isIpAddress(ipAddress)) {
throw new Error("The value you entered is not a valid IP address");
}
if(macfromip.ipIsSelf(ipAddress)){
throw new Error("The IP address cannot be self");
}
switch(os.platform()){
case 'linux':
macfromip.getMacInLinux(ipAddress, function(err, mac){
callback(err, mac);
});
break;
case 'win32':
macfromip.getMacInWin32(ipAddress, function(err, mac){
callback(err, mac);
});
break;
// OSX
case 'darwin':
macfromip.getMacInLinux(ipAddress, function(err, mac){
callback(err, mac);
});
break;
default:
callback('Unsupported platform: ' + os.platform(), null);
break;
}
};

@ -0,0 +1,62 @@
{
"_from": "macfromip",
"_id": "macfromip@1.1.1",
"_inBundle": false,
"_integrity": "sha1-uy9GiBDMOm0ZFxabj4InHuMOTd0=",
"_location": "/macfromip",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "macfromip",
"name": "macfromip",
"escapedName": "macfromip",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/macfromip/-/macfromip-1.1.1.tgz",
"_shasum": "bb2f468810cc3a6d1917169b8f82271ee30e4ddd",
"_spec": "macfromip",
"_where": "E:\\Arduino_project\\wIoT\\node",
"author": {
"name": "bcamarneiro",
"email": "camarneirobruno@gmail.com"
},
"bugs": {
"url": "https://github.com/bcamarneiro/macfromip/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Paul Cook"
},
{
"name": "Sean Nessworthy",
"email": "sean@nessworthy.me"
}
],
"deprecated": false,
"description": "On given an IP Address, will attempt to identify that IP's MAC address.",
"directories": {
"test": "test"
},
"homepage": "https://github.com/bcamarneiro/macfromip",
"keywords": [
"MAC",
"IP",
"Address"
],
"license": "MIT",
"main": "macfromip.js",
"name": "macfromip",
"repository": {
"type": "git",
"url": "git+https://github.com/bcamarneiro/macfromip.git"
},
"version": "1.1.1"
}

@ -0,0 +1,22 @@
var macfromip = require('../macfromip.js');
exports['isIpAddress'] = function (test) {
test.equal(macfromip.isEmpty('0'), false);
test.equal(macfromip.isEmpty(' '), false);
test.equal(macfromip.isEmpty(''), true);
test.equal(macfromip.isEmpty(null), true);
test.equal(macfromip.isEmpty(), true);
test.equal(macfromip.isString(false), false);
test.equal(macfromip.isString(1233536), false);
test.equal(macfromip.isString('1233536'), true);
test.equal(macfromip.isString('#$%&asda3445'), true);
test.equal(macfromip.isIpAddress('127.0.0.1'), true);
test.equal(macfromip.isIpAddress('255.255.255.255'), true);
test.equal(macfromip.isIpAddress('0.0.0.0'), true);
test.equal(macfromip.isIpAddress('asdasdasdghdsgsdg'), false);
test.equal(macfromip.isIpAddress('192.168.2.5a'), false);
test.done();
};

@ -7,6 +7,11 @@
"@network-utils/arp-lookup": { "@network-utils/arp-lookup": {
"version": "https://registry.npm.taobao.org/@network-utils/arp-lookup/download/@network-utils/arp-lookup-1.0.3.tgz" "version": "https://registry.npm.taobao.org/@network-utils/arp-lookup/download/@network-utils/arp-lookup-1.0.3.tgz"
}, },
"macfromip": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/macfromip/-/macfromip-1.1.1.tgz",
"integrity": "sha1-uy9GiBDMOm0ZFxabj4InHuMOTd0="
},
"node-arp": { "node-arp": {
"version": "1.0.6", "version": "1.0.6",
"resolved": "https://registry.npmjs.org/node-arp/-/node-arp-1.0.6.tgz", "resolved": "https://registry.npmjs.org/node-arp/-/node-arp-1.0.6.tgz",

@ -1,6 +1,6 @@
{ {
"name": "wiot", "name": "wiot",
"version": "0.0.4", "version": "0.0.5",
"description": "An awesome iot system for web developers~", "description": "An awesome iot system for web developers~",
"main": "wiot.js", "main": "wiot.js",
"scripts": { "scripts": {
@ -25,7 +25,7 @@
"homepage": "https://github.com/IoTcat/wIoT-nodeJS#readme", "homepage": "https://github.com/IoTcat/wIoT-nodeJS#readme",
"dependencies": { "dependencies": {
"@network-utils/arp-lookup": "^1.0.3", "@network-utils/arp-lookup": "^1.0.3",
"node-arp": "^1.0.6", "macfromip": "^1.1.1",
"ping": "^0.2.2" "ping": "^0.2.2"
} }
} }

@ -2,443 +2,464 @@
* @Author: IoTcat (https://iotcat.me) * @Author: IoTcat (https://iotcat.me)
* @Date: 2019-05-04 18:59:49 * @Date: 2019-05-04 18:59:49
* @Last Modified by: * @Last Modified by:
* @Last Modified time: 2019-05-05 02:31:52 * @Last Modified time: 2019-05-05 03:28:11
*/ */
var wiot = function (o_params) {
var o = { var wiot = function (o_params) {
MAC: "", var o = {
pin: { MAC: "",
D1: 0, pin: {
D2: 0, D1: 0,
D3: 0, D2: 0,
D4: 0, D3: 0,
D5: 0, D4: 0,
D6: 0, D5: 0,
D7: 0, D6: 0,
D8: 0 D7: 0,
}, D8: 0
hint: true, },
debug: false, hint: true,
on: () => {}, debug: false,
OUTPUT: 1, on: () => {},
INPUT: 0, OUTPUT: 1,
INPUT_PULLUP: 2, INPUT: 0,
HIGH: 1, INPUT_PULLUP: 2,
LOW: 0, HIGH: 1,
data: {}, LOW: 0,
ip: "default", data: {},
ip_range: "192.168.4", ip: "default",
version: "", ip_range: "192.168.0",
errDelayTime: 2000, localIP: "127.0.0.1",
okDelayTime: 30, version: "",
resetDelayTime: 4500, errDelayTime: 2000,
noTryMaxTime: 60000, okDelayTime: 30,
IntervalTime: 2000, resetDelayTime: 4500,
MaxToReScanTime: 180000, noTryMaxTime: 60000,
MinResearchTime: 5000, IntervalTime: 2000,
IpScanTimeOut: 300, MaxToReScanTime: 180000,
pingTimeout: 2, MinResearchTime: 5000,
LastConnectTime: Date.parse(new Date()), IpScanTimeOut: 1,
isConnected: false, pingTimeout: 2,
LastTryTime: Date.parse(new Date()), LastConnectTime: Date.parse(new Date()),
firstReady: 0, isConnected: false,
pinCmd: { LastTryTime: Date.parse(new Date()),
D1: 0, firstReady: 0,
D2: 0, pinCmd: {
D3: 0, D1: 0,
D4: 0, D2: 0,
D5: 0, D3: 0,
D6: 0, D4: 0,
D7: 0, D5: 0,
D8: 0 D6: 0,
} D7: 0,
}; D8: 0
}
/* merge paras */ };
if (typeof o_params.pin != undefined) {
o_params.pin = Object.assign(o.pin, o_params.pin); /* merge paras */
} if (typeof o_params.pin != undefined) {
Object.assign(o, o_params); o_params.pin = Object.assign(o.pin, o_params.pin);
}
/* require packages */ Object.assign(o, o_params);
var http = require('http');
var net = require('net'); /* require packages */
var arp = require('@network-utils/arp-lookup'); var http = require('http');
var ping = require('ping'); var arp = require('@network-utils/arp-lookup');
var nodeArp = require('node-arp'); var ping = require('ping');
var os = require('os');
/* tmp global var */ var nodeArp = require('macfromip');
var ip_point = 0;
/* tmp global var */
/* tools */ var ip_point = 0;
var IsJsonString = (str) => {
try { /* tools */
JSON.parse(str); var IsJsonString = (str) => {
} catch (e) { try {
return false; JSON.parse(str);
} } catch (e) {
return true; return false;
}; }
return true;
};
var ip_scan = function () {
var socket = new net.Socket();
socket.setTimeout(o.IpScanTimeOut); var getLocalIp = () => {
socket.on('connect', function () { var ifaces = os.networkInterfaces();
socket.end();
check_MAC(); for (var dev in ifaces) {
}); ifaces[dev].forEach((details) => {
socket.on('timeout', function () { if ((details.family == 'IPv4') && (details.internal == false)) {
socket.destroy(); o.localIP = details.address;
next_IP(); var ipParts = [];
}); ipParts = o.localIP.split(".");
socket.on('error', function (err) { o.ip_range = ipParts[0] + '.' + ipParts[1] + '.' + ipParts[2];
next_IP(); }
}); });
socket.on('close', function (err) {}); }
socket.connect(80, generate_IP()); };
};
var ip_scan = function () {
var check_MAC = () => { ping.promise.probe(generate_IP(), {
o.LastConnectTime = Date.parse(new Date()); timeout: o.IpScanTimeOut
nodeArp.getMAC(generate_IP(), (err, mac) => { }).then(function (res) {
if (!err) { if (res.alive == true) {
if (o.debug) console.log('Searched IP: ' + generate_IP()); check_MAC();
if (mac.toUpperCase() == o.MAC.toUpperCase()) { return;
if (o.hint) console.log('wiot - ' + o.MAC + ': Found MAC from ' + o.ip + ' :: Method: node-arp'); }
setTimeout(reCheck_MAC, o.IpScanTimeOut*2); next_IP();
return; });
}
next_IP(); };
return;
} var check_MAC = () => {
next_IP(); o.LastConnectTime = Date.parse(new Date());
}); if (generate_IP() == o.localIP) {
}; next_IP();
return;
var reCheck_MAC = () => { }
nodeArp.getMAC(generate_IP(), (err, mac) => { nodeArp.getMac(generate_IP(), (err, mac) => {
if(!err){ mac = mac.replace(/-/g, ":");
if(o.debug) console.log('Checking IP: '+generate_IP()); if (!err) {
if(mac.toUpperCase() == o.MAC.toUpperCase()){
if (o.debug) console.log('Searched IP: ' + generate_IP());
if (mac.toUpperCase() == o.MAC.toUpperCase()) {
if (o.hint) console.log('wiot - ' + o.MAC + ': Found MAC from ' + o.ip + ' :: Method: macfromip');
setTimeout(reCheck_MAC, o.IpScanTimeOut * 2);
return;
}
next_IP();
return;
}
next_IP();
});
};
var reCheck_MAC = () => {
nodeArp.getMac(generate_IP(), (err, mac) => {
mac = mac.replace(/-/g, ":");
if (!err) {
if (o.debug) console.log('Checking IP: ' + generate_IP());
if (mac.toUpperCase() == o.MAC.toUpperCase()) {
o.ip = generate_IP(); o.ip = generate_IP();
if (o.hint) console.log('wiot - ' + o.MAC + ': Confirm MAC from ' + o.ip + ' :: Method: node-arp'); if (o.hint) console.log('wiot - ' + o.MAC + ': Confirm MAC from ' + o.ip + ' :: Method: macfromip');
lstn(); lstn();
setup(); setup();
return; return;
} }
next_IP(); next_IP();
return; return;
} }
next_IP(); next_IP();
}); });
} };
var generate_IP = () => { var generate_IP = () => {
return o.ip_range + '.' + ip_point; return o.ip_range + '.' + ip_point;
}; };
var next_IP = () => { var next_IP = () => {
if (ip_point >= 255) { if (ip_point >= 255) {
ip_point = 0; ip_point = 0;
setTimeout(ip_scan, o.MinResearchTime); setTimeout(ip_scan, o.MinResearchTime);
return; return;
} }
ip_point++; ip_point++;
ip_scan(); ip_scan();
} };
var get_sync_url = () => { var get_sync_url = () => {
var s = 'http://' + o.ip + '/sync?D1='; var s = 'http://' + o.ip + '/sync?D1=';
s += o.pinCmd.D1; s += o.pinCmd.D1;
s += '&D2='; s += '&D2=';
s += o.pinCmd.D2; s += o.pinCmd.D2;
s += '&D3='; s += '&D3=';
s += o.pinCmd.D3; s += o.pinCmd.D3;
s += '&D4='; s += '&D4=';
s += o.pinCmd.D4; s += o.pinCmd.D4;
s += '&D5='; s += '&D5=';
s += o.pinCmd.D5; s += o.pinCmd.D5;
s += '&D6='; s += '&D6=';
s += o.pinCmd.D6; s += o.pinCmd.D6;
s += '&D7='; s += '&D7=';
s += o.pinCmd.D7; s += o.pinCmd.D7;
s += '&D8='; s += '&D8=';
s += o.pinCmd.D8; s += o.pinCmd.D8;
return s; return s;
}; };
var getVersion = () => { var getVersion = () => {
if (o.isConnected) { if (o.isConnected) {
http_request('http://' + o.ip + '/getVersion', (res) => { http_request('http://' + o.ip + '/getVersion', (res) => {
o.version = res.version; o.version = res.version;
if (o.hint) { if (o.hint) {
console.log('wiot - ' + o.MAC + ': Version: ' + o.version); console.log('wiot - ' + o.MAC + ': Version: ' + o.version);
} }
}, getVersion); }, getVersion);
return; return;
} }
setTimeout(getVersion, o.errDelayTime); setTimeout(getVersion, o.errDelayTime);
}; };
async function getMAC() { async function getMAC() {
await arp.toIP(o.MAC).then((val) => { await arp.toIP(o.MAC).then((val) => {
if (val != null) { if (val != null) {
o.ip = val; o.ip = val;
} else if (ip == "default") { } else if (ip == "default") {
ip_scan(); ip_scan();
} return;
o.ip = val; }
if (o.debug) console.log('Found MAC: ' + o.MAC + ' from IP: ' + val + ' :: Method: arp-lookup'); if (o.debug) console.log('Found MAC: ' + o.MAC + ' from IP: ' + o.ip + ' :: Method: arp-lookup');
lstn(); lstn();
setup(); setup();
}, (err) => { }, (err) => {
if (o.debug) console.log(err); if (o.debug) console.log(err);
setTimeout(getMAC, o.errDelayTime); setTimeout(getMAC, o.errDelayTime);
}); });
} }
/* http functions */ /* http functions */
var http_error_callback = (callback = () => {}) => { var http_error_callback = (callback = () => {}) => {
callback(); callback();
}; };
var http_connected_callback = (callback = () => {}) => { var http_connected_callback = (callback = () => {}) => {
callback(); callback();
}; };
var http_ok = () => { var http_ok = () => {
setTimeout(core, o.okDelayTime); setTimeout(core, o.okDelayTime);
}; };
var http_error = () => { var http_error = () => {
setTimeout(core, o.errDelayTime); setTimeout(core, o.errDelayTime);
}; };
var http_update = () => { var http_update = () => {
http_request(get_sync_url(), http_update_success, http_update_err); http_request(get_sync_url(), http_update_success, http_update_err);
}; };
var http_update_success = (res) => { var http_update_success = (res) => {
o.data = res; o.data = res;
http_ok(); http_ok();
}; };
var http_update_err = () => { var http_update_err = () => {
http_error(); http_error();
}; };
var http_request = (url, callback = () => {}, err = () => {}) => { var http_request = (url, callback = () => {}, err = () => {}) => {
if (o.isConnected) { if (o.isConnected) {
o.LastTryTime = Date.parse(new Date()); o.LastTryTime = Date.parse(new Date());
http.get(url, (res) => { http.get(url, (res) => {
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', function (data) { res.on('data', function (data) {
if (IsJsonString(data)) { if (IsJsonString(data)) {
var dataObj = JSON.parse(data); var dataObj = JSON.parse(data);
callback(dataObj); callback(dataObj);
} else { } else {
err(e); err(e);
if (o.hint) console.log('wIoT - ' + o.MAC + ": err_" + o.ip + " - Not Stadnard JSON Response!!"); if (o.hint) console.log('wIoT - ' + o.MAC + ": err_" + o.ip + " - Not Stadnard JSON Response!!");
} }
o.LastConnectTime = Date.parse(new Date()); o.LastConnectTime = Date.parse(new Date());
}); });
}).on('error', function (e) { }).on('error', function (e) {
err(e); err(e);
if (o.hint) console.log('wIoT - ' + o.MAC + ": err_" + o.ip + " - Lost Connection!!"); if (o.hint) console.log('wIoT - ' + o.MAC + ": err_" + o.ip + " - Lost Connection!!");
}).end(); }).end();
} else { } else {
http_error(); http_error();
} }
}; };
/* pin Mode */ /* pin Mode */
var setPinMode = (pin, mode) => { var setPinMode = (pin, mode) => {
if (pin < 1 || pin > 8) throw "Illegal Pin Number!!"; if (pin < 1 || pin > 8) throw "Illegal Pin Number!!";
if (mode == o.INPUT_PULLUP || mode == 2) { if (mode == o.INPUT_PULLUP || mode == 2) {
mode = "INPUT_PULLUP"; mode = "INPUT_PULLUP";
} else if (mode == o.OUTPUT || mode == 1) { } else if (mode == o.OUTPUT || mode == 1) {
mode = "OUTPUT"; mode = "OUTPUT";
} else { } else {
mode = "INPUT"; mode = "INPUT";
} }
http_request('http://' + o.ip + '/pinMode?pin=' + pin + '&mode=' + mode); http_request('http://' + o.ip + '/pinMode?pin=' + pin + '&mode=' + mode);
}; };
var http_update_pin = () => { var http_update_pin = () => {
if (o.isConnected) { if (o.isConnected) {
http_request('http://' + o.ip + '/getPinMode', (res) => { http_request('http://' + o.ip + '/getPinMode', (res) => {
if (JSON.stringify(o.pin) != JSON.stringify(res)) { if (JSON.stringify(o.pin) != JSON.stringify(res)) {
for (var i in o.pin) { for (var i in o.pin) {
if (i.substr(0, 1) == "D") { if (i.substr(0, 1) == "D") {
setPinMode(i.substr(1, 1), o.pin[i]); setPinMode(i.substr(1, 1), o.pin[i]);
} else if (i.length == 1) { } else if (i.length == 1) {
setPinMode(i, o.pin[i]); setPinMode(i, o.pin[i]);
} }
} }
setTimeout(() => { setTimeout(() => {
http_request('http://' + o.ip + '/reset'); http_request('http://' + o.ip + '/reset');
}, o.resetDelayTime); }, o.resetDelayTime);
setTimeout(() => { setTimeout(() => {
core(); core();
}, o.resetDelayTime + o.errDelayTime); }, o.resetDelayTime + o.errDelayTime);
if (o.hint) console.log('wIoT - ' + o.MAC + ": Seting Pin Mode!! reset..."); if (o.hint) console.log('wIoT - ' + o.MAC + ": Seting Pin Mode!! reset...");
} }
setTimeout(() => { setTimeout(() => {
core(); core();
}, o.resetDelayTime + o.errDelayTime); }, o.resetDelayTime + o.errDelayTime);
}, () => { }, () => {
setTimeout(http_update_pin, o.errDelayTime); setTimeout(http_update_pin, o.errDelayTime);
}); });
} else { } else {
setTimeout(http_update_pin, o.errDelayTime); setTimeout(http_update_pin, o.errDelayTime);
} }
}; };
/* pin write */ /* pin write */
o.analogWrite = (pin, out, callback = () => {}, err = () => {}) => { o.analogWrite = (pin, out, callback = () => {}, err = () => {}) => {
if (!isNaN(pin)) pin = 'D' + pin; if (!isNaN(pin)) pin = 'D' + pin;
if (isNaN(out)) out = 0; if (isNaN(out)) out = 0;
if (out > 255 || out == "HIGH" || out == o.HIGH) out = 255; if (out > 255 || out == "HIGH" || out == o.HIGH) out = 255;
if (out < 0 || out == "LOW" || out == o.LOW) out = 0; if (out < 0 || out == "LOW" || out == o.LOW) out = 0;
if (o.hint && o.pinCmd[pin] != out) console.log('wIoT - ' + o.MAC + ': Write Value ' + out + ' to ' + pin); if (o.hint && o.pinCmd[pin] != out) console.log('wIoT - ' + o.MAC + ': Write Value ' + out + ' to ' + pin);
o.pinCmd[pin] = out; o.pinCmd[pin] = out;
}; };
o.digitalWrite = (pin, out, callback = () => {}, err = () => {}) => { o.digitalWrite = (pin, out, callback = () => {}, err = () => {}) => {
if (out == o.HIGH || out == "HIGH" || out == 1) { if (out == o.HIGH || out == "HIGH" || out == 1) {
out = 255; out = 255;
} else { } else {
out = 0; out = 0;
} }
o.analogWrite(pin, out, callback, err); o.analogWrite(pin, out, callback, err);
}; };
/* pin read and write */ /* pin read and write */
o.digitalRead = (pin) => { o.digitalRead = (pin) => {
if (!isNaN(pin)) pin = 'D' + pin; if (!isNaN(pin)) pin = 'D' + pin;
return o.data[pin]; return o.data[pin];
}; };
o.analogRead = (pin = "A0") => { o.analogRead = (pin = "A0") => {
if (!isNaN(pin)) pin = 'A' + pin; if (!isNaN(pin)) pin = 'A' + pin;
return o.data.A0; return o.data.A0;
}; };
o.read = function (pin) { o.read = function (pin) {
if (isNaN(pin)) { if (isNaN(pin)) {
if (pin.substr(0, 1) == "D") { if (pin.substr(0, 1) == "D") {
return o.digitalRead(pin); return o.digitalRead(pin);
} else { } else {
return o.analogRead(pin); return o.analogRead(pin);
} }
} else { } else {
if (pin > 0) { if (pin > 0) {
return o.digitalRead(pin); return o.digitalRead(pin);
} else { } else {
return o.analogRead(pin); return o.analogRead(pin);
} }
} }
}; };
o.write = (pin, out, callback = () => {}, err = () => {}) => { o.write = (pin, out, callback = () => {}, err = () => {}) => {
o.analogWrite(pin, out, callback, err); o.analogWrite(pin, out, callback, err);
}; };
o.ready = function () { o.ready = function () {
if (!o.isConnected || JSON.stringify(o.data) == JSON.stringify({})) { if (!o.isConnected || JSON.stringify(o.data) == JSON.stringify({})) {
return false; return false;
} }
return true; return true;
}; };
/* exc functions */ /* exc functions */
var ini = function () { var ini = function () {
if (o.hint) console.log('wiot - ' + o.MAC + ': init...'); if (o.hint) console.log('wiot - ' + o.MAC + ': init...');
//getMAC(); getLocalIp();
ip_scan(); getMAC();
}; //ip_scan();
};
async function lstn() {
setInterval(async () => { async function lstn() {
if (o.LastConnectTime + o.errDelayTime > Date.parse(new Date())) { setInterval(async () => {
o.isConnected = true; if (o.LastConnectTime + o.errDelayTime > Date.parse(new Date())) {
http_connected_callback(); o.isConnected = true;
return; http_connected_callback();
} return;
ping.promise.probe(o.ip, { }
timeout: o.pingTimeout ping.promise.probe(o.ip, {
}).then(function (res) { timeout: o.pingTimeout
if (o.isConnected != res.alive) { }).then(function (res) {
if (res.alive == true) { if (o.isConnected != res.alive) {
o.LastConnectTime = Date.parse(new Date()); if (res.alive == true) {
http_connected_callback(); o.LastConnectTime = Date.parse(new Date());
} else { http_connected_callback();
http_error_callback(); } else {
} http_error_callback();
} }
if (!res.alive && o.LastConnectTime + o.MaxToReScanTime < Date.parse(new Date())) { }
ini(); if (!res.alive && o.LastConnectTime + o.MaxToReScanTime < Date.parse(new Date())) {
} else if (res.alive && o.LastTryTime + o.noTryMaxTime < Date.parse(new Date())) { ini();
core(); } else if (res.alive && o.LastTryTime + o.noTryMaxTime < Date.parse(new Date())) {
} core();
o.isConnected = res.alive; }
if (o.debug) console.log('Exist: ' + res.alive + ' From IP: ' + o.ip); o.isConnected = res.alive;
if (o.debug) console.log('Exist: ' + res.alive + ' From IP: ' + o.ip);
});
});
}, o.IntervalTime);
}, o.IntervalTime);
};
};
var setup = () => {
var setup = () => {
if (o.isConnected) {
if (o.isConnected) {
getVersion();
http_update_pin(); getVersion();
return; http_update_pin();
} return;
}
setTimeout(setup, o.errDelayTime);
}; setTimeout(setup, o.errDelayTime);
};
var core = () => {
var core = () => {
http_update();
http_update();
if (!o.firstReady && o.ready()) {
o.on(); if (!o.firstReady && o.ready()) {
o.firstReady = 1; o.on();
if (o.hint) console.log('wIoT - ' + o.MAC + ': Connected!!'); o.firstReady = 1;
} if (o.hint) console.log('wIoT - ' + o.MAC + ': Connected!!');
if (o.debug) console.log(o.data); }
}; if (o.debug) console.log(o.data);
};
/* exc cmd */
ini(); /* exc cmd */
ini();
return o;
return o;
};
};
exports.client = wiot;
exports.client = wiot;

Loading…
Cancel
Save