Import Energy Statistics using Websockets

I have created a dummy energy sensor. I am using n8n to retrieve data from my energy provider and import it into Home Assistant. Unfortunately, the data from my energy provider is only available for the previous day. While the import works perfectly, the current day’s data is always displayed incorrectly because the sensor’s current total is always shown as zero.

How can I set the current total value of the sensor to match the last statistic value, so that at least a zero is displayed for the current day?

n8n script

const WebSocket = require("ws");
const serverUrl = 'wss://your-websocket-url/api/websocket'; // Ersetzen durch tatsächliche URL
const awaitingResponses = new Map(); // Track sent messages and responses
const entityName = "Your Entity Name"; // Ersetzen durch tatsächlichen Namen
const entityId = "sensor.your_sensor_id"; // Ersetzen durch tatsächliche ID
Date.prototype.addDays = function (days) {
    this.setDate(this.getDate() + days);
    return this; // Ermöglicht method chaining
};

console.log($json.data);

async function setupWebSocket() {
    return new Promise((resolve, reject) => {
        const socket = new WebSocket(serverUrl);

        // Warten auf auth_ok nach Verbindungsaufbau
        let authenticated = false;

        // WebSocket geöffnet
        socket.on('open', () => {
            console.log('WebSocket-Verbindung hergestellt.');

            // Authentifizierungsnachricht senden
            const authMessage = {
                type: "auth",
                access_token: "your_access_token_here" // Ersetzen durch tatsächlichen Token
            };
            socket.send(JSON.stringify(authMessage));
        });

        // Nachrichten empfangen
        socket.on('message', (data) => {
            const message = JSON.parse(data);

            if (message.type === 'auth_ok') {
                console.log('Authentifizierung erfolgreich.');
                authenticated = true;
                resolve(socket);
            } else if (message.type === 'auth_invalid') {
                console.error('Authentifizierung fehlgeschlagen.');
                reject(new Error('Authentifizierung fehlgeschlagen.'));
                socket.close();
            }

            if (message.id && awaitingResponses.has(message.id)) {
                const resolve = awaitingResponses.get(message.id);
                resolve(message);
                awaitingResponses.delete(message.id);
            }
        });

        // Fehlerbehandlung
        socket.on('error', (error) => {
            console.error('WebSocket-Fehler:', error);
            reject(error);
        });

        // Verbindung geschlossen
        socket.on('close', (code, reason) => {
            console.log(`WebSocket-Verbindung geschlossen: Code=${code}, Grund=${reason || 'Keine Angabe'}`);
            if (!authenticated) {
                reject(new Error('Verbindung geschlossen, bevor Authentifizierung abgeschlossen wurde.'));
            }
        });
    });
}

async function sendMessage(socket, message) {
    return new Promise((resolve, reject) => {
        const messageId = message.id;
        awaitingResponses.set(messageId, resolve);

        if (socket.readyState !== WebSocket.OPEN) {
            return reject(new Error(`WebSocket ist nicht bereit. Status: ${socket.readyState}`));
        }

        socket.send(JSON.stringify(message));

        // Set a timeout to reject if no response is received
        setTimeout(() => {
            if (awaitingResponses.has(messageId)) {
                awaitingResponses.delete(messageId);
                reject(new Error(`Timeout für Nachricht mit ID ${messageId}`));
            }
        }, 10000); // 10 Sekunden Timeout
    });
}

async function main() {
    const socket = await setupWebSocket();

    try {
        // Erste Nachricht senden
        const firstMessage = {
            id: 1,
            type: "recorder/statistics_during_period",
            start_time: (new Date($input.item.json.data[0].hourReadable)).addDays(-1).toISOString(),
            end_time: (new Date($input.item.json.data.at(-1).hourReadable)).addDays(-1).toISOString(),
            statistic_ids: ["sensor.your_sensor_id_1", "sensor.your_sensor_id_2"], // IDs ersetzen
            period: "hour"
        };
        
        const firstResponse = await sendMessage(socket, firstMessage);
        let summe = firstResponse.result[entityId].at(-1).sum;
        let id = 2;
        
        for (let dat in $json.data) {
            summe = summe + parseFloat($json.data[dat].value); 
            const secondMessage = {
                id: id,
                type: "recorder/import_statistics",
                metadata: {
                    has_mean: false,
                    has_sum: true,
                    name: entityName,
                    source: "recorder",
                    statistic_id: entityId,
                    unit_of_measurement: "kWh"
                },
                stats: [
                    {
                        start: $json.data[dat].hourReadable,  
                        last_reset: null,
                        state: 1,
                        mean: 0,
                        min: 0,
                        max: 0,
                        sum: Number(summe.toFixed(2))
                    }
                ]
            };
            console.log(secondMessage);
            const response = await sendMessage(socket, secondMessage);
            id++;
        }
        return { json: { message: 'Alle Nachrichten gesendet.' } };

    } catch (error) {
        console.error('Fehler während der Kommunikation:', error);
        return { json: { message: `Fehler: ${error.message}` } };
    } finally {
        if (socket.readyState === WebSocket.OPEN) {
            socket.close(1000, "Verbindung wird geschlossen.");
            console.log('WebSocket-Verbindung sauber geschlossen.');
        } else {
            console.error('WebSocket-Verbindung war bereits geschlossen.');
        }
    }
}

return new Promise((resolve, reject) => {
    main()
        .then((result) => {
            console.log('Finales Ergebnis:', result.json.message);
            resolve(result);
        })
        .catch((error) => {
            console.error('Finaler Fehler:', error.json.message);
            reject(error);
        });
});

Sampe Data:


[
{
"data": 
[
{
"hour": 
1735167600000,
"value": 
0.2073,
"hourReadable": 
"2024-12-25T23:00:00.000Z",
"totalCumulative": 
0.2073
},
{
"hour": 
1735171200000,
"value": 
0.1985,
"hourReadable": 
"2024-12-26T00:00:00.000Z",
"totalCumulative": 
0.40580000000000005
},
{
"hour": 
1735174800000,
"value": 
0.2203,
"hourReadable": 
"2024-12-26T01:00:00.000Z",
"totalCumulative": 
0.6261000000000001
}

]
}
]

Sensory Configuration:

- sensor:
    name: "Stromzähler Bezug"
    unique_id: "strom_bezug"
    unit_of_measurement: "kWh"
    device_class: "energy"
    state_class: "total_increasing"
    #state_class: "measurement"
    #device_class: "current"
    state: 0