-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpenEPaperLink-Websocket
199 lines (181 loc) · 6.34 KB
/
OpenEPaperLink-Websocket
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
const serverIP = '192.168.X.XX'; //z.B. 192.168.10.71
/// AB HIER NICHTS MEHR ÄNDERN!
const WebSocket = require('ws');
const http = require('http');
const https = require('https');
const wsUrl = `ws://${serverIP}/ws`; // WebSocket-URL
let ws;
let pingInterval;
function ensureOpenEPaperLinkFolderExists(callback) {
const OpenEPaperLinkFolderPath = '0_userdata.0.OpenEPaperLink';
getObject(OpenEPaperLinkFolderPath, (err, obj) => {
if (err || !obj) {
setObject(OpenEPaperLinkFolderPath, {
type: 'channel',
common: { name: 'Open E-Paper Link' },
native: {}
}, callback);
} else {
callback();
}
});
}
function ensureChannelExists(path, alias, callback) {
getObject(path, (err, obj) => {
if (err || !obj) {
setObject(path, {
type: 'channel',
common: { name: alias || 'Unbekanntes Gerät' },
native: {}
}, callback);
} else if (obj.common.name !== alias) {
extendObject(path, { common: { name: alias } }, callback);
} else {
callback();
}
});
}
function createStateAndSet(statePath, value) {
setObject(statePath, {
type: 'state',
common: {
name: statePath.split('.').pop(),
type: 'string',
role: 'value',
read: true,
write: true
},
native: {}
}, (err) => {
if (!err) {
setState(statePath, String(value), true);
}
});
}
function updateStateIfChanged(statePath, value) {
getState(statePath, (err, state) => {
if (err || !state) {
createStateAndSet(statePath, String(value));
} else if (state.val !== String(value)) {
setState(statePath, String(value), true);
}
});
}
function fetchDimensions(hwType, callback) {
const hwTypeHex = hwType.toString(16).padStart(2, '0').toUpperCase(); // Convert hwType to two-digit uppercase hexadecimal
const url = `http://${serverIP}/tagtypes/${hwTypeHex}.json`;
http.get(url, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
if (res.statusCode === 200) {
try {
const dimensions = JSON.parse(data);
callback(null, dimensions);
} catch (e) {
callback(`Error parsing JSON from ${url}: ${e}`);
}
} else {
fetchFromGithub(hwTypeHex, callback);
}
});
}).on('error', (err) => {
fetchFromGithub(hwTypeHex, callback);
});
}
function fetchFromGithub(hwTypeHex, callback) {
const githubUrl = `https://github.com/OpenEPaperLink/OpenEPaperLink/tree/master/resources/tagtypes/${hwTypeHex}.json`;
https.get(githubUrl, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
if (res.statusCode === 200) {
try {
const dimensions = JSON.parse(data);
callback(null, dimensions);
} catch (e) {
callback(`Error parsing JSON from ${githubUrl}: ${e}`);
}
} else {
callback(`HTTP Error ${res.statusCode} from ${githubUrl}`);
}
});
}).on('error', (err) => {
callback(`Error fetching ${githubUrl}: ${err.message}`);
});
}
function handleHWType(basePath, hwType) {
createStateAndSet(`${basePath}.hwType`, String(hwType)); // Save hwType as a state
fetchDimensions(hwType, (err, dimensions) => {
if (!err && dimensions) {
createStateAndSet(`${basePath}.height`, String(dimensions.height));
createStateAndSet(`${basePath}.width`, String(dimensions.width));
createStateAndSet(`${basePath}.name`, String(dimensions.name));
if (dimensions.colors) {
createStateAndSet(`${basePath}.colors`, String(dimensions.colors));
}
if (dimensions.colortable) {
createStateAndSet(`${basePath}.colortable`, JSON.stringify(dimensions.colortable));
}
} else {
console.error(`Failed to fetch or set dimensions for hwType ${hwType}: ${err}`);
}
});
}
function connectWebSocket() {
ws = new WebSocket(wsUrl);
ws.on('open', function open() {
console.log('Verbunden mit WebSocket');
startHeartbeat();
});
ws.on('message', function incoming(data) {
console.log('Daten empfangen:', data);
if (data) {
try {
let parsedData = JSON.parse(data);
console.log('Verarbeitete Daten:', JSON.stringify(parsedData, null, 2));
handleData(parsedData);
} catch (err) {
console.error('Fehler bei der Verarbeitung der Daten:', err);
}
} else {
console.log('Keine Daten oder leere Nachricht empfangen');
}
});
ws.on('close', function close() {
console.log('WebSocket-Verbindung geschlossen, versuche neu zu verbinden...');
clearInterval(pingInterval);
setTimeout(connectWebSocket, 5000);
});
ws.on('error', function error(err) {
console.error('WebSocket-Fehler:', err);
});
}
function startHeartbeat() {
pingInterval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.ping(() => console.log('Ping sent'));
}
}, 10000); // Send ping every 10 seconds
ws.on('pong', () => {
console.log('Pong received');
});
}
function handleData(parsedData) {
if (parsedData.tags && Array.isArray(parsedData.tags)) {
parsedData.tags.forEach(tag => {
let basePath = `0_userdata.0.OpenEPaperLink.${tag.mac.replace(/:/g, '')}`;
ensureChannelExists(basePath, tag.alias, () => {
Object.keys(tag).forEach(key => {
let statePath = `${basePath}.${key}`;
let value = tag[key];
updateStateIfChanged(statePath, value);
if (key === 'hwType') {
handleHWType(basePath, tag.hwType);
}
});
});
});
}
}
connectWebSocket();