Compare commits

..
4 Commits
Author SHA1 Message Date
Tanner 1931b48c68 Remove empty whitespace lines 2026-08-25 18:17:45 +00:00
Tannerandaider bcddadf5b9 feat: support querying and merging multiple sensors server-side
Co-authored-by: aider (gemini/gemini-3.1-pro-preview) <aider@aider.chat>
2026-08-25 18:14:28 +00:00
Tannerandaider ef47ee3b26 feat: add MultiLineChart component and merge pressure charts
Co-authored-by: aider (gemini/gemini-3.1-pro-preview) <aider@aider.chat>
2026-08-25 18:07:37 +00:00
Tanner 6be13585fd feat: add pressure graphs 2026-08-25 18:07:37 +00:00
2 changed files with 161 additions and 47 deletions
+97
View File
@@ -31,6 +31,7 @@ const units = {
'Setpoint': ' °C',
'State': '',
'Lux': ' lx',
'Hpa': ' hpa',
'Soil': '',
};
@@ -668,6 +669,91 @@ function Lux({name, sensorName, end, duration}) {
);
}
function MultiLineChart({title, measurement, dataKey, sensors, colors, end, duration, yDomain, unitKey}) {
const [data, setData] = useState(false);
const [loading, setLoading] = useState(false);
useEffect(() => {
const get = async() => {
setLoading(true);
try {
const api_key = localStorage.getItem('api_key', 'null');
const params = { end: end.unix(), duration: duration.len.toLowerCase(), window: duration.win, api_key: api_key };
const names = sensors.join(',');
const res = await axios.get(`https://sensors-api.dns.t0.vc/history/${measurement}/${names}`, { params });
const formattedData = res.data.map(d => {
const newObj = { time: d.time };
sensors.forEach(sensor => {
newObj[sensor] = d[`${sensor}_${dataKey}`];
});
return newObj;
});
setData(formattedData);
setLoading(false);
} catch (error) {
console.log(error);
setLoading(false);
}
};
get();
}, [end, duration, measurement, dataKey, JSON.stringify(sensors)]);
const memoConvertTZ = (isDST, timeStr, format) => {
if (!timeStr) return '?';
let lookUp, result = null;
const date = timeStr.slice(5, 10);
const hours = timeStr.slice(11, 13);
const minutes = timeStr.slice(14, 16);
if (format === 'HH') { lookUp = [isDST, hours, format]; }
else { lookUp = [isDST, date, format]; }
if (tzcache[lookUp] != undefined ) { result = tzcache[lookUp]; }
else { result = moment(timeStr).tz('America/Edmonton').format(format); tzcache[lookUp] = result; }
if (format === 'HH') { return result + ':' + minutes; }
else { return result; }
};
const isDST = end.tz('America/Edmonton').isDST();
const tickFormatter = (timeStr) => memoConvertTZ(isDST, timeStr, duration.format);
return (
<ChartContainer
name={title}
data={data}
lastFormatter={(x) => {
const vals = sensors.map(s => x[s]).filter(v => v !== undefined);
return vals.length ? vals[0].toFixed(1) + (units[unitKey] || '') : 'No data';
}}
loading={loading}
>
<XAxis dataKey='time' minTickGap={10} tickFormatter={tickFormatter} />
<YAxis domain={yDomain} />
<CartesianGrid strokeDasharray='3 3'/>
<Tooltip
formatter={(v, name) => v.toFixed(1) + (units[unitKey] || '')}
labelFormatter={timeStr => moment(timeStr).tz('America/Edmonton').format('ddd MMM DD h:mm A')}
separator=': '
/>
<ReferenceLine x={moment().tz('America/Edmonton').startOf('day').toISOString().replace('.000', '')} stroke='blue' />
<Legend />
{sensors.map((sensor, i) => (
<Line
key={sensor}
type='monotone'
dataKey={sensor}
name={sensor}
stroke={colors[i % colors.length]}
strokeWidth={2}
dot={false}
isAnimationActive={false}
/>
))}
</ChartContainer>
);
}
function Soil({name, sensorName, end, duration}) {
const [data, loading, tickFormatter] = useSensor('soil', sensorName, end, duration);
@@ -790,6 +876,17 @@ function Graphs({end, duration}) {
<Lux name='Kitchen Lux' sensorName='Kitchen' end={end} duration={duration} />
<Lux name='Bedroom Lux' sensorName='Bedroom' end={end} duration={duration} />
<Lux name='Laundry Room Lux' sensorName='Laundry Room' end={end} duration={duration} />
<MultiLineChart
title='Pressure'
measurement='hpa'
dataKey='hpa'
sensors={['Kitchen', 'Bedroom', 'Laundry Room']}
colors={['black', 'red', 'blue']}
end={end}
duration={duration}
yDomain={[850, 915]}
unitKey='Hpa'
/>
<WH51Soil name='Side Garden Soil Moisture' sensorName='Side Garden' end={end} duration={duration} />
<Soil name='Dumb Cane Soil Moisture' sensorName='Dumb Cane' end={end} duration={duration} />
<Soil name='Kitchen Pothos Soil Moisture' sensorName='Kitchen Pothos' end={end} duration={duration} />
+64 -47
View File
@@ -445,7 +445,8 @@ async def history(request):
authed = api_key == settings.SENSORS_API_KEY
measurement = request.match_info.get('measurement')
name = request.match_info.get('name')
name_param = request.match_info.get('name')
names = name_param.split(',')
share_start = request.rel_url.query.get('shareStart', '')
share_end = request.rel_url.query.get('shareEnd', '')
@@ -458,8 +459,9 @@ async def history(request):
if not authed and measurement in ['owntracks', 'sleep']:
return web.json_response([])
if name not in [x.name for x in sensors.sensors]:
raise
for name in names:
if name not in [x.name for x in sensors.sensors]:
raise
end_unix = request.rel_url.query.get('end', None)
if end_unix:
@@ -496,13 +498,6 @@ async def history(request):
if window not in ['1m', '3m', '10m', '30m', '1h', '2h', '1d', '7d', '30d']:
raise
if name == 'Water':
scale = 10
elif name == 'Gas':
scale = 0.001055*1000
else:
scale = 1
start = int(start.timestamp())
end = int(end.timestamp())
@@ -512,47 +507,69 @@ async def history(request):
if end >= int(share_end):
end = int(share_end)
time_map = {}
if measurement == 'temperature':
client = sensors_client
q = 'select mean("temperature_C") as temperature_C, mean("humidity") as humidity from temperature where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'ertscm':
client = sensors_client
q = 'select derivative(max("consumption_data"))*{} as delta, max("consumption_data")*{} as max from ertscm where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(previous)'.format(scale, scale, name, start, end, window)
elif measurement == 'thermostat':
client = sensors_client
q = 'select first("spacetemp") as spacetemp, first("heattemp") as heattemp, mode("state") as state from thermostat where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(previous)'.format(name, start, end, window)
elif measurement == 'dust':
client = sensors_client
q = 'select max("avg_p10") as max_p10, max("avg_p25") as max_p25 from dust where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'air':
client = sensors_client
q = 'select max("pm10") as max_p10, max("pm25") as max_p25, max("co2") as max_co2, max("voc_idx") as max_voc from air where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'soil':
client = sensors_client
q = 'select mean("soil") as soil, mean("moisture") as moisture from soil where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'lux':
client = sensors_client
q = 'select mean("lux") as lux from air where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'hpa':
client = sensors_client
q = 'select mean("hpa") as hpa from air where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'sleep':
client = sensors_client
q = 'select max("max_mag") as max_mag from sleep where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'solar':
client = solar_client
q = 'select max("actual_total") as actual_total, last("lifetime_energy")-first("lifetime_energy") as lifetime_energy from ecu where time >= {}s and time < {}s group by time({}) fill(linear)'.format(start, end, window)
elif measurement == 'owntracks':
client = sensors_client
q = 'select first("lat") as lat, first("lon") as lon from owntracks where "acc" < 100 and "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(previous)'.format(name, start, end, window)
else:
raise
for name in names:
if name == 'Water':
scale = 10
elif name == 'Gas':
scale = 0.001055*1000
else:
scale = 1
q += ' tz(\'America/Edmonton\')'
if measurement == 'temperature':
client = sensors_client
q = 'select mean("temperature_C") as temperature_C, mean("humidity") as humidity from temperature where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'ertscm':
client = sensors_client
q = 'select derivative(max("consumption_data"))*{} as delta, max("consumption_data")*{} as max from ertscm where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(previous)'.format(scale, scale, name, start, end, window)
elif measurement == 'thermostat':
client = sensors_client
q = 'select first("spacetemp") as spacetemp, first("heattemp") as heattemp, mode("state") as state from thermostat where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(previous)'.format(name, start, end, window)
elif measurement == 'dust':
client = sensors_client
q = 'select max("avg_p10") as max_p10, max("avg_p25") as max_p25 from dust where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'air':
client = sensors_client
q = 'select max("pm10") as max_p10, max("pm25") as max_p25, max("co2") as max_co2, max("voc_idx") as max_voc from air where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'soil':
client = sensors_client
q = 'select mean("soil") as soil, mean("moisture") as moisture from soil where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'lux':
client = sensors_client
q = 'select mean("lux") as lux from air where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'hpa':
client = sensors_client
q = 'select mean("hpa") as hpa from air where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'sleep':
client = sensors_client
q = 'select max("max_mag") as max_mag from sleep where "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(linear)'.format(name, start, end, window)
elif measurement == 'solar':
client = solar_client
q = 'select max("actual_total") as actual_total, last("lifetime_energy")-first("lifetime_energy") as lifetime_energy from ecu where time >= {}s and time < {}s group by time({}) fill(linear)'.format(start, end, window)
elif measurement == 'owntracks':
client = sensors_client
q = 'select first("lat") as lat, first("lon") as lon from owntracks where "acc" < 100 and "name" = \'{}\' and time >= {}s and time < {}s group by time({}) fill(previous)'.format(name, start, end, window)
else:
raise
result = list(client.query(q).get_points())
q += ' tz(\'America/Edmonton\')'
points = list(client.query(q).get_points())
for p in points:
t = p['time']
if t not in time_map:
time_map[t] = {'time': t}
if len(names) > 1:
for k, v in p.items():
if k != 'time':
time_map[t][f"{name}_{k}"] = v
else:
time_map[t].update(p)
result = sorted(time_map.values(), key=lambda x: x['time'])
return web.json_response(result)