The problem with a connected building is the translator, not the sensor
A building already has its sensors. The problem faced by whoever develops software for a smart building is that each one speaks a different language: the electricity meter answers on Modbus, the air conditioner on BACnet, the lights on KNX or DALI. Your software does not need to know any of these languages. It needs to know a single message schema, and hand over to a small on-site program, the gateway, the job of translating. This article walks through the three points where translation breaks in practice: the MQTT topic schema, reading a Modbus register, and regulating temperature when the sensor is noisy.
European legislation pushes in the same direction: Directive (EU) 2024/1275 on the energy performance of buildings provides, in Article 13, that building automation and control systems must be able to monitor, log, analyse and allow adjustment of energy use. For a programmer this means continuous measurement is not an optional extra of a pilot project. The three listings are in TypeScript, run with Node 24; none of them talks to real hardware, and we say so where it matters.
The topic schema is your building's API
MQTT is a publish-and-subscribe protocol: the gateway publishes a reading on a topic (a
string of levels separated by /) and anyone subscribed to that topic receives it. The broker
does not know the data: it knows the names. That is why the naming schema is the real contract of the
system, and the first decision to take with care. The listing that follows implements the filter matching
rules described in the OASIS MQTT 5.0 specification, section 4.7, and tests them on a
edificio/<id>/<zona>/<grandezza>/<sensore> schema.
// MQTT 5.0 rules, section 4.7: '+' = one level, '#' = all remaining levels (tail only),
// and a filter that starts with a wildcard does NOT see topics that start with '$'.
export function corrisponde(filtro: string, topic: string): boolean {
const f = filtro.split('/');
const t = topic.split('/');
if (topic.startsWith('$') && (f[0] === '#' || f[0] === '+')) return false;
for (let i = 0; i < f.length; i++) {
if (f[i] === '#') return i === f.length - 1; // '#' is valid only as the last level
if (i >= t.length) return false;
if (f[i] !== '+' && f[i] !== t[i]) return false;
}
return f.length === t.length;
}
// Topic schema: building / zone / quantity / sensor
const prove: [string, string][] = [
['edificio/lecce-01/+/co2/+', 'edificio/lecce-01/aula-3/co2/s1'],
['edificio/lecce-01/+/co2/+', 'edificio/lecce-01/aula-3/temp/s1'],
['edificio/lecce-01/#', 'edificio/lecce-01'],
['edificio/+/aula-3/#', 'edificio/lecce-02/aula-3/co2/s1'],
['#', '$SYS/broker/uptime'],
['$SYS/#', '$SYS/broker/uptime'],
['edificio/#/co2', 'edificio/lecce-01/co2'],
];
for (const [filtro, topic] of prove) {
console.log(`${corrisponde(filtro, topic) ? 'SI ' : 'NO '} ${filtro} <- ${topic}`);
}
// Output:
// SI edificio/lecce-01/+/co2/+ <- edificio/lecce-01/aula-3/co2/s1
// NO edificio/lecce-01/+/co2/+ <- edificio/lecce-01/aula-3/temp/s1
// SI edificio/lecce-01/# <- edificio/lecce-01
// SI edificio/+/aula-3/# <- edificio/lecce-02/aula-3/co2/s1
// NO # <- $SYS/broker/uptime
// SI $SYS/# <- $SYS/broker/uptime
// NO edificio/#/co2 <- edificio/lecce-01/co2
The seven tests show the rules you get wrong most easily. The + wildcard replaces a single
level, so edificio/lecce-01/+/co2/+ picks up the CO2 readings of all zones but not the
temperatures. The # wildcard replaces all the remaining levels and can only be at the end: the
filter edificio/#/co2 is not valid, and the listing rejects it. The third case is subtle: the
specification states that sport/# also matches sport itself, because the
# includes the parent level. The last rule concerns topics that start with $,
reserved to the broker (for example $SYS/): a filter that starts with a wildcard does not see
them. The # filter therefore does not receive the broker's service messages, but
$SYS/# does.
Put the building identifier at the first level, because it is the one you will filter on most and the one on which you will apply permissions (each gateway may publish only under its own building). Put the quantity before the sensor, because "all the CO2 of the building" is a more frequent question than "everything sensor s1 says". One last note on quality of service: QoS 1 means at least once, and the specification says so explicitly, so the receiver may see the same message twice. For a temperature reading that is harmless; for a cumulative energy counter, a duplicate does not change the value, but for an event such as "open the valve" it must be made idempotent.
A Modbus register is 16 bits, the rest is decided by the manufacturer
Modbus is the protocol of energy meters, inverters and controllers. In the responses the specification (Modbus Application Protocol, section 4.2) fixes just one thing: data is big-endian, that is, the most significant byte travels first. A register is 16 bits. A 32-bit floating-point number takes two of them, and the specification I read says nothing about how they are ordered: it is decided by whoever built the device. Two swapped halves do not give an error, they give a number that looks valid.
// A Modbus register is a 16-bit integer. A 32-bit float takes two, and the ORDER of the
// two halves is decided by the meter's manufacturer, not by the protocol.
function floatDaRegistri(alto: number, basso: number, ordine: 'ABCD' | 'CDAB'): number {
const buf = new DataView(new ArrayBuffer(4));
const [r0, r1] = ordine === 'ABCD' ? [alto, basso] : [basso, alto];
buf.setUint16(0, r0, false); // false = big-endian: Modbus sends the high octet first
buf.setUint16(2, r1, false);
return buf.getFloat32(0, false);
}
// Build the two registers a meter would send for a voltage of 231.4 V.
const w = new DataView(new ArrayBuffer(4));
w.setFloat32(0, 231.4, false);
const r0 = w.getUint16(0, false);
const r1 = w.getUint16(2, false);
console.log(`registri letti: 0x${r0.toString(16)} 0x${r1.toString(16)}`);
console.log('ordine ABCD :', floatDaRegistri(r0, r1, 'ABCD').toFixed(2), 'V');
console.log('ordine CDAB :', floatDaRegistri(r0, r1, 'CDAB'));
// Other family of meters: signed 16-bit integer with a scale factor of 0.1 (e.g. 2314 = 231.4 V)
function interoScalato(reg: number, scala: number): number {
const conSegno = reg > 0x7fff ? reg - 0x10000 : reg;
return Math.round(conSegno * scala * 1000) / 1000;
}
console.log('2314 con scala 0.1 :', interoScalato(2314, 0.1), 'V');
console.log('0xFFEC con scala 0.1:', interoScalato(0xffec, 0.1), '(una temperatura di -2,0 gradi)');
// Output:
// registri letti: 0x4367 0x6666
// ordine ABCD : 231.40 V
// ordine CDAB : 2.718469112112857e+23
// 2314 con scala 0.1 : 231.4 V
// 0xFFEC con scala 0.1: -2 (una temperatura di -2,0 gradi)
The listing first builds the two registers a meter would send for 231.4 V (0x4367 and
0x6666), then decodes them in both orders. With ABCD, the first half is the high one, and it
gets 231.40; with CDAB it swaps the halves and gets 2.7 times 10 to the power of 23: no exception, no
warning, a value that is clearly absurd for a voltage but that in the logs of a system without range checks
would go unnoticed. The countermeasure is one of process, not code: at commissioning you read a known value
(the mains voltage, or a temperature you can measure with another instrument) and check which order returns
it, then write it in that device's configuration.
The last two lines show the other family of devices, which sends a 16-bit integer with a scale factor.
Register 2314 with scale 0.1 is 231.4 V; the value 0xFFEC is a signed integer and equals −20,
so −2.0 with the same scale. Forgetting the signed interpretation is the classic error with below-zero
temperatures, which show up as 6,551.6. And one last trap, documented in the specification: registers are
addressed starting from zero, so what the manufacturer's table numbers as register 1 is read at address 0
(the specification says registers 1-16 have addresses 0-15). If the readings come out shifted by one, start
here.
Regulating without making the relay click every minute
The last step is to use the measurements to command something, for example to switch the heating on. The naive rule is "if the temperature is below the setpoint, switch on; otherwise switch off". With a noisy sensor (and all of them are) the temperature oscillates around the setpoint by a few tenths of a degree, and the plant switches continuously: it wastes energy, wears the relay and the compressor, and disturbs whoever is in the room. The solution is called hysteresis: it switches on below the setpoint minus half the band and switches off above the setpoint plus half the band, so inside the band it does nothing.
// Simplified room: every minute the temperature moves towards the outside (loss) and rises if the
// heating is on. It is not a physical model of the building: it is there to count the switchings.
function prng(seed: number) {
let s = seed >>> 0;
return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 2 ** 32);
}
function simula(isteresi: number, setpoint: number): { commutazioni: number; minutiAcceso: number } {
const rnd = prng(42);
let temp = 19;
let acceso = false;
let commutazioni = 0;
let minutiAcceso = 0;
const esterna = 8;
for (let minuto = 0; minuto < 12 * 60; minuto++) {
const misura = temp + (rnd() - 0.5) * 0.4; // sensor noise: +-0.2 degrees
const volere = acceso ? misura < setpoint + isteresi / 2 : misura < setpoint - isteresi / 2;
if (volere !== acceso) {
acceso = volere;
commutazioni++;
}
temp += (esterna - temp) * 0.004 + (acceso ? 0.08 : 0);
if (acceso) minutiAcceso++;
}
return { commutazioni, minutiAcceso };
}
for (const isteresi of [0, 1]) {
const r = simula(isteresi, 21);
console.log(`isteresi ${isteresi} gradi: commutazioni=${r.commutazioni}, minuti acceso=${r.minutiAcceso} su 720`);
}
// Output:
// isteresi 0 gradi: commutazioni=337, minuti acceso=488 su 720
// isteresi 1 gradi: commutazioni=29, minuti acceso=485 su 720
The simulation is a toy model: the room loses heat towards the outside (8 degrees) in proportion to the difference, the heating adds 0.08 degrees per minute, the sensor is off by ±0.2 degrees. It describes no real building and must not be used to size a plant. It serves to show something that does not depend on the coefficients: with zero hysteresis the thermostat switches 337 times in 12 hours, with a one-degree band 29 times, for the same minutes of operation (488 against 485 out of 720). Comfort is the same and the switchings are a twelfth. The exact number changes with the model and the seed; the order of magnitude of the difference is what matters, and your real plant must be measured.
As for the idea of lowering the setpoint when the room is empty (setback), here we did not measure the saving, and we do not publish percentages: the ones in circulation depend on the climate, the building and how the baseline consumption is measured, and without a source we do not repeat them. The honest way to find out is a comparison on your building, with a reference period and a test period under the same weather conditions. The presence signal comes from sensors you already have (CO2, motion, door), but it remains a signal: it decides the setback but must not be treated as truth.
Security lies outside the protocols
The Modbus specification I consulted contains no authentication or encryption mechanisms: whoever reaches the port can read and, if the device allows it, write. That is why the gateway must never be exposed directly, and the plant network must be kept separate from the office network, with the gateway alone as a bridge, outbound, to the broker. We have not verified the security features of the individual building automation protocols and make no claims about them: check them in your plant's documentation before connecting it to an IP network.
Where the rest of the series connects
The readings published by the gateway are the raw material for two other articles: the real-time data pipeline shows how to handle events that arrive late or duplicated (what QoS 1 can produce), and property management with agents uses the same readings to decide when a machine must be checked. The association between a sensor and the room it is in is instead the subject of the BIM model. Where the readings are stored for the long term, with partitions and rollups, is shown by the article on sensor time series in PostgreSQL.
What you can do now
You can design an MQTT topic schema that holds up under filters and permissions, and you know what
+, # and topics with $ really do. You can read a Modbus register
without falling into the three classic errors (order of the halves, sign, address starting from zero) and
you know it is verified with a known value. You can keep a noisy sensor from making a plant oscillate, and
you have seen the effect of hysteresis on a model declared a toy. What remains to be done with real
hardware: read your meter's registers from the manufacturer's manual, measure consumption before and after,
and verify the security of your plant.
In this series, the next article is Mortgage Applications: States, Amortization and Deadlines.
Sources
- OASIS, MQTT Version 5.0, sections 4.3 and 4.7 - quality of service (QoS 1 at least once) and the rules for wildcards and topics with $, accessed on 2026-11-12
- Modbus Organization, MODBUS Application Protocol Specification V1.1b3 - big-endian encoding (section 4.2), function 03 and register addressing from zero (section 6.3), accessed on 2026-11-12
- Directive (EU) 2024/1275 on the energy performance of buildings, Article 13 - the capabilities required of building automation and control systems, accessed on 2026-11-12
The three listings were run with Node 24 on 2026-11-12; none of them communicates with real hardware. The thermostat simulation uses a pseudo-random generator with a fixed seed and a toy model: the numbers are those of that run.

Commenti
Caricamento commenti...
Sign in to comment