top of page

An Oil Temperature Gauge for the 420R, (Part 4)

4 hours ago
16 min read

In the previous posts on the oil temperature gauge for the 420R I covered the sender, the measurement and the hardware. This post covers the Wi-Fi side of the gauge, how it connects to a network, the web page it serves to a phone or desktop/laptop, and the data stream it sends to a device such as a laptop.


The data stream uses UDP multicast. Multicast isn't something most people come across, so I've explained how it works, how the packets are laid out, and how a laptop picks them up. Hope you enjoy!


Why Wi-Fi

The display is built around an ESP32-S3, which has Wi-Fi built in. On the car, the gauge's screen is the main thing, but there are times when it's useful to see the data somewhere else such as a phone to check data after a run, or a laptop to record the data alongside other logs.


By default Wi-Fi is off unless explicitly switched on, and isn't a requirement for any measurement to be taken, i.e. it is a completely optional feature. The gauge measures, checks for faults and raises alarms in exactly the same way with Wi-Fi on or off.


Switching Wi-Fi On

The four states, in the order the BOOT button steps through them
The four states, in the order the BOOT button steps through them

The BOOT button, the top button on the side of the display, switches Wi-Fi. Each short press moves to the next state;

  • off,

  • web page only,

  • web page and data stream,

  • data stream only.

A press of a second or more is ignored. The choice is always saved, so the gauge comes back in the same state at power-up.


A panel across the top of the screen confirms each press for three seconds. Once the gauge is on the network, the panel's second line says whether it joined or is hosting a Wi-Fi network, and gives the gauge's netwokrk address.

Hosting the network with IP address shown
Hosting the network with IP address shown

Joining or Hosting?

The same network name and password at home and at the circuit
The same network name and password at home and at the circuit

The network name and password are set when the firmware is built. When Wi-Fi is switched on, the gauge scans for that network.


The network is there

At home, the gauge joins the network as a client, the same as a phone or a laptop would. The router gives it an address, which the panel shows.


The network isn't there

At a circuit or out on the road there's no home router, so the gauge creates the network itself, with the same name and password. It becomes the access point, at the address 192.168.4.1 for example, and up to four devices can join it.

If the gauge has joined a network and that network drops, the gauge tries to rejoin it, and if it has gone, the gauge starts hosting the network itself.

Note although the Wi-fi SSID or name is the same as the home network along with the password, the Wi-Fi is not considered the same. Use of the same name and password is used for convienence only to avoid building a UI for setting Wi-Fi details.


Data Access


The measurement loop hands data over and never waits for the network
The measurement loop hands data over and never waits for the network

The temperature measurement runs in the gauge's main software loop, four times a second. The gauge's network activity runs in separate tasks at the lowest priority, below the main loop, so it can't hold up a measurement. Thus the main loop never waits for the network.


For the web page, it adds one row a second to a log in memory function. For the data stream, it leaves the latest reading in a "mailbox" for the Wi-Fi task to send. If the Wi-Fi task hasn't sent the previous packet by the time the next one arrives, the old one is replaced, not queued. A slow or busy network therefore loses a packet rather than delaying a reading or an alarm.


Web Page

The web page is designed for phone use and therefore pretty basic although it work perfectly well in a desktop browser. With the phone on the same network, opening the address shown on the gauge's panel in the phone's browser brings up the page. Nothing needs installing. When the gauge is hosting the network, the phone may warn that the network has no internet, and needs telling to stay connected.

Web view as shown on a desktop browser
Web view as shown on a desktop browser

What it shows

A copy of the gauge's Sweep dial with the live reading and status, the session maximum, the rate of change, the warm-up time, a chart of the whole session with the alarm thresholds marked, the time spent in each temperature band, and the measurement voltages.


Where it comes from

The page is a single file of about 32 KB, built into the firmware. It loads nothing from the internet, so it works at a circuit with no mobile signal.


How it gets the data

When the page opens, it asks the gauge for its thresholds and colours once. Then, once a second, it asks for any log rows it doesn't have yet. The gauge answers in JSON, a plain text format for data.


A trimmed example of one answer is shown below;

{"v":1,"session":"2161ab7c","first":0,"next":1843,"demo":false,"calibrated":true,
 "now":{"status":9,"alarm":9,"temp":92.4,"ohms":262.1,"max":94.0,"warmup":"WARM IN 6:12", ...},
 "bands":[372000,1105000,0,0,4500],
 "rows":[[1840,1840250,9,9,92.4,262.1,0.4866,0.0655,3.3169,-0.0021], ...]}

Each row holds the following;

  • a row number,

  • time since power-up in milliseconds,

  • status,

  • alarm,

  • temperature,

  • sender's resistance; and

  • four measurement voltages.


From power-up, whether Wi-Fi is on or not, the gauge records one row a second, and keeps the last 8 hours: 28,800 rows, about 1 MB, in the display's PSRAM. A phone that connects halfway through a day still gets the whole session. If the phone is locked or goes out of range, the next request picks up from the last row it has, up to 600 rows at a time, until it has caught up. The page saves the session in the phone browser's own storage as the rows arrive, so reloading the page or restarting the gauge doesn't lose it. The last three sessions are kept, and a Download CSV button saves a session as a spreadsheet file.

The page doesn't calculate a temperature, a colour or an alarm. It shows the gauge's values. With no temperature (a fault, an uncalibrated gauge, or a reading beyond the calibration table), the temperature is sent as null, and the page shows no temperature and leaves a gap in the chart rather than joining the line across it.

Further The page shows how long ago the gauge last answered. After 3 seconds with no answer the line turns amber, and after 10 seconds it turns red, the dial greys out and shows NO DATA, so an old reading is never mistaken for a live one.

The gauge's web server answers three requests;

  1. the page,

  2. its thresholds and colours;

  3. and the log.

Any other requests will generate an error, and additional nothing on the page can change a setting on the gauge. The page isn't encrypted, so anyone on the same network who knows the address could read it, but when the gauge is hosting the network that's only someone with the Wi-Fi password.


Data Stream

The data stream is for a laptop, or something like a Raspberry Pi. Four times a second, after every measurement, the gauge sends one small packet containing everything it measured, using UDP multicast. A program on the laptop listens for the packets and shows or records them.


UDP

Data sent over a network is split into packets. Most of what a laptop or phone does, such as loading a web page, uses TCP, which sets up a connection between two devices, numbers the packets, and resends any that go missing, so everything arrives complete and in order.


UDP is much simpler. Each packet is transmitted independently, without establishing a connection beforehand or retransmitting lost packets. This makes UDP particularly well suited to real-time telemetry applications, such as transmitting temperature readings, where occasional packet loss is acceptable and the most recent data is more valuable than historical readings. Retransmitting a lost reading half a second later serves little purpose, as the data may already be outdated by the time it arrives. The gauge does not need to maintain connection states, track recipients or wait for acknowledgements. If a packet is lost, a fresh reading follows just a quarter of a second later, naturally superseding the missing data. This approach minimises communication overhead and latency while prioritising the timely delivery of current readings.


Every UDP packet is sent to a destination IP address and port number. The IP address identifies either a specific device (unicast) or a group of interested receivers (multicast). The destination port identifies the application or service intended to receive the data. In this implementation, the gauge transmits telemetry to UDP port 5005, allowing any receiving application listening on that port, and configured for the appropriate destination address, to receive and process the readings.


Unicast, Broadcast and Multicast

There are three common methods of addressing UDP packets on an IPv4 network, each offering a different approach to distributing data.


Unicast

A packet is sent directly to the IP address of a specific device. This is how most conventional network communication operates. The sender must know the IP address of each recipient and transmit a separate copy of the packet to each one. For the gauge, this would require maintaining a list of receiving devices and updating their addresses whenever they connect to a different network. Network traffic and processing overhead also increase with each additional recipient.


Broadcast

A packet is sent to all devices within the local broadcast domain. The sender does not need to know the individual IP addresses of the recipients. However, every device within that broadcast domain receives the traffic, regardless of whether it has any interest in the data. This introduces unnecessary network traffic and processing overhead for unrelated devices.


Multicast

A packet is sent to a designated multicast group address rather than to individual devices. Applications interested in receiving the data explicitly subscribe to the multicast group. The sender transmits a single copy of each packet, and the network is responsible for distributing it to participating receivers, where multicast-aware infrastructure is available. The sender does not need to know the identity, IP address or number of receiving devices.


Multicast is particularly well suited to the gauge's telemetry requirements. The gauge continuously transmits readings to the same multicast group, regardless of whether there are zero, one or multiple receivers. Receiving applications can independently join or leave the group at any time without requiring any configuration changes or interaction with the gauge. This provides a loosely coupled, scalable and efficient communication model, allowing multiple applications to consume real-time telemetry without increasing the transmission overhead on the gauge itself.


Group Addresses

IPv4 multicast group addresses occupy a reserved address range from 224.0.0.0 to 239.255.255.255. Unlike conventional unicast addresses, these addresses identify multicast groups rather than individual network interfaces. Within this range, the block from 239.0.0.0 to 239.255.255.255 is reserved for administratively scoped multicast, allowing organisations and applications to define multicast groups for use within private network boundaries. This is conceptually similar to the use of private unicast address ranges, such as 192.168.x.x. By default, the gauge transmits telemetry to multicast group address 239.10.10.10 using UDP port 5005. Both parameters are configurable within the firmware, providing flexibility to accommodate different network environments, avoid conflicts with existing multicast services or establish separate telemetry groups.


Multicast subscription and network behaviour


Joining and leaving a multicast group

An application wishing to receive the telemetry stream must perform two operations:

  1. Open a UDP socket bound to port 5005.

  2. Request that the operating system join the multicast group 239.10.10.10 on the appropriate network interface.


The operating system manages multicast group membership using IGMP (Internet Group Management Protocol), informing the local network infrastructure that the device is interested in receiving traffic addressed to the specified multicast group. Incoming packets matching the multicast group and destination port are subsequently delivered to the receiving application.

When the application closes its socket or explicitly leaves the multicast group, the operating system withdraws its membership, provided no other application on the device requires membership of the same group on that interface.

The entire subscription process operates independently of the gauge. Receiving applications can dynamically join or leave the multicast group without requiring configuration changes, establishing a connection with the gauge or interrupting its operation.


Network infrastructure and traffic distribution

Network switches and wireless access points that support IGMP snooping use multicast membership messages to determine which network ports require multicast traffic. This allows the network infrastructure to distribute telemetry selectively, rather than unnecessarily forwarding it to every connected device.

When the gauge connects to an existing wireless network, multicast delivery depends on the capabilities and configuration of the local network infrastructure. Although most domestic networking equipment supports local multicast distribution, certain configurations, such as wireless client isolation, guest networks and multicast filtering, may prevent successful delivery.


Multicast over Wi-Fi

Wireless networks handle multicast traffic differently from conventional unicast traffic. These differences have implications for the reliability, latency and distribution of the telemetry stream.


Wireless transmission

Under conventional multicast operation, a wireless access point transmits each multicast packet as a shared wireless transmission rather than sending an individual copy to every connected device.


Devices that are not members of the multicast group discard the traffic. Some wireless access points implement multicast-to-unicast conversion, whereby multicast packets are converted into individual unicast transmissions for participating devices. This can improve delivery reliability but increases wireless bandwidth consumption as the number of receivers grows.

Multicast transmissions may also use lower wireless data rates than unicast transmissions to accommodate devices with weaker signal strength. Although this increases airtime consumption, the relatively low volume and frequency of the gauge's telemetry stream limit its impact on overall network performance.


Packet delivery and retransmission

Standard Wi-Fi unicast transmissions use link-layer acknowledgements and automatic retransmissions to improve delivery reliability. Conventional multicast transmissions do not benefit from these mechanisms, meaning occasional packet loss is expected, particularly in environments experiencing wireless interference, congestion or poor signal strength.


Each telemetry packet contains a sequence number, allowing receiving applications to:

  • Identify missing packets and measure packet loss.

  • Detect and discard duplicate packets.

  • Identify packets arriving out of sequence.

  • Monitor the continuity of the telemetry stream.


Missing readings are neither reconstructed nor estimated, ensuring that receiving applications only present genuine measurement data. The continuous transmission of fresh readings removes the need to recover lost historical data.


Power saving and transmission latency

Wireless access points may temporarily buffer multicast traffic to accommodate connected devices operating in power-saving mode. Buffered multicast packets are released following beacon frames containing a Delivery Traffic Indication Message (DTIM). When the gauge operates as a wireless access point, it configures the DTIM period to one beacon interval, approximately 100 milliseconds. This minimises the additional latency introduced by multicast buffering and supports the timely delivery of telemetry. When connected to an existing wireless network, the gauge has no control over the access point's DTIM configuration. Consequently, multicast delivery latency may vary depending on the network configuration.


Client compatibility and connectivity


Mobile devices and browser compatibility

Native mobile applications may require additional operating system permissions or network configuration to receive multicast traffic. These requirements vary depending on the operating system and its network security and power management policies. For this reason no mobile application has been built. Standard web browsers do not provide direct access to UDP sockets or IP multicast groups. This is one of the principal reasons the gauge provides a complementary web-based interface, allowing smartphones, tablets and other browser-enabled devices to access telemetry without requiring a dedicated application.


Firewall configuration

Local firewall policies on receiving devices may restrict incoming UDP traffic, preventing otherwise correctly configured applications from receiving the telemetry stream. Receiving devices must permit inbound UDP traffic destined for the configured multicast group and port.

The default configuration is:

Parameter

Default value

Transport protocol

UDP

Multicast group

239.10.10.10

Destination port

5005

Traffic direction

Inbound to the receiver

Network scope

Local network

Where possible, firewall rules should be restricted to the relevant multicast group, destination port and trusted network interfaces, rather than permitting unrestricted inbound UDP traffic.


Security and network containment

Network scope

The gauge transmits multicast packets with an IP Time to Live (TTL) value of 1. Routers decrement the TTL when forwarding IP packets, discarding packets that cannot be forwarded without the TTL reaching zero. This configuration confines the telemetry stream to the originating local IP network under normal routing conditions, preventing its propagation across conventional routed network boundaries. It is important to distinguish network containment from security enforcement. TTL is a network-scoping mechanism and does not provide authentication, confidentiality or access control. Any device with suitable network access and multicast reception capabilities may potentially receive the telemetry stream.


Unidirectional communication

The multicast telemetry interface is designed exclusively as a transmission mechanism. The gauge does not listen for incoming traffic on UDP port 5005, process requests from receiving applications or accept commands through the multicast telemetry interface.


This design provides several architectural benefits:

  • Reduced attack surface: No inbound telemetry service is exposed on the gauge.

  • Loose coupling: Receiving applications operate independently of the gauge and each other.

  • Predictable resource consumption: Transmission overhead remains independent of the number of receivers.

  • Operational resilience: The failure, disconnection or restart of a receiving application does not affect the gauge's operation.

  • Configuration simplicity: The gauge does not maintain client connections, recipient addresses or subscription state.


The multicast interface therefore provides a lightweight, connectionless and unidirectional telemetry distribution mechanism that prioritises measurement freshness, operational independence and efficient use of the gauge's available processing and network resources.


The UDP Packet

real packet, with each field's bytes and its value
real packet, with each field's bytes and its value

Every packet is 56 bytes long, with each field at a fixed position. The packet above is one of the test packets used to check the firmware, decoded field by field.


Bytes

Field

What it holds

0–3

magic

the letters OILG, so a listener can reject anything that isn't from the gauge

4

version

1. Any change to the layout will raise the version, and a listener skips versions it doesn't know.

5

length

56, the length of the whole packet

6–7

flags

five yes/no values, described below

8–11

session

a random number chosen at power-up. A new session means the gauge has restarted.

12–15

sequence

0 at power-up, then one more for each packet. A gap means lost packets.

16–19

uptime_ms

the time since power-up in milliseconds. The gauge has no clock.

20

status

the gauge's status, as a code from 0 to 11

21

alarm

the latched alarm: 9 normal, 10 high temperature, 11 critical

22–23

reserved

always 0

24–27

temp_c

the temperature in °C, only when flag bit 2 is set

28–31

resistance_ohms

the sender's resistance in ohms

32–43

ref_v, sender_v, supply_v

the voltage across the reference resistor, across the sender, and the 3.3 V supply

44–47

ground_offset_v

the voltage between the gauge's ground and the tank

48–51

max_c

the session's maximum temperature

52–55

crc32

a check value worked out from bytes 0 to 51

The status codes:

Code

Status

Code

Status

0

ADC UNAVAILABLE

6

BELOW CAL RANGE

1

SUPPLY FAULT

7

ABOVE CAL RANGE

2

GROUND FAULT

8

OIL WARMING

3

SENSOR SHORT

9

NORMAL

4

SENSOR OPEN

10

HIGH TEMPERATURE

5

CALIBRATION REQUIRED

11

CRITICAL TEMP

The flags, one bit each:

Bit

Value

Meaning when set

0

1

calibrated: a verified calibration is built into the firmware

1

2

demo build: the readings are synthetic and not real

2

4

has a temperature: temp_c holds a reading

3

8

the maximum went above the calibration table

4

16

a maximum exists

In the example the flags are 0x0015, which is 1 + 4 + 16: calibrated, has a temperature, and a maximum exists.


Encoding

Decoding the temperature in the example packet
Decoding the temperature in the example packet

Byte order (little-endian)

All multi-byte numerical values within the telemetry payload are encoded using little-endian byte order, meaning the least significant byte is transmitted first. This is consistent with the native byte order of the ESP32 and most modern desktop and laptop processors, simplifying encoding and decoding. For example, the 32-bit sequence number 1842, represented in hexadecimal as 0x00000732, is transmitted as the following four bytes: 32 07 00 00. Explicitly defining the byte order ensures consistent interpretation of the telemetry data, regardless of the receiving application's platform or programming language.


Floating-point representation

Temperature, resistance and voltage measurements are encoded as 32-bit, single-precision floating-point numbers in accordance with the IEEE 754 binary32 standard. Each value occupies four bytes and consists of a single sign bit, an 8-bit exponent and a 23-bit fraction field. This standardised representation provides sufficient precision and dynamic range for the gauge's measurement requirements while maintaining a compact telemetry payload. Floating-point values are also transmitted in little-endian byte order. The use of an internationally recognised numerical format ensures interoperability across different processor architectures, operating systems and programming languages without requiring proprietary numerical encoding or conversion mechanisms.


Some decimal values cannot be represented exactly using 32-bit floating-point numbers. For example, 92.4 is represented as approximately 92.4000015. The receiving application rounds the value to one decimal place for display, consistent with the gauge.


When a measurement is unavailable, such as during a sensor fault, the gauge transmits a special floating-point value known as NaN (Not a Number), represented by the bytes 00 00 C0 7F. Receiving applications must only display temperature readings when status flag bit 2 is set and the value is valid. Without verified calibration, the gauge does not provide valid current or maximum temperature readings. Values are never estimated or substituted.


The final four bytes contain a CRC-32 checksum calculated over the preceding 52 bytes. The receiving application recalculates the checksum and discards the packet if the values do not match. This provides an additional integrity check beyond UDP's optional 16-bit checksum in IPv4. The CRC-32 algorithm is the same as that used by Ethernet and ZIP files and is readily available in most programming languages, such as Python's zlib.crc32().


Each telemetry payload is 56 bytes, increasing to 84 bytes when the UDP and IPv4 headers are included. At four transmissions per second, the stream generates just 336 bytes per second, excluding wireless framing overhead, placing minimal demand on the Wi-Fi network.


Listening on a laptop

Python's standard library has everything need to receive and decode the stream. This short program joins the group, checks each packet, and prints the reading:

import socket
import struct
import zlib

GROUP, PORT = '239.10.10.10', 5005
PACKET = struct.Struct('<4sBBHIIIBBH7fI')  # 56 bytes, little-endian
STATUS = ['ADC UNAVAILABLE', 'SUPPLY FAULT', 'GROUND FAULT', 'SENSOR SHORT', 'SENSOR OPEN',
          'CALIBRATION REQUIRED', 'BELOW CAL RANGE', 'ABOVE CAL RANGE', 'OIL WARMING',
          'NORMAL', 'HIGH TEMPERATURE', 'CRITICAL TEMP']

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', PORT))
# Join the group. From here on, packets sent to 239.10.10.10 are passed to this program.
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                socket.inet_aton(GROUP) + socket.inet_aton('0.0.0.0'))

while True:
    data, sender = sock.recvfrom(1024)
    if len(data) != PACKET.size:
        continue                                   # not one of ours
    (magic, version, length, flags, session, sequence, uptime_ms, status, alarm, _,
     temp_c, ohms, ref_v, sender_v, supply_v, ground_v, max_c, crc) = PACKET.unpack(data)
    if magic != b'OILG' or version != 1 or zlib.crc32(data[:52]) != crc or status >= len(STATUS):
        continue                                   # wrong format, or damaged
    reading = f'{temp_c:.1f} °C' if flags & 4 else '--'   # bit 2: it has a temperature
    print(f'#{sequence}  {STATUS[status]}  {reading}  {ohms:.1f} ohm')

The string '<4sBBHIIIBBH7fI' describes the whole packet to Python's struct module. < means little-endian, 4s is the four magic letters, B is one byte, H is two bytes, I is four bytes, and 7f is the seven floating-point values.


Fed with the gauge's test packets, it prints:

#1842  NORMAL  92.4 °C  262.1 ohm
#5000  HIGH TEMPERATURE  117.6 °C  118.9 ohm
#9100  SENSOR OPEN  --  nan ohm
#15  CALIBRATION REQUIRED  --  123.4 ohm

Monitor Use

For proper use there's a fuller program in the project, udp_listen.py, which also uses only Python's standard library. It shows a live dashboard in a terminal window with;

  1. readings in large digits,

  2. coloured by the gauge's status,

  3. latched alarm,

  4. session maximum,

  5. trend,

  6. a chart of the last 5 minutes with the alarm thresholds marked,

  7. measurement voltages;

  8. and a count of packets received, lost and duplicated.

udp_listen.py client python script
udp_listen.py client python script

The script uses the session and sequence numbers to keep track of the stream. A gap in the sequence is counted as lost packets, a repeated sequence number is skipped, and a new session is noted as a gauge restart. If the packets stop, the status bar turns amber after 2 seconds, and after 10 seconds a red STREAM LOST banner appears and the reading greys out, so an old reading never looks live.


With --csv used a startup the script also writes every packet to a CSV file, with the laptop's own clock added to each row, which makes it straightforward to line the oil temperature up against other logs from the same session, should you have them.


A display freeze with Wi-Fi on

Introducing the web interface exposed a memory management issue. After flashing the new firmware, rebooting the gauge and enabling Wi-Fi, the display froze. Screen updates stopped and the long-press functionality became unresponsive. However, measurements continued in the background, with the serial log still reporting readings once per second.


The serial log revealed that every display frame was failing due to an out-of-memory error. The display's drawing buffers were located in external PSRAM, which the display interface could not transfer data from directly. Consequently, each frame required approximately 46 KB of contiguous internal memory as a temporary transfer buffer. The introduction of Wi-Fi and the web server had fragmented the available internal memory to the point where a sufficiently large contiguous block was no longer available, causing every frame update to fail.


The solution was to allocate two dedicated display buffers directly in internal memory, requiring approximately 37 KB in total. These buffers are allocated once during initialisation, before Wi-Fi and the web server start, eliminating the need for temporary memory allocations during display updates.


Following deployment of the revised firmware, the display has continued to operate correctly with Wi-Fi enabled, including normal screen updates and touch interaction.


Watch this space. More to follow in a future post.

Comments


follow me
  • Twitter Social Icon
  • White YouTube Icon
Meet Mark
Loves cars, light weight specials, jDM, Lotus, Caterham, Rallying and Trackdays
Mark Rodman Isle of Man CTRMint
bottom of page