фрагмент отправки в loop
void loop() {
ws.cleanupClients();
static unsigned long last = 0;
if (millis() - last > 2000) {
last = millis();
// cheek register СВ4021, contact with rezistors 1,5kOm
digitalWrite(LATCHPIN, 1);
delayMicroseconds(20);
digitalWrite(LATCHPIN, 0);
//--- 1 register СВ4021
switchVar1 = shiftIn(DATAPIN, CLOCKPIN);
for (int n = 0; n <= 7; n++) {
if (switchVar1 & (1 << n)) { // array[0-7]
ws.textAll(String("P=") + "1"); //nclose
} else {
ws.textAll(String("P=") + "0"); //nopen
}
}
//--- 2 register СВ4021
switchVar2 = shiftIn(DATAPIN, CLOCKPIN);
for (int n = 0; n <= 7; n++) {
if (switchVar2 & (1 << n)) { // array[7-15]
ws.textAll(String("P=") + "1"); //nclose
} else {
ws.textAll(String("P=") + "0"); //nopen
}
}
updateSensors();
ws.textAll(String("TEMP:") + tempC);
ws.textAll(String("HUMID:") + byte(humidity));
ws.textAll(String("SENSOR:") + byte(sensor));
}
}
код js на сервере
<script>
let ws = null,
timer = null;
const $s = document.getElementById('status')
const $c = document.getElementById('conn')
const $d = document.getElementById('sensor')
const $b = document.getElementById('btn')
const $t = document.getElementById('temp')
const $h = document.getElementById('humidity')
const $p = document.getElementById('pin_')
function setConn(x) {
$c.textContent = x ? 'подключено' : 'отключено';
$c.style.color = x ? 'green' : 'red'
}
function reconnect() {
if (timer) return;
timer = setTimeout(() => {
timer = null;
connect()
}, 2000)
}
function connect() {
try {
ws = new WebSocket('ws://' + window.location.host + '/ws');
} catch (e) {
reconnect();
return;
}
ws.onopen = () => setConn(true);
ws.onmessage = e => {
const m = e.data || '';
if (m === 'ON') {
$s.className = 'status on';
$s.textContent = 'Светодиод включён';
} else if (m === 'OFF') {
$s.className = 'status off';
$s.textContent = 'Светодиод выключён';
} else if (m.startsWith('SENSOR:')) {
$d.textContent = m.split(':')[1];
} else if (m.startsWith('TEMP:')) {
$t.textContent = m.split(':')[1];
} else if (m.startsWith('HUMID:')) {
$h.textContent = m.split(':')[1];
}
};
ws.onclose = () => {
setConn(false);
$s.className = 'status off';
$s.textContent = 'Соединение потеряно';
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
reconnect();
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
}
$b.addEventListener('click', () => {
if (ws && ws.readyState === WebSocket.OPEN) ws.send('TOGGLE');
else alert('Нет соединения')
});
connect();
</script>

