initial commit

This commit is contained in:
2026-03-06 12:25:27 -05:00
commit 4f2556bb42
45 changed files with 8473 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}HAMeter{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('main.static', filename='style.css') }}">
<link rel="icon" type="image/svg+xml" href="{{ url_for('main.static', filename='favicon.svg') }}">
</head>
<body>
<div class="app-layout">
<nav class="sidebar" id="sidebar">
<div class="sidebar-header">
<h1 class="logo">HAMeter</h1>
<div class="status-indicator" id="pipeline-status">
<span class="status-dot"></span>
<span class="status-text">Loading...</span>
</div>
</div>
<ul class="nav-links">
<li><a href="/dashboard" class="nav-link {% if request.path == '/dashboard' %}active{% endif %}"><span class="nav-icon">&#9671;</span> Dashboard</a></li>
<li><a href="/discovery" class="nav-link {% if request.path == '/discovery' %}active{% endif %}"><span class="nav-icon">&#9678;</span> Discovery</a></li>
<li><a href="/calibration" class="nav-link {% if request.path == '/calibration' %}active{% endif %}"><span class="nav-icon">&#9878;</span> Calibration</a></li>
<li class="nav-separator">Configuration</li>
<li><a href="/config/mqtt" class="nav-link {% if '/config/mqtt' in request.path %}active{% endif %}"><span class="nav-icon">&#8644;</span> MQTT</a></li>
<li><a href="/config/meters" class="nav-link {% if '/config/meters' in request.path %}active{% endif %}"><span class="nav-icon">&#9681;</span> Meters</a></li>
<li><a href="/config/general" class="nav-link {% if '/config/general' in request.path %}active{% endif %}"><span class="nav-icon">&#9881;</span> General</a></li>
<li class="nav-separator">System</li>
<li><a href="/logs" class="nav-link {% if request.path == '/logs' %}active{% endif %}"><span class="nav-icon">&#9776;</span> Logs</a></li>
</ul>
</nav>
<main class="main-content">
<header class="top-bar">
<button class="hamburger" id="hamburger" onclick="toggleSidebar()">&#9776;</button>
<h2 class="page-title">{% block page_title %}{% endblock %}</h2>
<div class="top-bar-actions">
{% block top_actions %}{% endblock %}
</div>
</header>
<div class="content-area">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="flash flash-{{ category }}">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</div>
</main>
</div>
<div class="toast-container" id="toast-container"></div>
<script src="{{ url_for('main.static', filename='app.js') }}"></script>
</body>
</html>

View File

@@ -0,0 +1,146 @@
{% extends "base.html" %}
{% block title %}Calibration - HAMeter{% endblock %}
{% block page_title %}Calibration{% endblock %}
{% block content %}
<div class="config-form-container">
{% if not meters %}
<div class="empty-state">
<p>No meters configured. <a href="/config/meters/add">Add a meter</a> first.</p>
</div>
{% else %}
<div class="calibration-info">
<p>Calibrate the multiplier that converts raw meter readings to actual units (kWh, gallons, etc.).</p>
<p><strong>How:</strong> Read the display on your physical meter, enter it below along with the current raw reading from HAMeter, and the multiplier will be calculated automatically.</p>
</div>
<form id="calibration-form" onsubmit="return false;">
<div class="form-group">
<label for="cal-meter">Select Meter</label>
<select id="cal-meter" onchange="onMeterSelect()">
{% for meter in meters %}
<option value="{{ meter.id }}"
data-unit="{{ meter.unit_of_measurement }}"
data-multiplier="{{ meter.multiplier }}"
data-raw="{{ readings.get(meter.id, '')|attr('raw_consumption') if readings.get(meter.id) else '' }}">
{{ meter.name }} ({{ meter.id }})
</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="cal-raw">Current Raw Reading (from HAMeter)</label>
<input type="number" id="cal-raw" step="any">
<small>This is the raw, uncalibrated value. You can find it on the Dashboard.</small>
</div>
<div class="form-group">
<label for="cal-physical">Current Physical Meter Reading</label>
<input type="number" id="cal-physical" step="any">
<small>Read this from the display on your physical meter. <span id="cal-unit-hint"></span></small>
</div>
<div class="form-actions">
<button type="button" class="btn btn-primary" onclick="calculate()">Calculate</button>
</div>
</form>
<div class="calibration-result hidden" id="cal-result">
<h3>Result</h3>
<div class="result-grid">
<div class="result-item">
<span class="result-label">New Multiplier</span>
<span class="result-value" id="cal-new-multiplier">--</span>
</div>
<div class="result-item">
<span class="result-label">Current Multiplier</span>
<span class="result-value" id="cal-current-multiplier">--</span>
</div>
<div class="result-item">
<span class="result-label">Preview</span>
<span class="result-value" id="cal-preview">--</span>
</div>
</div>
<div class="form-actions">
<button type="button" class="btn btn-primary" onclick="applyMultiplier()">Apply Multiplier</button>
</div>
</div>
{% endif %}
</div>
<script>
let selectedMeterId = null;
let calculatedMultiplier = null;
function onMeterSelect() {
const sel = document.getElementById('cal-meter');
const opt = sel.options[sel.selectedIndex];
selectedMeterId = parseInt(sel.value);
const raw = opt.dataset.raw;
if (raw) document.getElementById('cal-raw').value = raw;
document.getElementById('cal-current-multiplier').textContent = opt.dataset.multiplier;
const unit = opt.dataset.unit;
document.getElementById('cal-unit-hint').textContent = unit ? '(in ' + unit + ')' : '';
}
async function calculate() {
const raw = parseFloat(document.getElementById('cal-raw').value);
const physical = parseFloat(document.getElementById('cal-physical').value);
if (!raw || !physical) {
showToast('Enter both values', 'error');
return;
}
const resp = await fetch('/api/calibration/calculate', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({raw_reading: raw, physical_reading: physical}),
});
const data = await resp.json();
if (data.error) {
showToast(data.error, 'error');
return;
}
calculatedMultiplier = data.multiplier;
document.getElementById('cal-new-multiplier').textContent = data.multiplier;
document.getElementById('cal-preview').textContent = data.preview;
document.getElementById('cal-result').classList.remove('hidden');
}
async function applyMultiplier() {
if (!selectedMeterId || !calculatedMultiplier) return;
const resp = await fetch('/api/calibration/apply', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({meter_id: selectedMeterId, multiplier: calculatedMultiplier}),
});
const data = await resp.json();
if (data.ok) {
showToast('Multiplier applied', 'success');
if (data.restart_required) showRestartBanner();
} else {
showToast(data.error || 'Failed', 'error');
}
}
// Auto-select meter from query param or default to first
document.addEventListener('DOMContentLoaded', function() {
const params = new URLSearchParams(window.location.search);
const meterId = params.get('meter');
if (meterId) {
const sel = document.getElementById('cal-meter');
if (sel) {
for (let i = 0; i < sel.options.length; i++) {
if (sel.options[i].value === meterId) {
sel.selectedIndex = i;
break;
}
}
}
}
onMeterSelect();
});
</script>
{% endblock %}

View File

@@ -0,0 +1,77 @@
{% extends "base.html" %}
{% block title %}Dashboard - HAMeter{% endblock %}
{% block page_title %}Dashboard{% endblock %}
{% block top_actions %}
<button class="btn btn-secondary btn-sm" onclick="restartPipeline()">Restart Pipeline</button>
{% endblock %}
{% block content %}
<div class="dashboard">
{% if meters %}
<div class="meter-grid" id="meter-grid">
{% for meter in meters %}
<div class="meter-card" id="meter-card-{{ meter.id }}" data-meter-id="{{ meter.id }}">
<div class="meter-card-header">
<h3>{{ meter.name }}</h3>
<span class="badge badge-protocol">{{ meter.protocol|upper }}</span>
</div>
<div class="meter-card-body">
<div class="meter-reading" id="reading-{{ meter.id }}">
<span class="reading-value">--</span>
<span class="reading-unit">{{ meter.unit_of_measurement }}</span>
</div>
{% if meter.cost_factors %}
<div class="meter-cost" id="cost-section-{{ meter.id }}">
<div class="cost-value" id="cost-{{ meter.id }}">$--</div>
<div class="cost-label">Estimated Cost</div>
<div class="cost-details">
<div class="detail-row">
<span class="detail-label">Billing Start</span>
<span class="detail-value" id="billing-start-{{ meter.id }}">--</span>
</div>
<div class="detail-row">
<span class="detail-label">Fixed Charges</span>
<span class="detail-value" id="fixed-charges-{{ meter.id }}">$0.00</span>
</div>
</div>
<div class="cost-actions">
<button class="btn btn-secondary btn-sm" onclick="addFixedCharges({{ meter.id }})">Add Fixed Charges</button>
<button class="btn btn-secondary btn-sm" onclick="resetBillingPeriod({{ meter.id }})">Reset Period</button>
</div>
</div>
{% endif %}
<div class="meter-details">
<div class="detail-row">
<span class="detail-label">Raw Reading</span>
<span class="detail-value" id="raw-{{ meter.id }}">--</span>
</div>
<div class="detail-row">
<span class="detail-label">Last Seen</span>
<span class="detail-value" id="lastseen-{{ meter.id }}">--</span>
</div>
<div class="detail-row">
<span class="detail-label">Readings</span>
<span class="detail-value" id="count-{{ meter.id }}">0</span>
</div>
<div class="detail-row">
<span class="detail-label">Meter ID</span>
<span class="detail-value">{{ meter.id }}</span>
</div>
<div class="detail-row">
<span class="detail-label">Multiplier</span>
<span class="detail-value">{{ meter.multiplier }}</span>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="empty-state">
<p>No meters configured.</p>
<p><a href="/discovery" class="btn btn-primary">Run Discovery</a> or <a href="/config/meters/add" class="btn btn-secondary">Add Meter Manually</a></p>
</div>
{% endif %}
</div>
{% endblock %}

View File

@@ -0,0 +1,119 @@
{% extends "base.html" %}
{% block title %}Discovery - HAMeter{% endblock %}
{% block page_title %}Discovery{% endblock %}
{% block content %}
<div class="discovery-page">
<div class="discovery-info">
<p>Discovery mode listens for all nearby meter transmissions. This will <strong>temporarily stop</strong> meter monitoring while active.</p>
</div>
<div class="discovery-controls">
<div class="form-group form-inline">
<label for="duration">Duration (seconds)</label>
<input type="number" id="duration" value="120" min="10" max="600">
</div>
<div class="btn-group">
<button class="btn btn-primary" id="btn-start" onclick="startDiscovery()">Start Discovery</button>
<button class="btn btn-danger hidden" id="btn-stop" onclick="stopDiscovery()">Stop</button>
</div>
<div class="discovery-status hidden" id="discovery-status">
<span class="spinner-sm"></span>
<span id="discovery-timer">Listening...</span>
</div>
</div>
<div class="table-container">
<table class="data-table" id="discovery-table">
<thead>
<tr>
<th>Meter ID</th>
<th>Protocol</th>
<th>Count</th>
<th>Last Reading</th>
<th>Action</th>
</tr>
</thead>
<tbody id="discovery-tbody">
<tr class="empty-row"><td colspan="5">No meters found yet. Start discovery to scan.</td></tr>
</tbody>
</table>
</div>
</div>
<script>
let discoveryTimer = null;
let discoveryStart = null;
let discoveryDuration = 120;
const configuredIds = new Set({{ configured_ids|tojson }});
function startDiscovery() {
discoveryDuration = parseInt(document.getElementById('duration').value) || 120;
fetch('/api/discovery/start', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({duration: discoveryDuration}),
}).then(r => r.json()).then(data => {
if (data.ok) {
discoveryStart = Date.now();
document.getElementById('btn-start').classList.add('hidden');
document.getElementById('btn-stop').classList.remove('hidden');
document.getElementById('discovery-status').classList.remove('hidden');
document.getElementById('discovery-tbody').innerHTML =
'<tr class="empty-row"><td colspan="5">Listening for meters...</td></tr>';
discoveryTimer = setInterval(updateTimer, 1000);
}
});
}
function stopDiscovery() {
fetch('/api/discovery/stop', {method: 'POST'});
endDiscovery();
}
function endDiscovery() {
clearInterval(discoveryTimer);
document.getElementById('btn-start').classList.remove('hidden');
document.getElementById('btn-stop').classList.add('hidden');
document.getElementById('discovery-status').classList.add('hidden');
}
function updateTimer() {
const elapsed = Math.floor((Date.now() - discoveryStart) / 1000);
const remaining = discoveryDuration - elapsed;
if (remaining <= 0) {
endDiscovery();
return;
}
document.getElementById('discovery-timer').textContent =
'Listening... ' + remaining + 's remaining';
}
// SSE handler updates discovery results
if (typeof window._onDiscoveryUpdate === 'undefined') {
window._onDiscoveryUpdate = function(results) {
const tbody = document.getElementById('discovery-tbody');
if (!tbody) return;
if (!results || Object.keys(results).length === 0) return;
let html = '';
// Sort by count descending
const entries = Object.entries(results).sort((a, b) => (b[1].count || 0) - (a[1].count || 0));
for (const [mid, info] of entries) {
const meterId = parseInt(mid);
const configured = configuredIds.has(meterId);
html += '<tr>' +
'<td><code>' + mid + '</code></td>' +
'<td><span class="badge badge-protocol">' + (info.protocol || '').toUpperCase() + '</span></td>' +
'<td>' + (info.count || 0) + '</td>' +
'<td>' + (info.last_consumption || '--') + '</td>' +
'<td>' + (configured
? '<span class="text-muted">Configured</span>'
: '<a href="/config/meters/add?id=' + mid + '&protocol=' + (info.protocol || '') + '" class="btn btn-sm btn-primary">Add</a>'
) + '</td></tr>';
}
tbody.innerHTML = html;
};
}
</script>
{% endblock %}

View File

@@ -0,0 +1,66 @@
{% extends "base.html" %}
{% block title %}General Settings - HAMeter{% endblock %}
{% block page_title %}General Settings{% endblock %}
{% block content %}
<div class="config-form-container">
<form id="general-form" onsubmit="return false;">
<div class="form-group">
<label for="log_level">Log Level</label>
<select id="log_level">
<option value="DEBUG" {{ 'selected' if general.log_level == 'DEBUG' }}>DEBUG</option>
<option value="INFO" {{ 'selected' if general.log_level == 'INFO' }}>INFO</option>
<option value="WARNING" {{ 'selected' if general.log_level == 'WARNING' }}>WARNING</option>
<option value="ERROR" {{ 'selected' if general.log_level == 'ERROR' }}>ERROR</option>
</select>
</div>
<div class="form-group">
<label for="device_id">SDR Device Index</label>
<input type="text" id="device_id" value="{{ general.device_id }}">
<small>Usually "0" unless you have multiple RTL-SDR dongles.</small>
</div>
<div class="form-group">
<label for="rtl_tcp_host">rtl_tcp Host</label>
<input type="text" id="rtl_tcp_host" value="{{ general.rtl_tcp_host }}">
</div>
<div class="form-group">
<label for="rtl_tcp_port">rtl_tcp Port</label>
<input type="number" id="rtl_tcp_port" value="{{ general.rtl_tcp_port }}">
</div>
<div class="form-group">
<label for="rtlamr_extra_args">rtlamr Extra Arguments</label>
<input type="text" id="rtlamr_extra_args" value="{{ general.rtlamr_extra_args|join(' ') }}" placeholder="Space-separated arguments">
<small>Additional command-line arguments passed to rtlamr.</small>
</div>
<div class="form-actions">
<button type="button" class="btn btn-primary" onclick="saveGeneral()">Save</button>
</div>
</form>
</div>
<script>
async function saveGeneral() {
const data = {
log_level: document.getElementById('log_level').value,
device_id: document.getElementById('device_id').value,
rtl_tcp_host: document.getElementById('rtl_tcp_host').value,
rtl_tcp_port: parseInt(document.getElementById('rtl_tcp_port').value),
rtlamr_extra_args: document.getElementById('rtlamr_extra_args').value,
};
const resp = await fetch('/api/config/general', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
});
const res = await resp.json();
if (res.ok) {
showToast('Settings saved', 'success');
if (res.restart_required) showRestartBanner();
} else {
showToast(res.error || 'Save failed', 'error');
}
}
</script>
{% endblock %}

View File

@@ -0,0 +1,84 @@
{% extends "base.html" %}
{% block title %}Logs - HAMeter{% endblock %}
{% block page_title %}Logs{% endblock %}
{% block top_actions %}
<div class="log-controls">
<select id="log-level-filter" onchange="filterLogs()">
<option value="">All Levels</option>
<option value="DEBUG">DEBUG</option>
<option value="INFO">INFO</option>
<option value="WARNING">WARNING</option>
<option value="ERROR">ERROR</option>
</select>
<input type="text" id="log-search" placeholder="Filter..." oninput="filterLogs()">
<label class="checkbox-label">
<input type="checkbox" id="log-autoscroll" checked> Auto-scroll
</label>
<button class="btn btn-sm btn-secondary" onclick="clearLogs()">Clear</button>
</div>
{% endblock %}
{% block content %}
<div class="log-viewer" id="log-viewer"></div>
<script>
const logViewer = document.getElementById('log-viewer');
let allLogs = [];
// Load initial logs
fetch('/api/logs?count=500')
.then(r => r.json())
.then(logs => {
allLogs = logs;
renderLogs();
});
function addLogEntry(entry) {
allLogs.push(entry);
if (allLogs.length > 2000) allLogs = allLogs.slice(-1000);
renderLogs();
}
function renderLogs() {
const level = document.getElementById('log-level-filter').value;
const search = document.getElementById('log-search').value.toLowerCase();
const filtered = allLogs.filter(log => {
if (level && log.level !== level) return false;
if (search && !log.message.toLowerCase().includes(search) && !log.name.toLowerCase().includes(search)) return false;
return true;
});
logViewer.innerHTML = filtered.map(log => {
const cls = 'log-' + (log.level || 'INFO').toLowerCase();
return '<div class="log-line ' + cls + '">' +
'<span class="log-ts">' + (log.timestamp || '') + '</span> ' +
'<span class="log-level">[' + (log.level || '?') + ']</span> ' +
'<span class="log-name">' + (log.name || '') + ':</span> ' +
'<span class="log-msg">' + escapeHtml(log.message || '') + '</span>' +
'</div>';
}).join('');
if (document.getElementById('log-autoscroll').checked) {
logViewer.scrollTop = logViewer.scrollHeight;
}
}
function filterLogs() { renderLogs(); }
function clearLogs() { allLogs = []; renderLogs(); }
function escapeHtml(s) {
return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
// SSE log handler
if (typeof window._onLogUpdate === 'undefined') {
window._onLogUpdate = function(logs) {
if (Array.isArray(logs)) {
logs.forEach(addLogEntry);
}
};
}
</script>
{% endblock %}

View File

@@ -0,0 +1,160 @@
{% extends "base.html" %}
{% block title %}{{ 'Edit' if editing else 'Add' }} Meter - HAMeter{% endblock %}
{% block page_title %}{{ 'Edit' if editing else 'Add' }} Meter{% endblock %}
{% block content %}
<div class="config-form-container">
<form id="meter-form" onsubmit="return false;">
<div class="form-group">
<label for="meter-id">Meter ID (ERT Serial Number) <span class="required">*</span></label>
<input type="number" id="meter-id" value="{{ meter.id if meter else prefill_id|default('', true) }}" {{ 'readonly' if editing }} required>
{% if editing %}<small>Meter ID cannot be changed after creation.</small>{% endif %}
</div>
<div class="form-group">
<label for="meter-protocol">Protocol <span class="required">*</span></label>
<select id="meter-protocol">
{% for p in protocols %}
<option value="{{ p }}" {{ 'selected' if (meter and meter.protocol == p) or (not meter and prefill_protocol|default('', true) == p) }}>{{ p }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="meter-name">Name <span class="required">*</span></label>
<input type="text" id="meter-name" value="{{ meter.name if meter else '' }}" required>
</div>
<div class="form-group">
<label for="meter-device-class">Device Class</label>
<select id="meter-device-class" onchange="onDeviceClassChange()">
<option value="" {{ 'selected' if not meter or not meter.device_class }}>None</option>
<option value="energy" {{ 'selected' if meter and meter.device_class == 'energy' }}>Energy (Electric)</option>
<option value="gas" {{ 'selected' if meter and meter.device_class == 'gas' }}>Gas</option>
<option value="water" {{ 'selected' if meter and meter.device_class == 'water' }}>Water</option>
</select>
</div>
<div class="form-group">
<label for="meter-unit">Unit of Measurement</label>
<input type="text" id="meter-unit" value="{{ meter.unit_of_measurement if meter else '' }}" placeholder="Auto-set by device class">
</div>
<div class="form-group">
<label for="meter-icon">Icon</label>
<input type="text" id="meter-icon" value="{{ meter.icon if meter else '' }}" placeholder="e.g. mdi:flash">
</div>
<div class="form-group">
<label for="meter-state-class">State Class</label>
<select id="meter-state-class">
<option value="total_increasing" {{ 'selected' if not meter or meter.state_class == 'total_increasing' }}>total_increasing</option>
<option value="measurement" {{ 'selected' if meter and meter.state_class == 'measurement' }}>measurement</option>
<option value="total" {{ 'selected' if meter and meter.state_class == 'total' }}>total</option>
</select>
</div>
<div class="form-group">
<label for="meter-multiplier">Calibration Multiplier</label>
<input type="number" id="meter-multiplier" step="any" value="{{ meter.multiplier if meter else '1.0' }}">
<small>Use <a href="/calibration">Calibration</a> to calculate this value.</small>
</div>
<div class="form-group">
<label>Rate Components (Cost Factors)</label>
<small>Add rate components from your utility bill to track costs.</small>
<div id="cost-factors-list">
{% if meter and meter.cost_factors %}
{% for cf in meter.cost_factors %}
<div class="cost-factor-row" data-index="{{ loop.index0 }}">
<input type="text" class="cf-name" value="{{ cf.name }}" placeholder="Name (e.g. Generation)">
<input type="number" class="cf-rate" step="any" value="{{ cf.rate }}" placeholder="Rate">
<select class="cf-type">
<option value="per_unit" {{ 'selected' if cf.type == 'per_unit' }}>Per Unit</option>
<option value="fixed" {{ 'selected' if cf.type == 'fixed' }}>Fixed</option>
</select>
<button type="button" class="btn btn-icon" onclick="removeCostFactor(this)" title="Remove">&times;</button>
</div>
{% endfor %}
{% endif %}
</div>
<button type="button" class="btn btn-secondary btn-sm" onclick="addCostFactor()" style="margin-top: 0.5rem;">+ Add Rate Component</button>
</div>
<div class="form-actions">
<a href="/config/meters" class="btn btn-secondary">Cancel</a>
<button type="button" class="btn btn-primary" onclick="saveMeter()">Save</button>
</div>
</form>
</div>
<script>
function onDeviceClassChange() {
const dc = document.getElementById('meter-device-class').value;
if (!dc) return;
fetch('/api/meter_defaults/' + dc)
.then(r => r.json())
.then(data => {
if (data.unit) document.getElementById('meter-unit').value = data.unit;
if (data.icon) document.getElementById('meter-icon').value = data.icon;
});
}
function addCostFactor(name, rate, type) {
const list = document.getElementById('cost-factors-list');
const row = document.createElement('div');
row.className = 'cost-factor-row';
row.innerHTML =
'<input type="text" class="cf-name" value="' + (name || '') + '" placeholder="Name (e.g. Generation)">' +
'<input type="number" class="cf-rate" step="any" value="' + (rate || '') + '" placeholder="Rate">' +
'<select class="cf-type">' +
'<option value="per_unit"' + (type === 'fixed' ? '' : ' selected') + '>Per Unit</option>' +
'<option value="fixed"' + (type === 'fixed' ? ' selected' : '') + '>Fixed</option>' +
'</select>' +
'<button type="button" class="btn btn-icon" onclick="removeCostFactor(this)" title="Remove">&times;</button>';
list.appendChild(row);
}
function removeCostFactor(btn) {
btn.closest('.cost-factor-row').remove();
}
function collectCostFactors() {
const rows = document.querySelectorAll('.cost-factor-row');
const factors = [];
rows.forEach(function(row) {
const name = row.querySelector('.cf-name').value.trim();
const rate = parseFloat(row.querySelector('.cf-rate').value);
const type = row.querySelector('.cf-type').value;
if (name && !isNaN(rate)) {
factors.push({ name: name, rate: rate, type: type });
}
});
return factors;
}
async function saveMeter() {
const data = {
id: parseInt(document.getElementById('meter-id').value),
protocol: document.getElementById('meter-protocol').value,
name: document.getElementById('meter-name').value,
device_class: document.getElementById('meter-device-class').value,
unit_of_measurement: document.getElementById('meter-unit').value,
icon: document.getElementById('meter-icon').value,
state_class: document.getElementById('meter-state-class').value,
multiplier: parseFloat(document.getElementById('meter-multiplier').value) || 1.0,
cost_factors: collectCostFactors(),
};
const editing = {{ 'true' if editing else 'false' }};
const url = editing ? '/api/config/meters/' + data.id : '/api/config/meters';
const method = editing ? 'PUT' : 'POST';
const resp = await fetch(url, {
method: method,
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
});
const res = await resp.json();
if (res.ok) {
showToast('Meter saved', 'success');
setTimeout(() => window.location.href = '/config/meters', 500);
} else {
showToast(res.error || 'Save failed', 'error');
}
}
</script>
{% endblock %}

View File

@@ -0,0 +1,70 @@
{% extends "base.html" %}
{% block title %}Meters - HAMeter{% endblock %}
{% block page_title %}Meters{% endblock %}
{% block top_actions %}
<a href="/config/meters/add" class="btn btn-primary btn-sm">Add Meter</a>
{% endblock %}
{% block content %}
<div class="restart-banner hidden" id="restart-banner">
Pipeline restart required to apply changes.
<button class="btn btn-primary btn-sm" onclick="restartPipeline()">Restart Now</button>
</div>
{% if meters %}
<div class="table-container">
<table class="data-table">
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Protocol</th>
<th>Type</th>
<th>Unit</th>
<th>Multiplier</th>
<th>Cost Tracking</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for meter in meters %}
<tr>
<td>{{ meter.name }}</td>
<td><code>{{ meter.id }}</code></td>
<td><span class="badge badge-protocol">{{ meter.protocol|upper }}</span></td>
<td>{{ meter.device_class or '--' }}</td>
<td>{{ meter.unit_of_measurement }}</td>
<td>{{ meter.multiplier }}</td>
<td>{% if meter.cost_factors %}<span class="badge badge-cost">{{ meter.cost_factors|length }} rate{{ 's' if meter.cost_factors|length != 1 }}</span>{% else %}--{% endif %}</td>
<td class="actions-cell">
<a href="/config/meters/{{ meter.id }}/edit" class="btn btn-sm btn-secondary">Edit</a>
<a href="/calibration?meter={{ meter.id }}" class="btn btn-sm btn-secondary">Calibrate</a>
<button class="btn btn-sm btn-danger" onclick="deleteMeter({{ meter.id }}, '{{ meter.name }}')">Delete</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="empty-state">
<p>No meters configured.</p>
<p><a href="/config/meters/add" class="btn btn-primary">Add Meter</a> or <a href="/discovery" class="btn btn-secondary">Run Discovery</a></p>
</div>
{% endif %}
<script>
async function deleteMeter(id, name) {
if (!confirm('Delete meter "' + name + '" (ID: ' + id + ')?')) return;
const resp = await fetch('/api/config/meters/' + id, {method: 'DELETE'});
const data = await resp.json();
if (data.ok) {
showToast('Meter deleted', 'success');
setTimeout(() => location.reload(), 500);
} else {
showToast(data.error || 'Delete failed', 'error');
}
}
</script>
{% endblock %}

View File

@@ -0,0 +1,113 @@
{% extends "base.html" %}
{% block title %}MQTT Settings - HAMeter{% endblock %}
{% block page_title %}MQTT Settings{% endblock %}
{% block content %}
<div class="config-form-container">
<form id="mqtt-config-form" onsubmit="return false;">
<div class="form-group">
<label for="host">Host <span class="required">*</span></label>
<input type="text" id="host" name="host" value="{{ mqtt.host }}" required>
</div>
<div class="form-group">
<label for="port">Port</label>
<input type="number" id="port" name="port" value="{{ mqtt.port }}">
</div>
<div class="form-group">
<label for="user">Username</label>
<input type="text" id="user" name="user" value="{{ mqtt.user }}">
</div>
<div class="form-group">
<label for="password">Password</label>
<div class="input-group">
<input type="password" id="password" name="password" value="{{ '***' if mqtt.password else '' }}">
<button type="button" class="btn btn-icon" onclick="togglePassword('password')">Show</button>
</div>
</div>
<div class="form-group">
<label for="base_topic">Base Topic</label>
<input type="text" id="base_topic" name="base_topic" value="{{ mqtt.base_topic }}">
</div>
<div class="form-group">
<label>
<input type="checkbox" id="ha_autodiscovery" name="ha_autodiscovery" {{ 'checked' if mqtt.ha_autodiscovery }}>
HA Auto-Discovery
</label>
</div>
<div class="form-group" id="ha-topic-group">
<label for="ha_autodiscovery_topic">HA Discovery Topic</label>
<input type="text" id="ha_autodiscovery_topic" name="ha_autodiscovery_topic" value="{{ mqtt.ha_autodiscovery_topic }}">
</div>
<div class="form-group">
<label for="client_id">Client ID</label>
<input type="text" id="client_id" name="client_id" value="{{ mqtt.client_id }}">
</div>
<div class="form-actions">
<button type="button" class="btn btn-secondary" onclick="testMqttConnection()">Test Connection</button>
<button type="button" class="btn btn-primary" onclick="saveMqttConfig()">Save</button>
</div>
<div class="test-result hidden" id="mqtt-test-result"></div>
</form>
</div>
<script>
async function testMqttConnection() {
const result = document.getElementById('mqtt-test-result');
result.classList.remove('hidden');
result.textContent = 'Testing...';
result.className = 'test-result';
const data = {
host: document.getElementById('host').value,
port: parseInt(document.getElementById('port').value),
user: document.getElementById('user').value,
password: document.getElementById('password').value,
};
// Don't send masked password for test
if (data.password === '***') data.password = '';
try {
const resp = await fetch('/api/config/mqtt/test', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
});
const res = await resp.json();
result.textContent = res.message;
result.className = 'test-result ' + (res.ok ? 'test-success' : 'test-error');
} catch (e) {
result.textContent = 'Error: ' + e.message;
result.className = 'test-result test-error';
}
}
async function saveMqttConfig() {
const data = {
host: document.getElementById('host').value,
port: parseInt(document.getElementById('port').value),
user: document.getElementById('user').value,
password: document.getElementById('password').value,
base_topic: document.getElementById('base_topic').value,
ha_autodiscovery: document.getElementById('ha_autodiscovery').checked,
ha_autodiscovery_topic: document.getElementById('ha_autodiscovery_topic').value,
client_id: document.getElementById('client_id').value,
};
const resp = await fetch('/api/config/mqtt', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
});
const res = await resp.json();
if (res.ok) {
showToast('MQTT settings saved', 'success');
if (res.restart_required) {
showRestartBanner();
}
} else {
showToast(res.error || 'Save failed', 'error');
}
}
</script>
{% endblock %}

View File

@@ -0,0 +1,210 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HAMeter Setup</title>
<link rel="stylesheet" href="{{ url_for('main.static', filename='style.css') }}">
<link rel="icon" type="image/svg+xml" href="{{ url_for('main.static', filename='favicon.svg') }}">
</head>
<body class="setup-body">
<div class="setup-container">
<div class="setup-card" id="step-1">
<div class="setup-logo">HAMeter</div>
<h2>Welcome</h2>
<p>HAMeter reads utility meters via SDR and publishes readings to Home Assistant over MQTT.</p>
<p>Let's configure your connection.</p>
<button class="btn btn-primary btn-lg" onclick="showStep(2)">Get Started</button>
</div>
<div class="setup-card hidden" id="step-2">
<h2>MQTT Broker</h2>
<p>Enter your MQTT broker connection details.</p>
<form id="mqtt-form" onsubmit="return false;">
<div class="form-group">
<label for="mqtt-host">Host <span class="required">*</span></label>
<input type="text" id="mqtt-host" placeholder="192.168.1.74" required>
</div>
<div class="form-group">
<label for="mqtt-port">Port</label>
<input type="number" id="mqtt-port" value="1883">
</div>
<div class="form-group">
<label for="mqtt-user">Username</label>
<input type="text" id="mqtt-user" placeholder="Optional">
</div>
<div class="form-group">
<label for="mqtt-password">Password</label>
<input type="password" id="mqtt-password" placeholder="Optional">
</div>
<div class="form-actions">
<button type="button" class="btn btn-secondary" onclick="testMqtt()">Test Connection</button>
<button type="button" class="btn btn-primary" onclick="mqttNext()">Next</button>
</div>
<div class="test-result hidden" id="mqtt-test-result"></div>
</form>
</div>
<div class="setup-card hidden" id="step-3">
<h2>Add a Meter</h2>
<p>If you know your meter's radio ID and protocol, enter them below. Otherwise, you can use Discovery after setup.</p>
<form id="meter-form" onsubmit="return false;">
<div class="form-group">
<label for="meter-id">Meter ID (ERT Serial Number)</label>
<input type="number" id="meter-id" placeholder="e.g. 23040293">
</div>
<div class="form-group">
<label for="meter-protocol">Protocol</label>
<select id="meter-protocol">
{% for p in protocols %}
<option value="{{ p }}">{{ p }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="meter-name">Name</label>
<input type="text" id="meter-name" placeholder="e.g. Electric Meter">
</div>
<div class="form-group">
<label for="meter-device-class">Type</label>
<select id="meter-device-class" onchange="updateMeterDefaults()">
<option value="">-- Select --</option>
<option value="energy">Energy (Electric)</option>
<option value="gas">Gas</option>
<option value="water">Water</option>
</select>
</div>
<div class="form-actions">
<a href="#" class="btn btn-link" onclick="skipMeter()">Skip &mdash; I'll use Discovery later</a>
<button type="button" class="btn btn-primary" onclick="saveMeterAndFinish()">Save &amp; Start</button>
</div>
</form>
</div>
<div class="setup-card hidden" id="step-4">
<div class="setup-success">&#10003;</div>
<h2>Setup Complete</h2>
<p>HAMeter is starting up. Redirecting to dashboard...</p>
<div class="spinner"></div>
</div>
<div class="setup-error hidden" id="setup-error">
<p class="error-text"></p>
</div>
</div>
<script>
function showStep(n) {
document.querySelectorAll('.setup-card').forEach(el => el.classList.add('hidden'));
document.getElementById('step-' + n).classList.remove('hidden');
}
async function testMqtt() {
const result = document.getElementById('mqtt-test-result');
result.classList.remove('hidden');
result.textContent = 'Testing...';
result.className = 'test-result';
try {
const resp = await fetch('/api/config/mqtt/test', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
host: document.getElementById('mqtt-host').value,
port: parseInt(document.getElementById('mqtt-port').value),
user: document.getElementById('mqtt-user').value,
password: document.getElementById('mqtt-password').value,
}),
});
const data = await resp.json();
result.textContent = data.message;
result.className = 'test-result ' + (data.ok ? 'test-success' : 'test-error');
} catch (e) {
result.textContent = 'Request failed: ' + e.message;
result.className = 'test-result test-error';
}
}
function mqttNext() {
const host = document.getElementById('mqtt-host').value.trim();
if (!host) {
showError('MQTT host is required');
return;
}
showStep(3);
}
function updateMeterDefaults() {
const dc = document.getElementById('meter-device-class').value;
if (!dc) return;
fetch('/api/meter_defaults/' + dc)
.then(r => r.json())
.then(data => {
// Auto-fill name if empty
const nameEl = document.getElementById('meter-name');
if (!nameEl.value) {
const names = {energy: 'Electric Meter', gas: 'Gas Meter', water: 'Water Meter'};
nameEl.value = names[dc] || '';
}
});
}
async function saveMeterAndFinish() {
await doSetup(true);
}
async function skipMeter() {
await doSetup(false);
}
async function doSetup(includeMeter) {
const payload = {
mqtt: {
host: document.getElementById('mqtt-host').value.trim(),
port: parseInt(document.getElementById('mqtt-port').value),
user: document.getElementById('mqtt-user').value,
password: document.getElementById('mqtt-password').value,
},
};
if (includeMeter) {
const meterId = document.getElementById('meter-id').value;
if (!meterId) {
showError('Meter ID is required');
return;
}
payload.meter = {
id: parseInt(meterId),
protocol: document.getElementById('meter-protocol').value,
name: document.getElementById('meter-name').value || 'Meter 1',
device_class: document.getElementById('meter-device-class').value,
};
}
try {
const resp = await fetch('/api/setup', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload),
});
const data = await resp.json();
if (data.ok) {
showStep(4);
setTimeout(() => window.location.href = '/dashboard', 3000);
} else {
showError(data.error || 'Setup failed');
}
} catch (e) {
showError('Request failed: ' + e.message);
}
}
function showError(msg) {
const el = document.getElementById('setup-error');
el.classList.remove('hidden');
el.querySelector('.error-text').textContent = msg;
setTimeout(() => el.classList.add('hidden'), 5000);
}
</script>
</body>
</html>