Add hwmon dashboard widget and fix EMC2302 fan stall detection

This commit is contained in:
Tomaz Zaman 2026-03-03 02:00:54 +01:00
parent f535564d2d
commit 55441f0eca
9 changed files with 324 additions and 2 deletions

View file

@ -99,10 +99,10 @@ build-pcf2131:
build-caam:
${MAKE} -C ${KMOD_CAAM} ${KMOD_ARGS}
modules: build-cdx build-fci build-auto_bridge build-pf_notify \
build-tmp431:
${MAKE} -C ${KMOD_TMP} ${KMOD_ARGS}
modules: build-cdx build-fci build-auto_bridge build-pf_notify \
build-emc2302 build-ina2xx build-lp5812 build-sfpled build-pcf2131 \
build-caam build-tmp431
@ -202,6 +202,9 @@ package: clean dist
# rc.syshook early scripts
install -m 755 ${PKG_RCDDIR}/01-growfs ${PKG_STAGEDIR}/usr/local/etc/rc.syshook.d/early/
install -m 755 ${PKG_RCDDIR}/02-mono-modules ${PKG_STAGEDIR}/usr/local/etc/rc.syshook.d/early/
# OPNsense plugin files (hwmon dashboard widget)
cp -R ${OPSDIR}/plugins/hwmon/src/opnsense/ ${PKG_STAGEDIR}/usr/local/opnsense/
chmod 755 ${PKG_STAGEDIR}/usr/local/opnsense/scripts/hwmon/sensors.py
# Generate manifest with version
sed 's/%%VERSION%%/${PKG_VERSION}/' ${PKG_METADIR}/+MANIFEST \
> ${PKG_STAGEDIR}/+MANIFEST

View file

@ -48,7 +48,7 @@
#define EMC2305_RPM_FACTOR 3932160
#define EMC2305_TACH_SHIFT 3 /* lower 3 bits unused */
#define EMC2305_TACH_MULTIPLIER 2
#define EMC2305_RPM_MIN 480
#define EMC2305_RPM_MIN 1000 /* stalled/missing fans read ~960 */
#define EMC2305_MAX_FANS 5

View file

@ -23,3 +23,10 @@
/usr/local/etc/rc.d/fand
/usr/local/etc/rc.syshook.d/early/01-growfs
/usr/local/etc/rc.syshook.d/early/02-mono-modules
@dir /usr/local/opnsense/scripts/hwmon
/usr/local/opnsense/scripts/hwmon/sensors.py
/usr/local/opnsense/service/conf/actions.d/actions_hwmon.conf
/usr/local/opnsense/mvc/app/controllers/OPNsense/Hwmon/Api/SensorsController.php
/usr/local/opnsense/mvc/app/models/OPNsense/Hwmon/ACL/ACL.xml
/usr/local/opnsense/www/js/widgets/Hwmon.js
/usr/local/opnsense/www/js/widgets/Metadata/Hwmon.xml

View file

@ -0,0 +1,19 @@
<?php
namespace OPNsense\Hwmon\Api;
use OPNsense\Base\ApiControllerBase;
use OPNsense\Core\Backend;
class SensorsController extends ApiControllerBase
{
public function statusAction()
{
$backend = new Backend();
$data = json_decode($backend->configdRun('hwmon sensors'), true);
if (!is_array($data)) {
return ['power' => [], 'fans' => [], 'temperatures' => []];
}
return $data;
}
}

View file

@ -0,0 +1,8 @@
<acl>
<page-hwmon-sensors>
<name>Diagnostics: Hardware Monitor</name>
<patterns>
<pattern>api/hwmon/*</pattern>
</patterns>
</page-hwmon-sensors>
</acl>

View file

@ -0,0 +1,140 @@
#!/usr/local/bin/python3
"""
Hardware sensor reader for Mono Gateway dashboard widget.
Discovers and reads INA2xx power monitors, EMC2302 fan controllers,
and TMU temperature sensors via sysctl.
"""
import json
import subprocess
import sys
def sysctl_tree(prefix):
"""Read all sysctls under prefix, return dict of name->value."""
sp = subprocess.run(
['/sbin/sysctl', '-i', prefix],
capture_output=True, text=True
)
result = {}
for line in sp.stdout.splitlines():
parts = line.split(': ', 1)
if len(parts) == 2:
result[parts[0].strip()] = parts[1].strip()
return result
def parse_power(raw):
"""Parse dev.ina2xx.* into power sensor list."""
# Group by device instance
instances = {}
for key, val in raw.items():
# dev.ina2xx.0.bus_voltage -> instance=0, field=bus_voltage
parts = key.split('.')
if len(parts) < 4 or parts[0] != 'dev' or parts[1] != 'ina2xx':
continue
try:
idx = int(parts[2])
except ValueError:
continue
field = '.'.join(parts[3:])
instances.setdefault(idx, {})[field] = val
sensors = []
for idx in sorted(instances):
fields = instances[idx]
label = fields.get('label', f'ina2xx.{idx}')
try:
voltage = int(fields.get('bus_voltage', 0))
current = int(fields.get('current', 0))
power = int(fields.get('power', 0))
except ValueError:
continue
sensors.append({
'label': label,
'voltage': voltage,
'current': current,
'power': power,
})
return sensors
def parse_fans(raw):
"""Parse dev.emc2302.* into fan list."""
# Group by controller then fan
controllers = {}
for key, val in raw.items():
parts = key.split('.')
if len(parts) < 5 or parts[0] != 'dev' or parts[1] != 'emc2302':
continue
try:
ctrl = int(parts[2])
except ValueError:
continue
fan_field = '.'.join(parts[3:])
# e.g. fan0.rpm, fan1.pwm
controllers.setdefault(ctrl, {})[fan_field] = val
fans = []
for ctrl in sorted(controllers):
fields = controllers[ctrl]
# Discover fan channels
fan_ids = set()
for k in fields:
if k.startswith('fan') and '.' in k:
fan_ids.add(k.split('.')[0])
for fan_id in sorted(fan_ids):
try:
rpm = int(fields.get(f'{fan_id}.rpm', 0))
pwm_raw = int(fields.get(f'{fan_id}.pwm', 0))
fault = int(fields.get(f'{fan_id}.fault', 0))
except ValueError:
continue
pwm_pct = round(pwm_raw * 100 / 255)
# Skip fans with 0 RPM (stalled or not connected)
if rpm == 0:
continue
fans.append({
'label': fan_id,
'rpm': rpm,
'pwm': pwm_pct,
'fault': fault != 0,
})
return fans
def parse_temperatures(raw):
"""Parse hw.temperature.* into temperature list."""
temps = []
for key, val in sorted(raw.items()):
if not key.startswith('hw.temperature.'):
continue
name = key.replace('hw.temperature.', '')
# Value is like "47.0C"
temp_str = val.rstrip('C').strip()
try:
temp = float(temp_str)
except ValueError:
continue
# Pretty-print the name: core-cluster -> Core Cluster
label = name.replace('-', ' ').replace('_', ' ').title()
temps.append({
'label': label,
'value': temp,
})
return temps
if __name__ == '__main__':
power_raw = sysctl_tree('dev.ina2xx')
fan_raw = sysctl_tree('dev.emc2302')
temp_raw = sysctl_tree('hw.temperature')
result = {
'power': parse_power(power_raw),
'fans': parse_fans(fan_raw),
'temperatures': parse_temperatures(temp_raw),
}
print(json.dumps(result))

View file

@ -0,0 +1,4 @@
[sensors]
command:/usr/local/opnsense/scripts/hwmon/sensors.py
type:script_output
message:Read hardware sensors

View file

@ -0,0 +1,126 @@
/*
* Copyright (C) 2026 Mono Technologies d.o.o.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
export default class Hwmon extends BaseTableWidget {
constructor() {
super();
this.tickTimeout = 10;
}
getGridOptions() {
return {
sizeToContent: 650
};
}
getMarkup() {
let $container = $('<div></div>');
let $powerHeader = $(`<div class="hwmon-section" id="hwmon-power-section">
<b><i class="fa fa-bolt"></i> ${this.translations.power}</b>
</div>`);
let $powerTable = this.createTable('hwmon-power', {
headerPosition: 'left',
});
let $fanHeader = $(`<div class="hwmon-section" id="hwmon-fan-section">
<b><i class="fa fa-fan"></i> ${this.translations.fans}</b>
</div>`);
let $fanTable = this.createTable('hwmon-fans', {
headerPosition: 'left',
});
let $tempHeader = $(`<div class="hwmon-section" id="hwmon-temp-section">
<b><i class="fa fa-thermometer-half"></i> ${this.translations.temperatures}</b>
</div>`);
let $tempTable = this.createTable('hwmon-temps', {
headerPosition: 'left',
});
$container.append($powerHeader, $powerTable, $fanHeader, $fanTable, $tempHeader, $tempTable);
return $container;
}
async onWidgetTick() {
const data = await this.ajaxCall('/api/hwmon/sensors/status');
if (!data || (!data.power?.length && !data.fans?.length && !data.temperatures?.length)) {
$('#hwmon-power-section').hide();
$('#hwmon-fan-section').hide();
$('#hwmon-temp-section').hide();
$('#hwmon-power').html(`<div style="margin: 1em;">${this.translations.nosensors}</div>`);
return;
}
// Power sensors
if (data.power?.length) {
$('#hwmon-power-section').show();
let powerRows = [];
data.power.forEach(s => {
let voltage = (s.voltage / 1000).toFixed(2);
let current = (s.current / 1000).toFixed(2);
powerRows.push([
s.label,
`${voltage} V &nbsp; ${current} A &nbsp; ${(s.power / 1000).toFixed(1)} W`
]);
});
super.updateTable('hwmon-power', powerRows);
} else {
$('#hwmon-power-section').hide();
}
// Fans
if (data.fans?.length) {
$('#hwmon-fan-section').show();
let fanRows = [];
data.fans.forEach(f => {
let status = f.fault
? '<i class="fa fa-exclamation-triangle text-danger"></i> Fault'
: `${f.rpm} RPM &nbsp; ${f.pwm}%`;
fanRows.push([f.label, status]);
});
super.updateTable('hwmon-fans', fanRows);
} else {
$('#hwmon-fan-section').hide();
}
// Temperatures
if (data.temperatures?.length) {
$('#hwmon-temp-section').show();
let tempRows = [];
data.temperatures.forEach(t => {
let color = t.value >= 80 ? 'text-danger' : (t.value >= 70 ? 'text-warning' : '');
let display = color
? `<span class="${color}">${t.value.toFixed(1)}&deg;C</span>`
: `${t.value.toFixed(1)}&deg;C`;
tempRows.push([t.label, display]);
});
super.updateTable('hwmon-temps', tempRows);
} else {
$('#hwmon-temp-section').hide();
}
}
}

View file

@ -0,0 +1,15 @@
<metadata>
<hwmon>
<filename>Hwmon.js</filename>
<endpoints>
<endpoint>/api/hwmon/sensors/status</endpoint>
</endpoints>
<translations>
<title>Hardware Monitor</title>
<power>Power</power>
<fans>Fans</fans>
<temperatures>Temperatures</temperatures>
<nosensors>No hardware sensors detected.</nosensors>
</translations>
</hwmon>
</metadata>