ln.ethercat/ln.ethercat.service/www/static/js/ecapp.js

161 lines
4.3 KiB
JavaScript

class EthercatApplication
{
constructor(options){
this.state = { state: "N/A", slaves: [] };
this.processdata = [];
this.refresh_interval = 1000;
this.ac_sockets = [];
this.subscriptions = {};
this.subscribed = {
sdo: []
}
this.data = {
slaves: {
}
};
let pageURI = window.location;
let scheme = pageURI.scheme == "https" ? "wss:" : "ws:";
let host = pageURI.host;
this.base_url = scheme + "//" + host;
this.connectMainSocket();
}
connectMainSocket(){
this.socket = this.connectWebSocket("/api/v1/socket", true);
this.socket.onmessage = (evt)=>{
let message = JSON.parse(evt.data);
switch (message.event)
{
case "state":
this.applyState(message.value);
break;
case "pdo":
this.processdata = message.value;
break;
case "sdo":
this.subscribed.sdo = message.value;
break;
default:
//console.log("unknown event received: " + message.event);
break;
}
};
this.socket.onerror = (evt)=>{
console.log("weboscket error: ", evt);
this.socket.close();
};
this.socket.onclose = (evt)=>{
console.log("weboscket closed: ", evt);
if (evt.target == this.socket)
setTimeout(()=>this.connectMainSocket(), 1000);
};
}
connectWebSocket(path, keep){
let ws = new WebSocket(this.base_url + path);
if (!keep)
{
console.log("add to dispose list:", ws);
this.ac_sockets.push(ws);
}
return ws;
}
closeWebSockets(){
while (this.ac_sockets.length)
{
let ws = this.ac_sockets.pop();
console.log("disposing:", ws);
ws.close();
}
}
sendMessage(eventName, o){
this.socket.send(JSON.stringify({
event: eventName,
value: o
}));
}
applyState(state){
this.state = state;
}
POST(url, o){
return fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(o)
})
}
getSDOList(slave_id){
if (!this.data.slaves[slave_id])
this.data.slaves[slave_id] = {};
if (!this.data.slaves[slave_id].sdolist)
{
this.data.slaves[slave_id].sdolist = [];
fetch("/api/v1/slaves/" + slave_id + "/sdo")
.then((b) => {
b.json()
.then((json)=>{
json.forEach((sdo)=>{
this.data.slaves[slave_id].sdolist.push(sdo);
});
});
});
}
return this.data.slaves[slave_id].sdolist;
}
subscribe(slave, sdo_index){
slave = parseInt(slave);
if (!this.subscriptions[slave]) this.subscriptions[slave] = {};
if (!Object.keys(this.subscriptions[slave]).includes(sdo_index))
{
this.subscriptions[slave][sdo_index] = 1;
this.sendMessage("subscribe", [
{
Slave: slave,
Index: sdo_index,
SubIndex: 0,
},
]);
} else {
this.subscriptions[slave][sdo_index]++;
}
}
unsubscribe(slave, sdo_index){
slave = parseInt(slave);
if (this.subscriptions[slave] && Object.keys(this.subscriptions[slave]).includes(sdo_index))
{
this.subscriptions[slave][sdo_index]--;
if (!this.subscriptions[slave][sdo_index])
{
this.sendMessage("unsubscribe", [
{
Slave: slave,
Index: sdo_index,
SubIndex: 0,
},
]);
}
}
}
requestState(slave_id, state){
this.POST("/api/v1/slaves/" + slave_id + "/state", { state });
}
}