Newer
Older
import * as os from "os";
import * as std from "std";
import { WebSocket } from "/usr/lib/quickjs/websocket.js";
class AsyncClient {
constructor() {
globalThis.WebSocket = WebSocket;
// paho-mqtt requires setTimeout and clearTimeout in global scope
globalThis.setTimeout = os.setTimeout;
globalThis.clearTimeout = function (timeout) {
if (timeout) {
os.clearTimeout(timeout);
}
};
globalThis.global = globalThis;
std.loadScript("/usr/lib/usp-js/lib/protobuf.min.js");
std.loadScript("/usr/lib/usp-js/lib/paho-mqtt.min.js");
protobuf.Root.prototype.fetch = function (filename, callback) {
os.setTimeout(function () {
const data = std.loadFile(filename);
if (data === null) {
console.log("failed to load file: " + filename);
callback(new Error("failed to load file: " + filename));
} else {
//console.log(`data loaded for ${filename}`)
callback(null, data);
}
}, 0);
};
}
async connectAsync(
host = "localhost",
port = 9001,
user = "admin",
password = "admin",
clientId = "proto::interop-usp-controller"
) {
this.client = new Paho.Client(
host,
port,
"/mqtt",
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
);
const opts = {
userName: user,
password: password,
};
const client = this.client;
const connectPromise = new Promise(function (resolve, reject) {
opts.onFailure = function (err) {
reject(new Error(err.errorMessage));
};
opts.onSuccess = function () {
resolve(client);
};
client.connect(opts);
});
this.client = await connectPromise;
// this.client.subscribe('/usp/controller/#')
return this;
}
async subscribe(id) {
this.client.subscribe(id);
}
async unsubscribe(id) {
this.client.unsubscribe(id);
}
async on(msg, callback) {
if (msg === "message") {
this.client.onMessageArrived = function (msg) {
callback(msg.payloadBytes);
};
} else if (msg === "error") {
// there is no erro handling in paho mqtt
this.client.onConnectionLost = function (responseObject) {
callback(responseObject);
console.log("USP Disconnected: ", responseObject.errorMessage);
};
}
}
async publish(topic, msg) {
this.client.send(topic, msg);
}
async end() {
this.client.disconnect();
}
}
async function main() {
const client = new AsyncClient();
await client.connect();
}
const mqttAsync = new AsyncClient();
export default mqttAsync;