Compare commits
2 Commits
65d4ff7b62
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34a243ec02 | ||
|
|
7478cdffce |
@@ -7,6 +7,7 @@ const CIRC = 2 * Math.PI * 52; // ~326.73
|
|||||||
const glow = document.getElementById('glow');
|
const glow = document.getElementById('glow');
|
||||||
const durInput = document.getElementById('dur-input');
|
const durInput = document.getElementById('dur-input');
|
||||||
const btnRun = document.getElementById('btn-run');
|
const btnRun = document.getElementById('btn-run');
|
||||||
|
const btnLearn = document.getElementById('btn-learn');
|
||||||
const btnOpen = document.getElementById('btn-open');
|
const btnOpen = document.getElementById('btn-open');
|
||||||
const btnClose = document.getElementById('btn-close');
|
const btnClose = document.getElementById('btn-close');
|
||||||
|
|
||||||
@@ -45,10 +46,25 @@ const CIRC = 2 * Math.PI * 52; // ~326.73
|
|||||||
if (durInput.value !== String(secs)) durInput.value = secs;
|
if (durInput.value !== String(secs)) durInput.value = secs;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Disable controls while timer is running
|
// Disable controls while timer is running or learning
|
||||||
const running = state.timerActive;
|
const running = state.timerActive;
|
||||||
btnRun.disabled = running;
|
const learning = state.countMode;
|
||||||
durInput.disabled = running;
|
btnRun.disabled = running || learning;
|
||||||
|
durInput.disabled = running || learning;
|
||||||
|
btnOpen.disabled = running || learning;
|
||||||
|
btnClose.disabled = running || learning;
|
||||||
|
|
||||||
|
// Learn button toggles label and action
|
||||||
|
if (learning) {
|
||||||
|
btnLearn.textContent = '⏹ Stop Learn';
|
||||||
|
btnLearn.onclick = doStopLearn;
|
||||||
|
btnLearn.classList.add('active-learn');
|
||||||
|
} else {
|
||||||
|
btnLearn.textContent = '📐 Learn';
|
||||||
|
btnLearn.onclick = doLearn;
|
||||||
|
btnLearn.classList.remove('active-learn');
|
||||||
|
}
|
||||||
|
btnLearn.disabled = running; // can't start learn while timer runs
|
||||||
|
|
||||||
if (state.timerActive && state.timerStartedAt && state.timerEndsAt) {
|
if (state.timerActive && state.timerStartedAt && state.timerEndsAt) {
|
||||||
const total = state.timerEndsAt - state.timerStartedAt;
|
const total = state.timerEndsAt - state.timerStartedAt;
|
||||||
@@ -64,9 +80,12 @@ const CIRC = 2 * Math.PI * 52; // ~326.73
|
|||||||
badgeTxt.textContent = 'Timer Running';
|
badgeTxt.textContent = 'Timer Running';
|
||||||
glow.classList.add('active');
|
glow.classList.add('active');
|
||||||
} else if (state.countMode) {
|
} else if (state.countMode) {
|
||||||
|
const elapsed = state.countStart
|
||||||
|
? Math.max(0, (Date.now() + serverOffset) - state.countStart)
|
||||||
|
: 0;
|
||||||
ring.style.strokeDashoffset = CIRC;
|
ring.style.strokeDashoffset = CIRC;
|
||||||
cd.textContent = '⏱';
|
cd.textContent = fmt(elapsed);
|
||||||
cd.className = 'countdown idle';
|
cd.className = 'countdown';
|
||||||
label.textContent = 'LEARNING';
|
label.textContent = 'LEARNING';
|
||||||
badge.className = 'badge counting';
|
badge.className = 'badge counting';
|
||||||
badgeTxt.textContent = 'Count Mode';
|
badgeTxt.textContent = 'Count Mode';
|
||||||
@@ -192,6 +211,10 @@ const CIRC = 2 * Math.PI * 52; // ~326.73
|
|||||||
function doOpen() { apiPost('/api/open'); }
|
function doOpen() { apiPost('/api/open'); }
|
||||||
function doClose() { apiPost('/api/close'); }
|
function doClose() { apiPost('/api/close'); }
|
||||||
|
|
||||||
|
async function doLearn() { await apiPost('/api/learn'); }
|
||||||
|
async function doStopLearn() { await apiPost('/api/stop-learn'); }
|
||||||
|
|
||||||
|
|
||||||
// Also save duration on Enter or blur
|
// Also save duration on Enter or blur
|
||||||
durInput.addEventListener('change', () => {
|
durInput.addEventListener('change', () => {
|
||||||
const secs = parseInt(durInput.value, 10);
|
const secs = parseInt(durInput.value, 10);
|
||||||
@@ -199,3 +222,50 @@ const CIRC = 2 * Math.PI * 52; // ~326.73
|
|||||||
apiPost('/api/duration', { seconds: secs });
|
apiPost('/api/duration', { seconds: secs });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── Button online status ──
|
||||||
|
const deviceDot = document.getElementById('device-dot');
|
||||||
|
const deviceState = document.getElementById('device-state');
|
||||||
|
const valveDot = document.getElementById('valve-dot');
|
||||||
|
const valveState = document.getElementById('valve-state');
|
||||||
|
|
||||||
|
function updateDeviceWidget(dot, stateEl, online) {
|
||||||
|
if (online === true) {
|
||||||
|
dot.className = 'device-dot online';
|
||||||
|
stateEl.className = 'device-state online';
|
||||||
|
stateEl.textContent = 'Online';
|
||||||
|
} else if (online === false) {
|
||||||
|
dot.className = 'device-dot offline';
|
||||||
|
stateEl.className = 'device-state offline';
|
||||||
|
stateEl.textContent = 'Offline';
|
||||||
|
} else {
|
||||||
|
dot.className = 'device-dot';
|
||||||
|
stateEl.className = 'device-state';
|
||||||
|
stateEl.textContent = 'Unknown';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pollButtonOnline() {
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/button-online');
|
||||||
|
const d = await r.json();
|
||||||
|
updateDeviceWidget(deviceDot, deviceState, d.online);
|
||||||
|
} catch {
|
||||||
|
updateDeviceWidget(deviceDot, deviceState, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pollValveOnline() {
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/valve-online');
|
||||||
|
const d = await r.json();
|
||||||
|
updateDeviceWidget(valveDot, valveState, d.online);
|
||||||
|
} catch {
|
||||||
|
updateDeviceWidget(valveDot, valveState, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pollButtonOnline();
|
||||||
|
pollValveOnline();
|
||||||
|
setInterval(pollButtonOnline, 10000);
|
||||||
|
setInterval(pollValveOnline, 10000);
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
|
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
|
||||||
|
|
||||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
--bg: #0a0e1a;
|
--bg: #0a0e1a;
|
||||||
@@ -151,8 +155,15 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@keyframes pulse-dot {
|
@keyframes pulse-dot {
|
||||||
0%, 100% { opacity: 1; }
|
|
||||||
50% { opacity: 0.4; }
|
0%,
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
50% {
|
||||||
|
opacity: 0.4;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Info row ── */
|
/* ── Info row ── */
|
||||||
@@ -263,6 +274,23 @@
|
|||||||
border-color: var(--red);
|
border-color: var(--red);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.btn.warning {
|
||||||
|
border-color: rgba(245, 158, 11, 0.35);
|
||||||
|
color: var(--orange);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn.warning:hover {
|
||||||
|
background: rgba(245, 158, 11, 0.15);
|
||||||
|
border-color: var(--orange);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn.warning.active-learn {
|
||||||
|
background: var(--orange);
|
||||||
|
border-color: transparent;
|
||||||
|
color: #000;
|
||||||
|
animation: pulse-dot 1s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
.btn.success {
|
.btn.success {
|
||||||
border-color: rgba(34, 197, 94, 0.3);
|
border-color: rgba(34, 197, 94, 0.3);
|
||||||
}
|
}
|
||||||
@@ -306,10 +334,104 @@
|
|||||||
text-align: right;
|
text-align: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dur-input::-webkit-inner-spin-button { opacity: 0.3; }
|
.dur-input::-webkit-inner-spin-button {
|
||||||
|
opacity: 0.3;
|
||||||
|
}
|
||||||
|
|
||||||
.dur-unit {
|
.dur-unit {
|
||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
color: var(--text-dim);
|
color: var(--text-dim);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Device Status Widgets ── */
|
||||||
|
.devices-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.6rem;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-status {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.9rem;
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 16px;
|
||||||
|
padding: 0.7rem 1.2rem;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-icon-wrap {
|
||||||
|
position: relative;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-icon {
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
object-fit: contain;
|
||||||
|
border-radius: 10px;
|
||||||
|
display: block;
|
||||||
|
filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-dot {
|
||||||
|
position: absolute;
|
||||||
|
bottom: -3px;
|
||||||
|
right: -3px;
|
||||||
|
width: 13px;
|
||||||
|
height: 13px;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 2px solid var(--bg);
|
||||||
|
background: var(--text-dim);
|
||||||
|
transition: background 0.4s ease, box-shadow 0.4s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-dot.online {
|
||||||
|
background: var(--green);
|
||||||
|
box-shadow: 0 0 7px var(--green);
|
||||||
|
animation: pulse-dot 2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-dot.offline {
|
||||||
|
background: var(--red);
|
||||||
|
box-shadow: 0 0 6px var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-info {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-name {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-state {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-dim);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
transition: color 0.4s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-state.online {
|
||||||
|
color: var(--green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-state.offline {
|
||||||
|
color: var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-desc {
|
||||||
|
font-size: 0.68rem;
|
||||||
|
color: var(--text-dim);
|
||||||
|
line-height: 1.35;
|
||||||
|
opacity: 0.75;
|
||||||
|
}
|
||||||
BIN
public/waterButtonStatus/taster.png
Normal file
BIN
public/waterButtonStatus/taster.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9.8 KiB |
BIN
public/waterButtonStatus/valve.png
Normal file
BIN
public/waterButtonStatus/valve.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
@@ -18,6 +18,7 @@
|
|||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { startStatusServer } from '../waterButtonStatusServer.js';
|
import { startStatusServer } from '../waterButtonStatusServer.js';
|
||||||
|
import { startTelegramBot } from '../waterButtonTelegramBot.js';
|
||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
@@ -29,15 +30,8 @@ const WATER_BUTTON_MAC = '08A6F773510C';
|
|||||||
const REMOTE_SWITCH_MAC = 'CC8DA243B0A0';
|
const REMOTE_SWITCH_MAC = 'CC8DA243B0A0';
|
||||||
|
|
||||||
// Telegram
|
// Telegram
|
||||||
const BOT_TOKEN = process.env.WATER_VALVE_TELEGRAM_TOKEN;
|
|
||||||
const BOT_PASSWORD = process.env.WATER_VALVE_TELEGRAM_PASSWORD;
|
|
||||||
const TELEGRAM_API = `https://api.telegram.org/bot${BOT_TOKEN}`;
|
|
||||||
const AUTH_FILE = path.join(__dirname, 'telegram_authorized_users.json');
|
|
||||||
|
|
||||||
// Generation counter — incremented on each hot reload to stop the old poll loop
|
|
||||||
const BOT_GEN = Date.now();
|
|
||||||
if (!global.__waterBotGen) global.__waterBotGen = 0;
|
|
||||||
global.__waterBotGen = BOT_GEN;
|
|
||||||
|
|
||||||
// sendRPC / getState persisted across hot reloads via globals (populated on first ctx event)
|
// sendRPC / getState persisted across hot reloads via globals (populated on first ctx event)
|
||||||
if (!global.__waterBotRPC) global.__waterBotRPC = null;
|
if (!global.__waterBotRPC) global.__waterBotRPC = null;
|
||||||
@@ -96,277 +90,15 @@ function getState(mac) {
|
|||||||
return deviceState.get(mac);
|
return deviceState.get(mac);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Telegram auth ─────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function loadAuthorizedUsers() {
|
startTelegramBot({
|
||||||
try {
|
getState,
|
||||||
if (fs.existsSync(AUTH_FILE)) {
|
WATER_BUTTON_MAC,
|
||||||
return new Set(JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8')));
|
REMOTE_SWITCH_MAC,
|
||||||
}
|
setLight,
|
||||||
} catch (err) {
|
persistedState,
|
||||||
console.error('[TelegramBot] Error loading authorized users:', err);
|
saveState
|
||||||
}
|
|
||||||
return new Set();
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveAuthorizedUsers(users) {
|
|
||||||
try {
|
|
||||||
fs.writeFileSync(AUTH_FILE, JSON.stringify([...users], null, 2));
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[TelegramBot] Error saving authorized users:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const authorizedUsers = loadAuthorizedUsers();
|
|
||||||
|
|
||||||
// ── Telegram bot ──────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
async function telegramRequest(method, params = {}) {
|
|
||||||
const res = await fetch(`${TELEGRAM_API}/${method}`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify(params)
|
|
||||||
});
|
});
|
||||||
return res.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
function menuKeyboard(durSec) {
|
|
||||||
return {
|
|
||||||
keyboard: [
|
|
||||||
[{ text: '🔓 Open valve' }, { text: '🔒 Close valve' }],
|
|
||||||
[{ text: `💧 Run timer (${durSec}s)` }, { text: '📊 Status' }]
|
|
||||||
],
|
|
||||||
resize_keyboard: true,
|
|
||||||
persistent: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getConnectionStatus() {
|
|
||||||
try {
|
|
||||||
const getState = global.__waterBotGetState;
|
|
||||||
if (!getState) return '❓ Button\n❓ Valve';
|
|
||||||
const [buttonOnline, valveOnline] = await Promise.all([
|
|
||||||
getState(WATER_BUTTON_MAC, 'system', 'online'),
|
|
||||||
getState(REMOTE_SWITCH_MAC, 'system', 'online')
|
|
||||||
]);
|
|
||||||
const btn = buttonOnline === true ? '✅' : buttonOnline === false ? '❌ OFFLINE' : '❓';
|
|
||||||
const vlv = valveOnline === true ? '✅' : valveOnline === false ? '❌ OFFLINE' : '❓';
|
|
||||||
return `${btn} Button\n${vlv} Valve`;
|
|
||||||
} catch {
|
|
||||||
return '❓ Button\n❓ Valve';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function reply(chatId, text, durSec) {
|
|
||||||
const connStatus = await getConnectionStatus();
|
|
||||||
return telegramRequest('sendMessage', {
|
|
||||||
chat_id: chatId,
|
|
||||||
text: `${connStatus}\n\n${text}`,
|
|
||||||
reply_markup: menuKeyboard(durSec)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function sendMessage(chatId, text) {
|
|
||||||
return telegramRequest('sendMessage', { chat_id: chatId, text });
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseDuration(raw) {
|
|
||||||
if (!raw) return null;
|
|
||||||
if (raw.endsWith('m')) return Math.round(parseFloat(raw) * 60000);
|
|
||||||
if (raw.endsWith('s')) return Math.round(parseFloat(raw) * 1000);
|
|
||||||
const ms = parseInt(raw, 10);
|
|
||||||
return isNaN(ms) ? null : ms;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleBotMessage(msg) {
|
|
||||||
const chatId = msg.chat.id;
|
|
||||||
const text = (msg.text || '').trim();
|
|
||||||
const parts = text.split(/\s+/);
|
|
||||||
// Strip @botname suffix that Telegram adds in groups
|
|
||||||
const cmd = parts[0].toLowerCase().split('@')[0];
|
|
||||||
|
|
||||||
// ── Authorization gate ───────────────────────────────────────────────────
|
|
||||||
if (!authorizedUsers.has(chatId)) {
|
|
||||||
if (text === BOT_PASSWORD) {
|
|
||||||
authorizedUsers.add(chatId);
|
|
||||||
saveAuthorizedUsers(authorizedUsers);
|
|
||||||
console.log(`[TelegramBot] New authorized user: ${chatId} (${msg.from?.username || msg.from?.first_name || 'unknown'})`);
|
|
||||||
const state = getState(WATER_BUTTON_MAC);
|
|
||||||
await reply(chatId, 'Access granted. Use the buttons below or type a number (seconds) to set the duration.', (state.storedDuration / 1000).toFixed(1));
|
|
||||||
} else {
|
|
||||||
await sendMessage(chatId, 'Please enter the password to use this bot.');
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const state = getState(WATER_BUTTON_MAC);
|
|
||||||
const durSec = (state.storedDuration / 1000).toFixed(1);
|
|
||||||
|
|
||||||
// ── Plain number → set duration in seconds ───────────────────────────────
|
|
||||||
const numericMatch = text.match(/^(\d+(?:\.\d+)?)$/);
|
|
||||||
if (numericMatch) {
|
|
||||||
const ms = Math.round(parseFloat(numericMatch[1]) * 1000);
|
|
||||||
if (ms <= 0 || ms > 300000) {
|
|
||||||
await reply(chatId, 'Duration must be between 1 and 300 seconds.', durSec);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
state.storedDuration = ms;
|
|
||||||
persistedState[WATER_BUTTON_MAC] = { storedDuration: ms };
|
|
||||||
saveState(persistedState);
|
|
||||||
const newSec = (ms / 1000).toFixed(1);
|
|
||||||
await reply(chatId, `Duration set to ${newSec}s.`, newSec);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Menu button labels map to commands ───────────────────────────────────
|
|
||||||
const buttonMap = {
|
|
||||||
'🔓 open valve': '/open',
|
|
||||||
'🔒 close valve': '/close',
|
|
||||||
'📊 status': '/status'
|
|
||||||
};
|
|
||||||
// Run timer button label includes dynamic duration — match by prefix
|
|
||||||
const normalised = text.toLowerCase();
|
|
||||||
const resolvedCmd = buttonMap[normalised]
|
|
||||||
|| (normalised.startsWith('💧 run timer') ? '/run' : cmd);
|
|
||||||
|
|
||||||
if (resolvedCmd === '/start' || resolvedCmd === '/help') {
|
|
||||||
await reply(chatId,
|
|
||||||
`💧 Water valve bot\n\n` +
|
|
||||||
`Use the buttons below, or:\n` +
|
|
||||||
`/open — Open valve\n` +
|
|
||||||
`/close — Close valve\n` +
|
|
||||||
`/run — Open then close after ${durSec}s\n` +
|
|
||||||
`/duration <value> — Set timer (e.g. 30s, 2m, 10000)\n` +
|
|
||||||
`<number> — Set duration in seconds (e.g. 45)\n` +
|
|
||||||
`/status — Current status`,
|
|
||||||
durSec
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolvedCmd === '/status') {
|
|
||||||
await reply(chatId,
|
|
||||||
`Status:\n` +
|
|
||||||
`• Duration: ${state.storedDuration}ms (${durSec}s)\n` +
|
|
||||||
`• Count mode: ${state.countMode}\n` +
|
|
||||||
`• Timer active: ${state.timer !== null}`,
|
|
||||||
durSec
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolvedCmd === '/duration') {
|
|
||||||
if (!parts[1]) {
|
|
||||||
await reply(chatId,
|
|
||||||
`Current duration: ${durSec}s\n` +
|
|
||||||
`Type a number (seconds) or use /duration <value>\n` +
|
|
||||||
`Examples: 30 /duration 30s /duration 2m`,
|
|
||||||
durSec
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const ms = parseDuration(parts[1]);
|
|
||||||
if (!ms || ms <= 0 || ms > 300000) {
|
|
||||||
await reply(chatId, 'Invalid duration. Use e.g. 30s, 2m, or seconds 1–300.', durSec);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
state.storedDuration = ms;
|
|
||||||
persistedState[WATER_BUTTON_MAC] = { storedDuration: ms };
|
|
||||||
saveState(persistedState);
|
|
||||||
const newSec = (ms / 1000).toFixed(1);
|
|
||||||
await reply(chatId, `Duration set to ${newSec}s.`, newSec);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const sendRPC = global.__waterBotRPC;
|
|
||||||
if (!sendRPC) {
|
|
||||||
await reply(chatId, 'Not ready yet — waiting for first device event. Try again in a moment.', durSec);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolvedCmd === '/open') {
|
|
||||||
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
|
|
||||||
state.countMode = false;
|
|
||||||
state.timerStartedAt = null;
|
|
||||||
state.timerEndsAt = null;
|
|
||||||
await setLight(sendRPC, WATER_BUTTON_MAC, false, 0); // light off = switch on = valve open
|
|
||||||
await reply(chatId, 'Valve opened.', durSec);
|
|
||||||
|
|
||||||
} else if (resolvedCmd === '/close') {
|
|
||||||
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
|
|
||||||
state.countMode = false;
|
|
||||||
state.timerStartedAt = null;
|
|
||||||
state.timerEndsAt = null;
|
|
||||||
await setLight(sendRPC, WATER_BUTTON_MAC, true, 95); // light on = switch off = valve closed
|
|
||||||
await reply(chatId, 'Valve closed.', durSec);
|
|
||||||
|
|
||||||
} else if (resolvedCmd === '/run') {
|
|
||||||
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
|
|
||||||
state.countMode = false;
|
|
||||||
await setLight(sendRPC, WATER_BUTTON_MAC, false, 0); // open valve
|
|
||||||
const duration = state.storedDuration;
|
|
||||||
state.timerStartedAt = Date.now();
|
|
||||||
state.timerEndsAt = Date.now() + duration;
|
|
||||||
await reply(chatId, `Valve opened. Closing in ${(duration / 1000).toFixed(1)}s…`, durSec);
|
|
||||||
|
|
||||||
state.timer = setTimeout(async () => {
|
|
||||||
try {
|
|
||||||
const rpc = global.__waterBotRPC;
|
|
||||||
if (rpc) await setLight(rpc, WATER_BUTTON_MAC, true, 95); // close valve
|
|
||||||
state.timer = null;
|
|
||||||
state.timerStartedAt = null;
|
|
||||||
state.timerEndsAt = null;
|
|
||||||
await reply(chatId, 'Timer elapsed — valve closed.', (getState(WATER_BUTTON_MAC).storedDuration / 1000).toFixed(1));
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[TelegramBot] Timer callback error:', err);
|
|
||||||
}
|
|
||||||
}, duration);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
await reply(chatId, 'Unknown command. Use the buttons below or send /help.', durSec);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function botLoop() {
|
|
||||||
console.log(`[TelegramBot] Starting (gen ${BOT_GEN})`);
|
|
||||||
let offset = 0;
|
|
||||||
|
|
||||||
while (BOT_GEN === global.__waterBotGen) {
|
|
||||||
try {
|
|
||||||
const data = await telegramRequest('getUpdates', {
|
|
||||||
offset,
|
|
||||||
timeout: 25,
|
|
||||||
allowed_updates: ['message']
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!data.ok) {
|
|
||||||
await sleep(5000);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const update of data.result || []) {
|
|
||||||
offset = update.update_id + 1;
|
|
||||||
if (update.message) {
|
|
||||||
handleBotMessage(update.message).catch(err =>
|
|
||||||
console.error('[TelegramBot] Handler error:', err)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[TelegramBot] Polling error:', err.message);
|
|
||||||
await sleep(5000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`[TelegramBot] Stopped (gen ${BOT_GEN} superseded)`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start long-polling immediately (non-blocking)
|
|
||||||
if (BOT_TOKEN) {
|
|
||||||
botLoop().catch(err => console.error('[TelegramBot] Fatal error:', err));
|
|
||||||
} else {
|
|
||||||
console.error('[TelegramBot] WATER_VALVE_TELEGRAM_TOKEN not set in .env — bot disabled');
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Rule export ───────────────────────────────────────────────────────────────
|
// ── Rule export ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -569,6 +301,7 @@ export default {
|
|||||||
startStatusServer({
|
startStatusServer({
|
||||||
getState,
|
getState,
|
||||||
WATER_BUTTON_MAC,
|
WATER_BUTTON_MAC,
|
||||||
|
REMOTE_SWITCH_MAC,
|
||||||
setLight,
|
setLight,
|
||||||
persistedState,
|
persistedState,
|
||||||
saveState
|
saveState
|
||||||
|
|||||||
@@ -6,16 +6,45 @@ const STATUS_PORT = 8082;
|
|||||||
export function startStatusServer({
|
export function startStatusServer({
|
||||||
getState,
|
getState,
|
||||||
WATER_BUTTON_MAC,
|
WATER_BUTTON_MAC,
|
||||||
|
REMOTE_SWITCH_MAC,
|
||||||
setLight,
|
setLight,
|
||||||
persistedState,
|
persistedState,
|
||||||
saveState
|
saveState
|
||||||
}) {
|
}) {
|
||||||
|
async function getButtonOnline() {
|
||||||
|
try {
|
||||||
|
const ctxGetState = global.__waterBotGetState;
|
||||||
|
if (!ctxGetState) return null;
|
||||||
|
const online = await ctxGetState(WATER_BUTTON_MAC, 'system', 'online');
|
||||||
|
// DB stores booleans as strings 'true'/'false'
|
||||||
|
if (online === true || online === 'true') return true;
|
||||||
|
if (online === false || online === 'false') return false;
|
||||||
|
return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getValveOnline() {
|
||||||
|
try {
|
||||||
|
const ctxGetState = global.__waterBotGetState;
|
||||||
|
if (!ctxGetState) return null;
|
||||||
|
const online = await ctxGetState(REMOTE_SWITCH_MAC, 'system', 'online');
|
||||||
|
if (online === true || online === 'true') return true;
|
||||||
|
if (online === false || online === 'false') return false;
|
||||||
|
return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function getStatusJSON() {
|
function getStatusJSON() {
|
||||||
const state = getState(WATER_BUTTON_MAC);
|
const state = getState(WATER_BUTTON_MAC);
|
||||||
return {
|
return {
|
||||||
valveOpen: state.timer !== null || (!state.countMode && state.timer === null),
|
valveOpen: state.timer !== null || (!state.countMode && state.timer === null),
|
||||||
timerActive: state.timer !== null,
|
timerActive: state.timer !== null,
|
||||||
countMode: state.countMode,
|
countMode: state.countMode,
|
||||||
|
countStart: state.countStart || null,
|
||||||
storedDuration: state.storedDuration,
|
storedDuration: state.storedDuration,
|
||||||
timerStartedAt: state.timerStartedAt,
|
timerStartedAt: state.timerStartedAt,
|
||||||
timerEndsAt: state.timerEndsAt,
|
timerEndsAt: state.timerEndsAt,
|
||||||
@@ -35,6 +64,31 @@ export function startStatusServer({
|
|||||||
<div class="container">
|
<div class="container">
|
||||||
<h1>💧 Water Timer</h1>
|
<h1>💧 Water Timer</h1>
|
||||||
|
|
||||||
|
<div class="devices-row">
|
||||||
|
<div class="device-status">
|
||||||
|
<div class="device-icon-wrap">
|
||||||
|
<img src="/taster.png" class="device-icon" alt="Button">
|
||||||
|
<span class="device-dot" id="device-dot"></span>
|
||||||
|
</div>
|
||||||
|
<div class="device-info">
|
||||||
|
<span class="device-name">Button</span>
|
||||||
|
<span class="device-state" id="device-state">Checking…</span>
|
||||||
|
<span class="device-desc">Short press: run timer · Long press: start learn, short press to stop</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="device-status">
|
||||||
|
<div class="device-icon-wrap">
|
||||||
|
<img src="/valve.png" class="device-icon" alt="Valve">
|
||||||
|
<span class="device-dot" id="valve-dot"></span>
|
||||||
|
</div>
|
||||||
|
<div class="device-info">
|
||||||
|
<span class="device-name">Valve</span>
|
||||||
|
<span class="device-state" id="valve-state">Checking…</span>
|
||||||
|
<span class="device-desc">⚠️ Connect according to flow direction mark</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="ring-wrapper">
|
<div class="ring-wrapper">
|
||||||
<div class="glow" id="glow"></div>
|
<div class="glow" id="glow"></div>
|
||||||
<svg class="ring-svg" viewBox="0 0 120 120">
|
<svg class="ring-svg" viewBox="0 0 120 120">
|
||||||
@@ -66,6 +120,7 @@ export function startStatusServer({
|
|||||||
<span class="dur-unit">sec</span>
|
<span class="dur-unit">sec</span>
|
||||||
</div>
|
</div>
|
||||||
<button class="btn primary" id="btn-run" onclick="doRun()">▶ Run</button>
|
<button class="btn primary" id="btn-run" onclick="doRun()">▶ Run</button>
|
||||||
|
<button class="btn warning" id="btn-learn" onclick="doLearn()">📐 Learn</button>
|
||||||
</div>
|
</div>
|
||||||
<button class="btn success" id="btn-open" onclick="doOpen()">🔓 Open</button>
|
<button class="btn success" id="btn-open" onclick="doOpen()">🔓 Open</button>
|
||||||
<button class="btn danger" id="btn-close" onclick="doClose()">🔒 Close</button>
|
<button class="btn danger" id="btn-close" onclick="doClose()">🔒 Close</button>
|
||||||
@@ -81,7 +136,7 @@ export function startStatusServer({
|
|||||||
try { global.__waterStatusServer.close(); } catch (e) { }
|
try { global.__waterStatusServer.close(); } catch (e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
const srv = http.createServer((req, res) => {
|
const srv = http.createServer(async (req, res) => {
|
||||||
const url = new URL(req.url, `http://${req.headers.host}`);
|
const url = new URL(req.url, `http://${req.headers.host}`);
|
||||||
|
|
||||||
const jsonHeaders = {
|
const jsonHeaders = {
|
||||||
@@ -102,6 +157,32 @@ export function startStatusServer({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/taster.png') {
|
||||||
|
res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'public, max-age=86400' });
|
||||||
|
res.end(fs.readFileSync(new URL('./public/waterButtonStatus/taster.png', import.meta.url)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/api/button-online') {
|
||||||
|
const online = await getButtonOnline();
|
||||||
|
res.writeHead(200, jsonHeaders);
|
||||||
|
res.end(JSON.stringify({ online }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/valve.png') {
|
||||||
|
res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'public, max-age=86400' });
|
||||||
|
res.end(fs.readFileSync(new URL('./public/waterButtonStatus/valve.png', import.meta.url)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/api/valve-online') {
|
||||||
|
const online = await getValveOnline();
|
||||||
|
res.writeHead(200, jsonHeaders);
|
||||||
|
res.end(JSON.stringify({ online }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (url.pathname === '/api/status') {
|
if (url.pathname === '/api/status') {
|
||||||
res.writeHead(200, jsonHeaders);
|
res.writeHead(200, jsonHeaders);
|
||||||
res.end(JSON.stringify(getStatusJSON()));
|
res.end(JSON.stringify(getStatusJSON()));
|
||||||
@@ -114,17 +195,55 @@ export function startStatusServer({
|
|||||||
req.on('data', c => body += c);
|
req.on('data', c => body += c);
|
||||||
req.on('end', async () => {
|
req.on('end', async () => {
|
||||||
const sendRPC = global.__waterBotRPC;
|
const sendRPC = global.__waterBotRPC;
|
||||||
|
|
||||||
// Wait, inside the route we need `state` which uses `getState(WATER_BUTTON_MAC)`
|
|
||||||
// The original code did: const state = getState(WATER_BUTTON_MAC);
|
|
||||||
const state = getState(WATER_BUTTON_MAC);
|
const state = getState(WATER_BUTTON_MAC);
|
||||||
|
|
||||||
|
// ── Learn / Stop-learn: work regardless of device connection ──
|
||||||
|
if (url.pathname === '/api/learn') {
|
||||||
|
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
|
||||||
|
state.timerStartedAt = null;
|
||||||
|
state.timerEndsAt = null;
|
||||||
|
state.countMode = true;
|
||||||
|
state.countStart = Date.now();
|
||||||
|
if (sendRPC) {
|
||||||
|
try { await setLight(sendRPC, WATER_BUTTON_MAC, false, 0); } catch (e) {
|
||||||
|
console.warn('[WaterStatus] learn: setLight failed:', e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.writeHead(200, jsonHeaders);
|
||||||
|
res.end(JSON.stringify({ ok: true, action: 'learn' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/api/stop-learn') {
|
||||||
|
if (!state.countMode) {
|
||||||
|
res.writeHead(200, jsonHeaders);
|
||||||
|
res.end(JSON.stringify({ ok: true, action: 'stop-learn', skipped: true }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const elapsed = Date.now() - (state.countStart || Date.now());
|
||||||
|
state.countMode = false;
|
||||||
|
state.countStart = 0;
|
||||||
|
state.storedDuration = elapsed;
|
||||||
|
persistedState[WATER_BUTTON_MAC] = { storedDuration: elapsed };
|
||||||
|
saveState(persistedState);
|
||||||
|
if (sendRPC) {
|
||||||
|
try { await setLight(sendRPC, WATER_BUTTON_MAC, true, 95); } catch (e) {
|
||||||
|
console.warn('[WaterStatus] stop-learn: setLight failed:', e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.writeHead(200, jsonHeaders);
|
||||||
|
res.end(JSON.stringify({ ok: true, action: 'stop-learn', storedDuration: elapsed }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── All other commands require a live device connection ──
|
||||||
if (!sendRPC) {
|
if (!sendRPC) {
|
||||||
res.writeHead(503, jsonHeaders);
|
res.writeHead(503, jsonHeaders);
|
||||||
res.end(JSON.stringify({ ok: false, error: 'Not ready — no device connection' }));
|
res.end(JSON.stringify({ ok: false, error: 'Not ready — no device connection' }));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (url.pathname === '/api/run') {
|
if (url.pathname === '/api/run') {
|
||||||
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
|
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
|
||||||
|
|||||||
301
waterButtonTelegramBot.js
Normal file
301
waterButtonTelegramBot.js
Normal file
@@ -0,0 +1,301 @@
|
|||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = path.dirname(__filename);
|
||||||
|
|
||||||
|
const AUTH_FILE = path.join(__dirname, 'telegram_authorized_users.json');
|
||||||
|
const BOT_TOKEN = process.env.WATER_VALVE_TELEGRAM_TOKEN;
|
||||||
|
const BOT_PASSWORD = process.env.WATER_VALVE_TELEGRAM_PASSWORD;
|
||||||
|
const TELEGRAM_API = `https://api.telegram.org/bot${BOT_TOKEN}`;
|
||||||
|
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
|
||||||
|
|
||||||
|
// Generation counter — incremented on each hot reload to stop the old poll loop
|
||||||
|
const BOT_GEN = Date.now();
|
||||||
|
if (!global.__waterBotGen) global.__waterBotGen = 0;
|
||||||
|
global.__waterBotGen = BOT_GEN;
|
||||||
|
|
||||||
|
export function startTelegramBot({
|
||||||
|
getState,
|
||||||
|
WATER_BUTTON_MAC,
|
||||||
|
REMOTE_SWITCH_MAC,
|
||||||
|
setLight,
|
||||||
|
persistedState,
|
||||||
|
saveState
|
||||||
|
}) {
|
||||||
|
// ── Telegram auth ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function loadAuthorizedUsers() {
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(AUTH_FILE)) {
|
||||||
|
return new Set(JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8')));
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[TelegramBot] Error loading authorized users:', err);
|
||||||
|
}
|
||||||
|
return new Set();
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveAuthorizedUsers(users) {
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(AUTH_FILE, JSON.stringify([...users], null, 2));
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[TelegramBot] Error saving authorized users:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const authorizedUsers = loadAuthorizedUsers();
|
||||||
|
|
||||||
|
// ── Telegram bot ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function telegramRequest(method, params = {}) {
|
||||||
|
const res = await fetch(`${TELEGRAM_API}/${method}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(params)
|
||||||
|
});
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
function menuKeyboard(durSec) {
|
||||||
|
return {
|
||||||
|
keyboard: [
|
||||||
|
[{ text: '🔓 Open valve' }, { text: '🔒 Close valve' }],
|
||||||
|
[{ text: `💧 Run timer (${durSec}s)` }, { text: '📊 Status' }]
|
||||||
|
],
|
||||||
|
resize_keyboard: true,
|
||||||
|
persistent: true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getConnectionStatus() {
|
||||||
|
try {
|
||||||
|
const getState = global.__waterBotGetState;
|
||||||
|
if (!getState) return '❓ Button\n❓ Valve';
|
||||||
|
const [buttonOnline, valveOnline] = await Promise.all([
|
||||||
|
getState(WATER_BUTTON_MAC, 'system', 'online'),
|
||||||
|
getState(REMOTE_SWITCH_MAC, 'system', 'online')
|
||||||
|
]);
|
||||||
|
const btn = buttonOnline === true ? '✅' : buttonOnline === false ? '❌ OFFLINE' : '❓';
|
||||||
|
const vlv = valveOnline === true ? '✅' : valveOnline === false ? '❌ OFFLINE' : '❓';
|
||||||
|
return `${btn} Button\n${vlv} Valve`;
|
||||||
|
} catch {
|
||||||
|
return '❓ Button\n❓ Valve';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reply(chatId, text, durSec) {
|
||||||
|
const connStatus = await getConnectionStatus();
|
||||||
|
return telegramRequest('sendMessage', {
|
||||||
|
chat_id: chatId,
|
||||||
|
text: `${connStatus}\n\n${text}`,
|
||||||
|
reply_markup: menuKeyboard(durSec)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendMessage(chatId, text) {
|
||||||
|
return telegramRequest('sendMessage', { chat_id: chatId, text });
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseDuration(raw) {
|
||||||
|
if (!raw) return null;
|
||||||
|
if (raw.endsWith('m')) return Math.round(parseFloat(raw) * 60000);
|
||||||
|
if (raw.endsWith('s')) return Math.round(parseFloat(raw) * 1000);
|
||||||
|
const ms = parseInt(raw, 10);
|
||||||
|
return isNaN(ms) ? null : ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleBotMessage(msg) {
|
||||||
|
const chatId = msg.chat.id;
|
||||||
|
const text = (msg.text || '').trim();
|
||||||
|
const parts = text.split(/\s+/);
|
||||||
|
// Strip @botname suffix that Telegram adds in groups
|
||||||
|
const cmd = parts[0].toLowerCase().split('@')[0];
|
||||||
|
|
||||||
|
// ── Authorization gate ───────────────────────────────────────────────────
|
||||||
|
if (!authorizedUsers.has(chatId)) {
|
||||||
|
if (text === BOT_PASSWORD) {
|
||||||
|
authorizedUsers.add(chatId);
|
||||||
|
saveAuthorizedUsers(authorizedUsers);
|
||||||
|
console.log(`[TelegramBot] New authorized user: ${chatId} (${msg.from?.username || msg.from?.first_name || 'unknown'})`);
|
||||||
|
const state = getState(WATER_BUTTON_MAC);
|
||||||
|
await reply(chatId, 'Access granted. Use the buttons below or type a number (seconds) to set the duration.', (state.storedDuration / 1000).toFixed(1));
|
||||||
|
} else {
|
||||||
|
await sendMessage(chatId, 'Please enter the password to use this bot.');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const state = getState(WATER_BUTTON_MAC);
|
||||||
|
const durSec = (state.storedDuration / 1000).toFixed(1);
|
||||||
|
|
||||||
|
// ── Plain number → set duration in seconds ───────────────────────────────
|
||||||
|
const numericMatch = text.match(/^(\d+(?:\.\d+)?)$/);
|
||||||
|
if (numericMatch) {
|
||||||
|
const ms = Math.round(parseFloat(numericMatch[1]) * 1000);
|
||||||
|
if (ms <= 0 || ms > 300000) {
|
||||||
|
await reply(chatId, 'Duration must be between 1 and 300 seconds.', durSec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.storedDuration = ms;
|
||||||
|
persistedState[WATER_BUTTON_MAC] = { storedDuration: ms };
|
||||||
|
saveState(persistedState);
|
||||||
|
const newSec = (ms / 1000).toFixed(1);
|
||||||
|
await reply(chatId, `Duration set to ${newSec}s.`, newSec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Menu button labels map to commands ───────────────────────────────────
|
||||||
|
const buttonMap = {
|
||||||
|
'🔓 open valve': '/open',
|
||||||
|
'🔒 close valve': '/close',
|
||||||
|
'📊 status': '/status'
|
||||||
|
};
|
||||||
|
// Run timer button label includes dynamic duration — match by prefix
|
||||||
|
const normalised = text.toLowerCase();
|
||||||
|
const resolvedCmd = buttonMap[normalised]
|
||||||
|
|| (normalised.startsWith('💧 run timer') ? '/run' : cmd);
|
||||||
|
|
||||||
|
if (resolvedCmd === '/start' || resolvedCmd === '/help') {
|
||||||
|
await reply(chatId,
|
||||||
|
`💧 Water valve bot\n\n` +
|
||||||
|
`Use the buttons below, or:\n` +
|
||||||
|
`/open — Open valve\n` +
|
||||||
|
`/close — Close valve\n` +
|
||||||
|
`/run — Open then close after ${durSec}s\n` +
|
||||||
|
`/duration <value> — Set timer (e.g. 30s, 2m, 10000)\n` +
|
||||||
|
`<number> — Set duration in seconds (e.g. 45)\n` +
|
||||||
|
`/status — Current status`,
|
||||||
|
durSec
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resolvedCmd === '/status') {
|
||||||
|
await reply(chatId,
|
||||||
|
`Status:\n` +
|
||||||
|
`• Duration: ${state.storedDuration}ms (${durSec}s)\n` +
|
||||||
|
`• Count mode: ${state.countMode}\n` +
|
||||||
|
`• Timer active: ${state.timer !== null}`,
|
||||||
|
durSec
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resolvedCmd === '/duration') {
|
||||||
|
if (!parts[1]) {
|
||||||
|
await reply(chatId,
|
||||||
|
`Current duration: ${durSec}s\n` +
|
||||||
|
`Type a number (seconds) or use /duration <value>\n` +
|
||||||
|
`Examples: 30 /duration 30s /duration 2m`,
|
||||||
|
durSec
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const ms = parseDuration(parts[1]);
|
||||||
|
if (!ms || ms <= 0 || ms > 300000) {
|
||||||
|
await reply(chatId, 'Invalid duration. Use e.g. 30s, 2m, or seconds 1–300.', durSec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.storedDuration = ms;
|
||||||
|
persistedState[WATER_BUTTON_MAC] = { storedDuration: ms };
|
||||||
|
saveState(persistedState);
|
||||||
|
const newSec = (ms / 1000).toFixed(1);
|
||||||
|
await reply(chatId, `Duration set to ${newSec}s.`, newSec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sendRPC = global.__waterBotRPC;
|
||||||
|
if (!sendRPC) {
|
||||||
|
await reply(chatId, 'Not ready yet — waiting for first device event. Try again in a moment.', durSec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resolvedCmd === '/open') {
|
||||||
|
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
|
||||||
|
state.countMode = false;
|
||||||
|
state.timerStartedAt = null;
|
||||||
|
state.timerEndsAt = null;
|
||||||
|
await setLight(sendRPC, WATER_BUTTON_MAC, false, 0); // light off = switch on = valve open
|
||||||
|
await reply(chatId, 'Valve opened.', durSec);
|
||||||
|
|
||||||
|
} else if (resolvedCmd === '/close') {
|
||||||
|
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
|
||||||
|
state.countMode = false;
|
||||||
|
state.timerStartedAt = null;
|
||||||
|
state.timerEndsAt = null;
|
||||||
|
await setLight(sendRPC, WATER_BUTTON_MAC, true, 95); // light on = switch off = valve closed
|
||||||
|
await reply(chatId, 'Valve closed.', durSec);
|
||||||
|
|
||||||
|
} else if (resolvedCmd === '/run') {
|
||||||
|
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
|
||||||
|
state.countMode = false;
|
||||||
|
await setLight(sendRPC, WATER_BUTTON_MAC, false, 0); // open valve
|
||||||
|
const duration = state.storedDuration;
|
||||||
|
state.timerStartedAt = Date.now();
|
||||||
|
state.timerEndsAt = Date.now() + duration;
|
||||||
|
await reply(chatId, `Valve opened. Closing in ${(duration / 1000).toFixed(1)}s…`, durSec);
|
||||||
|
|
||||||
|
state.timer = setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
const rpc = global.__waterBotRPC;
|
||||||
|
if (rpc) await setLight(rpc, WATER_BUTTON_MAC, true, 95); // close valve
|
||||||
|
state.timer = null;
|
||||||
|
state.timerStartedAt = null;
|
||||||
|
state.timerEndsAt = null;
|
||||||
|
await reply(chatId, 'Timer elapsed — valve closed.', (getState(WATER_BUTTON_MAC).storedDuration / 1000).toFixed(1));
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[TelegramBot] Timer callback error:', err);
|
||||||
|
}
|
||||||
|
}, duration);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
await reply(chatId, 'Unknown command. Use the buttons below or send /help.', durSec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function botLoop() {
|
||||||
|
console.log(`[TelegramBot] Starting (gen ${BOT_GEN})`);
|
||||||
|
let offset = 0;
|
||||||
|
|
||||||
|
while (BOT_GEN === global.__waterBotGen) {
|
||||||
|
try {
|
||||||
|
const data = await telegramRequest('getUpdates', {
|
||||||
|
offset,
|
||||||
|
timeout: 25,
|
||||||
|
allowed_updates: ['message']
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!data.ok) {
|
||||||
|
await sleep(5000);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const update of data.result || []) {
|
||||||
|
offset = update.update_id + 1;
|
||||||
|
if (update.message) {
|
||||||
|
handleBotMessage(update.message).catch(err =>
|
||||||
|
console.error('[TelegramBot] Handler error:', err)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[TelegramBot] Polling error:', err.message);
|
||||||
|
await sleep(5000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[TelegramBot] Stopped (gen ${BOT_GEN} superseded)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start long-polling immediately (non-blocking)
|
||||||
|
if (BOT_TOKEN) {
|
||||||
|
botLoop().catch(err => console.error('[TelegramBot] Fatal error:', err));
|
||||||
|
} else {
|
||||||
|
console.error('[TelegramBot] WATER_VALVE_TELEGRAM_TOKEN not set in .env — bot disabled');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user