Skip to content

Commit 8610ec3

Browse files
committed
Many fixes
1 parent f7dc6a7 commit 8610ec3

File tree

4 files changed

+67
-111
lines changed

4 files changed

+67
-111
lines changed

arduino-cloud-api.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const apiProperties = new ArduinoIotClient.PropertiesV2Api(client);
2828
const apiSeries = new ArduinoIotClient.SeriesV2Api(client);
2929
const apiThings = new ArduinoIotClient.ThingsV2Api(client);
3030

31-
class arduinClientHttp {
31+
class ArduinClientHttp {
3232
constructor(token) {
3333
this.token = token;
3434

@@ -74,4 +74,4 @@ class arduinClientHttp {
7474
return apiSeries.seriesV2BatchQueryRaw(body);
7575
}
7676
}
77-
exports.arduinClientHttp = arduinClientHttp;
77+
exports.ArduinClientHttp = ArduinClientHttp;

arduino-cloud.js

Lines changed: 46 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,28 @@ module.exports = function (RED) {
1111
if (connectionConfig && config.thing !== "" && config.thing !== "0" && config.property !== "" && config.property !== "0") {
1212
try {
1313

14-
this.arduinoClient = await connectionManager.getClientMqtt(connectionConfig);
1514
this.thing = config.thing;
1615
this.propertyId = config.property;
17-
this.propertyName = config.name;
18-
await this.arduinoClient.onPropertyValue( this.thing, this.propertyName, this.update);
19-
20-
this.on('close', function(done) {
21-
connectionManager.deleteClientMqtt(connectionConfig.credentials.clientid, this.propertyName).then(() =>{done();});
16+
this.propertyName = config.propname;
17+
this.arduinoClient = await connectionManager.getClientMqtt(connectionConfig);
18+
if (this.arduinoClient && this.arduinoClient.connection.isConnected()) {
19+
await this.arduinoClient.onPropertyValue(this.thing, this.propertyName, (msg) => {
20+
this.send(
21+
{
22+
topic: this.propertyName,
23+
payload: msg,
24+
timestamp: (new Date()).getTime()
25+
}
26+
);
27+
const s = getStatus(msg);
28+
if (s != undefined)
29+
this.status({ fill: "grey", shape: "dot", text: s });
30+
else
31+
this.status({});
32+
});
33+
}
34+
this.on('close', function (done) {
35+
connectionManager.deleteClientMqtt(connectionConfig.credentials.clientid, this.thing, this.propertyName).then(() => { done(); });
2236
});
2337

2438
//this.poll(connectionConfig);
@@ -29,46 +43,6 @@ module.exports = function (RED) {
2943
}
3044
realConstructor.apply(this, [config]);
3145
}
32-
ArduinoIotInput.prototype = {
33-
/*poll: async function (connectionConfig) {
34-
try {
35-
await connectionManager.connect(connectionConfig);
36-
const property = await this.arduinoRestClient.getProperty(this.thing, this.propertyId);
37-
if (typeof (property.last_value) !== "object" && property.last_value !== this.lastValue ||
38-
typeof (property.last_value) === "object" && !_.isEqual(property.last_value, this.lastValue)
39-
) {
40-
this.send(
41-
{
42-
topic: property.name,
43-
payload: property.last_value,
44-
timestamp: property.value_updated_at
45-
}
46-
);
47-
const s = getStatus(property.last_value);
48-
if (s != undefined)
49-
this.status({ fill: "grey", shape: "dot", text: s });
50-
else
51-
this.status({});
52-
this.lastValue = property.last_value;
53-
}
54-
55-
this.pollTimeout = setTimeout(() => { this.poll(connectionConfig) }, 1000);
56-
} catch (err) {
57-
this.status({ fill: "red", shape: "dot", text: "Error getting value" });
58-
console.log(err);
59-
}
60-
}*/
61-
update: function (msg){
62-
var date = new Date();
63-
this.send(
64-
{
65-
topic: this.propertyName,
66-
payload: msg,
67-
timestamp: date.getTime()
68-
}
69-
);
70-
}
71-
}
7246
RED.nodes.registerType("property in", ArduinoIotInput);
7347

7448
function ArduinoIotOutput(config) {
@@ -96,7 +70,7 @@ module.exports = function (RED) {
9670
this.status({ fill: "red", shape: "dot", text: "Error setting value" });
9771
}
9872
});
99-
this.on('close', function() {
73+
this.on('close', function () {
10074
connectionManager.deleteClientHttp(connectionConfig.credentials.clientid);
10175
});
10276
}
@@ -127,7 +101,7 @@ module.exports = function (RED) {
127101
const now = moment();
128102
const end = now.format();
129103
const count = this.timeWindowCount
130-
if(count !== null && count !== "" && count !== undefined && Number.isInteger(parseInt(count)) && parseInt(count) !== 0) {
104+
if (count !== null && count !== "" && count !== undefined && Number.isInteger(parseInt(count)) && parseInt(count) !== 0) {
131105
const start = now.subtract(count * this.timeWindowUnit, 'second').format();
132106

133107
const result = await this.arduinoRestClient.getSeries(this.thing, this.propertyId, start, end);
@@ -154,7 +128,7 @@ module.exports = function (RED) {
154128
}
155129
});
156130

157-
this.on('close', function() {
131+
this.on('close', function () {
158132
connectionManager.deleteClientHttp(connectionConfig.credentials.clientid);
159133
});
160134
}
@@ -182,11 +156,11 @@ module.exports = function (RED) {
182156
this.propertyId = config.property;
183157
this.propertyName = config.name;
184158
const pollTime = this.timeWindowCount * this.timeWindowUnit;
185-
if(pollTime !== null && pollTime !== "" && pollTime !== undefined && Number.isInteger(parseInt(pollTime)) && parseInt(pollTime) !== 0) {
159+
if (pollTime !== null && pollTime !== "" && pollTime !== undefined && Number.isInteger(parseInt(pollTime)) && parseInt(pollTime) !== 0) {
186160
this.poll(connectionConfig, pollTime);
187161
this.on('close', function () {
188162
connectionManager.deleteClientHttp(connectionConfig.credentials.clientid);
189-
if(this.pollTimeoutPoll)
163+
if (this.pollTimeoutPoll)
190164
clearTimeout(this.pollTimeoutPoll);
191165

192166
});
@@ -282,69 +256,48 @@ module.exports = function (RED) {
282256
}
283257
});
284258

285-
RED.httpAdmin.get("/things", RED.auth.needsPermission('Property-in.read'), async function (req, res) {
259+
async function getThingsOrProperties(req, res, thingsOrProperties) {
260+
let arduinoRestClient;
286261
try {
287262
if (req.query.clientid || req.query.clientsecret) {
288-
await connectionManager.connect(
289-
{
290-
credentials: {
291-
clientid: req.query.clientid,
292-
clientsecret: req.query.clientsecret
293-
}
263+
arduinoRestClient = await connectionManager.getClientHttp({
264+
credentials: {
265+
clientid: req.query.clientid,
266+
clientsecret: req.query.clientsecret
294267
}
295-
);
268+
});
296269
} else if (req.query.connectionid) {
297270
const connectionConfig = RED.nodes.getNode(req.query.connectionid);
298271
if (!connectionConfig) {
299272
console.log("No credentials available.");
300273
return res.send(JSON.stringify({ error: "No credentials available." }));
301274
}
302-
await connectionManager.connect(connectionConfig);
275+
arduinoRestClient = await connectionManager.getClientHttp(connectionConfig);
303276
} else {
304277
console.log("No credentials available.");
305278
return res.send(JSON.stringify({ error: "No credentials available." }));
306279
}
307-
const arduinoRestClient = connectionManager.apiRest;
308-
const things = await arduinoRestClient.getThings();
309-
return res.send(JSON.stringify(things));
280+
if (thingsOrProperties === "things") {
281+
return res.send(JSON.stringify(await arduinoRestClient.getThings()));
282+
} else if (thingsOrProperties === "properties") {
283+
const thing_id = req.query.thing_id;
284+
return res.send(JSON.stringify(await arduinoRestClient.getProperties(thing_id)));
285+
} else {
286+
console.log("Wrong parameter in getThingsOrProperties.");
287+
return res.send(JSON.stringify({ error: "Wrong parameter in getThingsOrProperties." }));
288+
}
310289
} catch (err) {
311290
console.log(`Status: ${err.status}, message: ${err.error}`);
312291
return res.send(JSON.stringify({ error: "Wrong credentials or system unavailable." }));
313292
}
293+
}
294+
RED.httpAdmin.get("/things", RED.auth.needsPermission('Property-in.read'), async function (req, res) {
295+
return getThingsOrProperties(req, res, "things");
314296
});
315297

316298
RED.httpAdmin.get("/properties", RED.auth.needsPermission('Property-in.read'), async function (req, res) {
317-
try {
318-
if (req.query.clientid && req.query.clientsecret) {
319-
await connectionManager.connect(
320-
{
321-
credentials: {
322-
clientid: req.query.clientid,
323-
clientsecret: req.query.clientsecret
324-
}
325-
}
326-
);
327-
} else if (req.query.connectionid) {
328-
const connectionConfig = RED.nodes.getNode(req.query.connectionid);
329-
if (!connectionConfig)
330-
return res.send(JSON.stringify([]));
331-
await connectionManager.connect(connectionConfig);
332-
} else {
333-
console.log("No credentials available.");
334-
return res.send(JSON.stringify([]));
335-
}
336-
const ArduinoRestClient = connectionManager.apiRest;
337-
const thing_id = req.query.thing_id;
338-
const properties = await ArduinoRestClient.getProperties(thing_id);
339-
return res.send(JSON.stringify(properties));
340-
} catch (err) {
341-
console.log(`Status: ${err.status}, message: ${err.error}`);
342-
return res.send({ error: "Wrong credentials or system unavailable." });
343-
}
299+
return getThingsOrProperties(req, res, "properties");
344300
});
345-
346-
347-
348301
}
349302

350303
function getStatus(value) {

arduino-connection-manager.js

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const request = require("async-request");
2-
const arduinClientHttp = require('./arduino-cloud-api');
2+
const ArduinClientHttp = require('./arduino-cloud-api');
33
const ArduinoClientMqtt = require ('./arduino-iot-client-mqtt');
44
//import { mqttClient } from './arduino-connection-manager_old';
55
const accessTokenUri = process.env.NODE_RED_ACCESS_TOKEN_URI || 'https://login.arduino.cc/oauth/token';
@@ -52,12 +52,12 @@ async function getClientMqtt(connectionConfig){
5252
throw new Error("Cannot find cooonection config or credentials.");
5353
}
5454
try{
55-
var user = findUser(clientId);
56-
var clientMqtt;
55+
let user = findUser(connectionConfig.credentials.clientid);
56+
let clientMqtt;
5757
if(user === -1){
5858

59-
clientMqtt = new ArduinoClientMqtt();
60-
var tokenInfo = await getToken(connectionConfig);
59+
clientMqtt = new ArduinoClientMqtt.ArduinoClientMqtt();
60+
const tokenInfo = await getToken(connectionConfig);
6161
if(tokenInfo !==undefined){
6262
const ArduinoCloudOptions = {
6363
host: "wss.iot.oniudra.cc",
@@ -70,7 +70,7 @@ async function getClientMqtt(connectionConfig){
7070
useCloudProtocolV2: true
7171
};
7272
await clientMqtt.connect(ArduinoCloudOptions);
73-
var timeout = setTimeout(() => { updateToken(connectionConfig) }, tokenInfo.expires_in * 1000);
73+
const timeout = setTimeout(() => { updateToken(connectionConfig) }, tokenInfo.expires_in * 1000);
7474
connections.push({
7575
clientId: connectionConfig.credentials.clientid,
7676
connectionConfig: connectionConfig,
@@ -80,13 +80,15 @@ async function getClientMqtt(connectionConfig){
8080
clientHttp: null,
8181
timeoutUpdateToken: timeout
8282
});
83+
} else {
84+
// TODO: what happens when token is undefined?
85+
clientMqtt = undefined;
8386
}
84-
8587
} else{
8688
if(connections[user].clientMqtt !== null){
8789
clientMqtt = connections[user].clientMqtt;
8890
}else{
89-
clientMqtt = new ArduinoClientMqtt();
91+
clientMqtt = new ArduinoClientMqtt.ArduinoClientMqtt();
9092
const ArduinoCloudOptions = {
9193
host: "wss.iot.oniudra.cc",
9294
token: connections[user].token,
@@ -113,13 +115,13 @@ async function getClientHttp(connectionConfig){
113115
throw new Error("Cannot find cooonection config or credentials.");
114116
}
115117
try{
116-
var user = findUser(clientId);
118+
var user = findUser(connectionConfig.credentials.clientid);
117119
var clientHttp;
118120
if(user === -1){
119121

120122
var tokenInfo = await getToken(connectionConfig);
121123
if(tokenInfo !==undefined){
122-
clientHttp= new arduinClientHttp(tokenInfo.token);
124+
clientHttp= new ArduinClientHttp.ArduinClientHttp(tokenInfo.token);
123125
var timeout = setTimeout(() => { updateToken(connectionConfig) }, tokenInfo.expires_in * 1000);
124126
connections.push({
125127
clientId: connectionConfig.credentials.clientid,
@@ -137,7 +139,7 @@ async function getClientHttp(connectionConfig){
137139
if(connections[user].clientHttp !== null){
138140
clientHttp = connections[user].clientHttp;
139141
}else{
140-
clientHttp = new arduinClientHttp(connections[user].token);
142+
clientHttp = new ArduinClientHttp.ArduinClientHttp(connections[user].token);
141143

142144
connections[user].clientHttp=clientHttp;
143145
}
@@ -176,11 +178,12 @@ async function updateToken(connectionConfig){
176178
}
177179
}
178180

179-
async function deleteClientMqtt(clientId, propertyName ){
181+
async function deleteClientMqtt(clientId, thing, propertyName ){
180182
var user = findUser(clientId);
181183
if(user !== -1){
182184
if(connections[user].clientMqtt !== null){
183-
var ret = await connections[user].clientMqtt.removePropertyValueCallback(clientId, propertyName);
185+
var ret = await connections[user].clientMqtt.removePropertyValueCallback(thing, propertyName);
186+
// TODO: NOT CLEAR WHAT FOLLOWS. SHOULD BE -1 INSTEAD OF 0 ?
184187
if(ret === 0){
185188
await connections[user].clientMqtt.disconnect();
186189
delete connections[user].clientMqtt;

arduino-iot-client-mqtt.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ const arduinoCloudPort = 8443;
5454
const arduinoCloudHost = 'wss.iot.arduino.cc';
5555
const arduinoAuthURL = 'https://auth.arduino.cc';
5656

57-
class clientMqtt{
57+
class ArduinoClientMqtt{
5858
constructor(){
5959
this.connection = null;
6060
this.connectionOptions = null;
@@ -600,7 +600,7 @@ class clientMqtt{
600600
if (!this.propertyCallback[propOutputTopic]) {
601601
this.propertyCallback[propOutputTopic] = {};
602602
this.propertyCallback[propOutputTopic][name] = cb;
603-
return subscribe(propOutputTopic, cb);
603+
return this.subscribe(propOutputTopic, cb);
604604
}
605605

606606
if (this.propertyCallback[propOutputTopic] && !this.propertyCallback[propOutputTopic][name]) {
@@ -623,4 +623,4 @@ class clientMqtt{
623623
};
624624
}
625625

626-
exports.clientMqtt = clientMqtt;
626+
exports.ArduinoClientMqtt = ArduinoClientMqtt;

0 commit comments

Comments
 (0)