Add webserver functionality and HTML interface for alarm clock
This commit is contained in:
113
public/index.html
Normal file
113
public/index.html
Normal file
@@ -0,0 +1,113 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Alarm Clock</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
color: #fff;
|
||||
}
|
||||
.container {
|
||||
background: rgba(255,255,255,0.1);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 20px;
|
||||
padding: 40px;
|
||||
text-align: center;
|
||||
max-width: 400px;
|
||||
width: 90%;
|
||||
}
|
||||
h1 { margin-bottom: 30px; font-size: 1.8rem; }
|
||||
.time { font-size: 3rem; font-weight: 300; margin-bottom: 20px; }
|
||||
.alarm-time { font-size: 1.5rem; color: #4fc3f7; margin-bottom: 30px; }
|
||||
.alarm-active { color: #ff5252; animation: pulse 1s infinite; }
|
||||
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
||||
.controls { display: flex; flex-direction: column; gap: 15px; }
|
||||
.time-input { display: flex; justify-content: center; gap: 10px; align-items: center; }
|
||||
input[type="number"] {
|
||||
width: 60px; padding: 10px; font-size: 1.2rem;
|
||||
border: none; border-radius: 8px; text-align: center;
|
||||
background: rgba(255,255,255,0.2); color: #fff;
|
||||
}
|
||||
input[type="number"]:focus { outline: 2px solid #4fc3f7; }
|
||||
button {
|
||||
padding: 12px 24px; font-size: 1rem; border: none;
|
||||
border-radius: 8px; cursor: pointer; transition: all 0.2s;
|
||||
}
|
||||
.btn-primary { background: #4fc3f7; color: #1a1a2e; }
|
||||
.btn-primary:hover { background: #29b6f6; }
|
||||
.btn-danger { background: #ff5252; color: #fff; }
|
||||
.btn-danger:hover { background: #ff1744; }
|
||||
.status { margin-top: 20px; font-size: 0.9rem; color: #aaa; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>Alarm Clock</h1>
|
||||
<div class="time" id="currentTime">--:--:--</div>
|
||||
<div class="alarm-time" id="alarmTime">Alarm: --:--</div>
|
||||
<div class="controls">
|
||||
<div class="time-input">
|
||||
<input type="number" id="hour" min="0" max="23" placeholder="HH">
|
||||
<span>:</span>
|
||||
<input type="number" id="minute" min="0" max="59" placeholder="MM">
|
||||
</div>
|
||||
<button class="btn-primary" onclick="setAlarm()">Set Alarm</button>
|
||||
<button class="btn-danger" id="dismissBtn" onclick="dismissAlarm()" style="display:none">Dismiss Alarm</button>
|
||||
</div>
|
||||
<div class="status" id="status"></div>
|
||||
</div>
|
||||
<script>
|
||||
async function fetchStatus() {
|
||||
try {
|
||||
const res = await fetch('/api/status');
|
||||
const data = await res.json();
|
||||
document.getElementById('currentTime').textContent = data.current_time;
|
||||
const alarmEl = document.getElementById('alarmTime');
|
||||
alarmEl.textContent = 'Alarm: ' + (data.alarm_time || '--:--');
|
||||
alarmEl.classList.toggle('alarm-active', data.alarm_active);
|
||||
document.getElementById('dismissBtn').style.display = data.alarm_active ? 'block' : 'none';
|
||||
} catch (e) {
|
||||
document.getElementById('status').textContent = 'Connection error';
|
||||
}
|
||||
}
|
||||
async function setAlarm() {
|
||||
const hour = parseInt(document.getElementById('hour').value);
|
||||
const minute = parseInt(document.getElementById('minute').value);
|
||||
if (isNaN(hour) || isNaN(minute)) {
|
||||
document.getElementById('status').textContent = 'Please enter valid hour and minute';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch('/api/alarm', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ hour, minute })
|
||||
});
|
||||
const data = await res.json();
|
||||
document.getElementById('status').textContent = data.success ? 'Alarm set!' : data.error;
|
||||
fetchStatus();
|
||||
} catch (e) {
|
||||
document.getElementById('status').textContent = 'Failed to set alarm';
|
||||
}
|
||||
}
|
||||
async function dismissAlarm() {
|
||||
try {
|
||||
await fetch('/api/dismiss', { method: 'POST' });
|
||||
fetchStatus();
|
||||
} catch (e) {
|
||||
document.getElementById('status').textContent = 'Failed to dismiss alarm';
|
||||
}
|
||||
}
|
||||
fetchStatus();
|
||||
setInterval(fetchStatus, 1000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,2 +1,3 @@
|
||||
astral
|
||||
requests
|
||||
requests
|
||||
flask
|
||||
11
src/main.py
11
src/main.py
@@ -3,7 +3,9 @@ from .shelly import ShellyDevice
|
||||
from .audio import AudioPlayer
|
||||
from .alarm_clock import AlarmClock
|
||||
from .relay import Relay
|
||||
from .webserver import run_server
|
||||
from os import path
|
||||
import threading
|
||||
|
||||
def main():
|
||||
"""Main entry point for the alarm clock application."""
|
||||
@@ -47,6 +49,15 @@ def main():
|
||||
dismiss_action=lambda: relay.off()
|
||||
)
|
||||
|
||||
# Start webserver in background thread
|
||||
server_thread = threading.Thread(
|
||||
target=run_server,
|
||||
kwargs={'alarm_clock': alarm_clock, 'host': '0.0.0.0', 'port': 5000},
|
||||
daemon=True
|
||||
)
|
||||
server_thread.start()
|
||||
print("Webserver started on http://0.0.0.0:5000")
|
||||
|
||||
alarm_clock.start()
|
||||
|
||||
|
||||
|
||||
117
src/webserver.py
Normal file
117
src/webserver.py
Normal file
@@ -0,0 +1,117 @@
|
||||
from flask import Flask, jsonify, request, send_from_directory
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
from os import path
|
||||
|
||||
from .config import CITY
|
||||
|
||||
|
||||
def create_app(alarm_clock=None):
|
||||
"""Create and configure the Flask application."""
|
||||
|
||||
# Get the absolute path to the public folder
|
||||
public_folder = path.abspath(path.join(path.dirname(__file__), '..', 'public'))
|
||||
|
||||
app = Flask(__name__, static_folder=public_folder, static_url_path='')
|
||||
|
||||
# Store alarm_clock reference
|
||||
app.alarm_clock = alarm_clock
|
||||
|
||||
# Serve static files from public folder
|
||||
@app.route('/')
|
||||
def serve_index():
|
||||
return send_from_directory(public_folder, 'index.html')
|
||||
|
||||
@app.route('/<path:filename>')
|
||||
def serve_static(filename):
|
||||
return send_from_directory(public_folder, filename)
|
||||
|
||||
# API endpoints
|
||||
@app.route('/api/status', methods=['GET'])
|
||||
def get_status():
|
||||
"""Get current alarm clock status."""
|
||||
now = datetime.now(ZoneInfo(CITY.timezone))
|
||||
|
||||
response = {
|
||||
'current_time': now.strftime('%H:%M:%S'),
|
||||
'timezone': CITY.timezone,
|
||||
'alarm_active': False,
|
||||
'alarm_time': None,
|
||||
'config_mode': 'normal'
|
||||
}
|
||||
|
||||
if app.alarm_clock:
|
||||
response['alarm_active'] = app.alarm_clock.alarm_active
|
||||
response['alarm_time'] = app.alarm_clock.alarm_time.strftime('%H:%M')
|
||||
response['config_mode'] = app.alarm_clock.config_mode
|
||||
|
||||
return jsonify(response)
|
||||
|
||||
@app.route('/api/alarm', methods=['GET'])
|
||||
def get_alarm():
|
||||
"""Get current alarm time."""
|
||||
if not app.alarm_clock:
|
||||
return jsonify({'error': 'Alarm clock not initialized'}), 503
|
||||
|
||||
return jsonify({
|
||||
'hour': app.alarm_clock.alarm_time.hour,
|
||||
'minute': app.alarm_clock.alarm_time.minute,
|
||||
'formatted': app.alarm_clock.alarm_time.strftime('%H:%M')
|
||||
})
|
||||
|
||||
@app.route('/api/alarm', methods=['POST'])
|
||||
def set_alarm():
|
||||
"""Set alarm time. Expects JSON with 'hour' and 'minute'."""
|
||||
if not app.alarm_clock:
|
||||
return jsonify({'error': 'Alarm clock not initialized'}), 503
|
||||
|
||||
data = request.get_json()
|
||||
if not data:
|
||||
return jsonify({'error': 'JSON body required'}), 400
|
||||
|
||||
hour = data.get('hour')
|
||||
minute = data.get('minute')
|
||||
|
||||
if hour is None or minute is None:
|
||||
return jsonify({'error': 'Both hour and minute are required'}), 400
|
||||
|
||||
try:
|
||||
hour = int(hour)
|
||||
minute = int(minute)
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({'error': 'Hour and minute must be integers'}), 400
|
||||
|
||||
if not (0 <= hour <= 23):
|
||||
return jsonify({'error': 'Hour must be between 0 and 23'}), 400
|
||||
if not (0 <= minute <= 59):
|
||||
return jsonify({'error': 'Minute must be between 0 and 59'}), 400
|
||||
|
||||
app.alarm_clock.alarm_time = app.alarm_clock.alarm_time.replace(
|
||||
hour=hour, minute=minute
|
||||
)
|
||||
app.alarm_clock.reset_wakeup_actions()
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'alarm_time': app.alarm_clock.alarm_time.strftime('%H:%M')
|
||||
})
|
||||
|
||||
@app.route('/api/dismiss', methods=['POST'])
|
||||
def dismiss_alarm():
|
||||
"""Dismiss the active alarm."""
|
||||
if not app.alarm_clock:
|
||||
return jsonify({'error': 'Alarm clock not initialized'}), 503
|
||||
|
||||
if not app.alarm_clock.alarm_active:
|
||||
return jsonify({'message': 'No active alarm to dismiss'}), 200
|
||||
|
||||
app.alarm_clock.dismiss_alarm()
|
||||
return jsonify({'success': True, 'message': 'Alarm dismissed'})
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def run_server(alarm_clock=None, host='0.0.0.0', port=5000, debug=False):
|
||||
"""Run the webserver."""
|
||||
app = create_app(alarm_clock)
|
||||
app.run(host=host, port=port, debug=debug, threaded=True)
|
||||
Reference in New Issue
Block a user