Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/node-red-local-powerwall-read.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@teslemetry/node-red-contrib-teslemetry": minor
---

Add a Local Powerwall Read node that polls a Powerwall gateway on your local network and sends what it returns: live status, meters aggregates, system status, grid status, state of energy, gateway config, components, firmware or backup events.
24 changes: 23 additions & 1 deletion packages/node-red-contrib-teslemetry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Configuration node to store your Teslemetry Access Token.
- **Replay last known values on connect**: Off by default, so nodes stay silent until a value next changes. When ticked, Teslemetry sends its last known state each time the stream connects or reconnects. Replayed events carry `isCache: true` in the payload of the event nodes; a Signal node outputs only the value, so a replayed value there has no marker.

### teslemetry-local-powerwall
Configuration node that connects Node-RED to a Powerwall gateway on your local network. Node-RED must be on the same network as the gateway. Pick it in the **Local gateway** field of an Energy Command node to send commands to the Powerwall without the internet.
Configuration node that connects Node-RED to a Powerwall gateway on your local network. Node-RED must be on the same network as the gateway. Pick it in the **Local gateway** field of an Energy Command node to send commands to the Powerwall without the internet, or of a Local Powerwall Read node to read the gateway.

**Configuration:**
- **Config**: Select your Teslemetry Config node
Expand All @@ -77,6 +77,28 @@ Configuration node that connects Node-RED to a Powerwall gateway on your local n

The key and password are stored as Node-RED credentials: outside your flows, never in an exported flow, and not shown again in the editor. Set `credentialSecret` in `settings.js` to encrypt them with a secret of your own.

### teslemetry-local-powerwall-read
Reads a Powerwall gateway over your local network, with no internet or Teslemetry in between. It polls the gateway itself and sends what the gateway returns as it is. The cloud nodes (Energy Event, Energy Command) are unchanged; this node does not merge local data into them.

**Configuration:**
- **Local gateway**: A Teslemetry Local Powerwall config node, paired and verified.
- **Read**: What to read:
- **Live status**: solar, battery, home and grid power, the battery level and the grid status, in the shape of the cloud's `live_status`. Values the gateway has no source for are `null`.
- **Meters (aggregates)**: the gateway's `/api/meters/aggregates`, power, energy and voltage per meter (`site`, `battery`, `load`, `solar`...).
- **System status** and **Device controller**: the gateway's status queries (battery energy, grid connection, meter power, alerts; the second adds more device detail).
- **Grid status**: a string such as `SystemGridConnected`.
- **State of energy**: the battery level as the Tesla app shows it, and **State of energy (raw)** as the gateway counts it, which includes a 5% buffer.
- **Gateway config** (`config.json`), **Components (Powerwall 3)**, **Firmware** and **Backup events**.
- **Poll every**: Seconds between reads, 10 by default, from 2 to 86400 (24 hours). Set 0 to read only when a message arrives.

Any input message also reads the gateway once. Polling stops when the flow is redeployed or stopped.

**Outputs:**
- `msg.payload`: What the gateway returned for the read (an object, or a string or number for grid status and state of energy).
- `msg.topic`: The read's name, such as `meters_aggregates`.

The node status shows the time of the last read, or the error. A read triggered by a message that fails goes to a **catch** node; a gateway that stays unreachable while polling is logged once, not on every poll.

### teslemetry-vehicle-command
Send commands to a specific vehicle or retrieve vehicle data.

Expand Down
1 change: 1 addition & 0 deletions packages/node-red-contrib-teslemetry/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"teslemetry-energy-command": "dist/nodes/teslemetry-energy-command.js",
"teslemetry-energy-history": "dist/nodes/teslemetry-energy-history.js",
"teslemetry-energy-event": "dist/nodes/teslemetry-energy-event.js",
"teslemetry-local-powerwall-read": "dist/nodes/teslemetry-local-powerwall-read.js",
"teslemetry-wall-connector": "dist/nodes/teslemetry-wall-connector.js"
}
},
Expand Down
21 changes: 21 additions & 0 deletions packages/node-red-contrib-teslemetry/src/localPowerwall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,24 @@ export async function sendLocalFirst<M extends keyof SiteCommands>(
});
return { result: await call(router), path, failover };
}

/**
* The reads a gateway answers on the LAN, by the name a Local Powerwall Read
* node selects. Each resolves to what the gateway returned, unwrapped from the
* cloud-style `response` envelope where the library adds one.
*/
export const LOCAL_READS = {
live_status: async (site: LocalSite) => (await site.live_status()).response,
meters_aggregates: (site: LocalSite) => site.powerwall.get_meters_aggregates(),
status: (site: LocalSite) => site.powerwall.get_status(),
device_controller: (site: LocalSite) => site.powerwall.get_device_controller(),
grid_status: (site: LocalSite) => site.powerwall.get_grid_status(),
battery_soe: (site: LocalSite) => site.powerwall.get_battery_soe(),
battery_soe_raw: (site: LocalSite) => site.powerwall.get_battery_soe_raw(),
config: (site: LocalSite) => site.powerwall.get_config(),
components: (site: LocalSite) => site.powerwall.get_components(),
firmware: (site: LocalSite) => site.powerwall.get_firmware_details(),
backup_events: (site: LocalSite) => site.powerwall.get_backup_events(),
} satisfies Record<string, (site: LocalSite) => Promise<unknown>>;

export type LocalRead = keyof typeof LOCAL_READS;
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
<script type="text/javascript">
(function () {
const READS = {
live_status: "Live status",
meters_aggregates: "Meters (aggregates)",
status: "System status",
device_controller: "Device controller",
grid_status: "Grid status",
battery_soe: "State of energy",
battery_soe_raw: "State of energy (raw)",
config: "Gateway config",
components: "Components (Powerwall 3)",
firmware: "Firmware",
backup_events: "Backup events",
};

RED.nodes.registerType("teslemetry-local-powerwall-read", {
category: "Teslemetry Energy",
paletteLabel: "Local Read",
color: "#e6e600",
defaults: {
name: { value: "" },
localGateway: {
value: "",
type: "teslemetry-local-powerwall",
required: true,
},
read: { value: "live_status", required: true },
interval: {
value: 10,
validate: function (v) {
const n = Number(v);
return v === "" || n === 0 || (n >= 2 && n <= 86400);
},
},
},
inputs: 1,
outputs: 1,
icon: "font-awesome/fa-server",
label: function () {
return this.name || "Local: " + (READS[this.read] || this.read);
},
oneditprepare: function () {
const select = $("#node-input-read");
Object.keys(READS).forEach(function (key) {
select.append($("<option>").val(key).text(READS[key]));
});
select.val(this.read || "live_status");
$("#node-input-interval").spinner({ min: 0, max: 86400 });
},
});
})();
</script>

<script type="text/html" data-template-name="teslemetry-local-powerwall-read">
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
<input type="text" id="node-input-name" placeholder="Name" />
</div>
<div class="form-row">
<label for="node-input-localGateway">
<i class="fa fa-server"></i> Local gateway
</label>
<input type="text" id="node-input-localGateway" />
</div>
<div class="form-row">
<label for="node-input-read"><i class="fa fa-book"></i> Read</label>
<select id="node-input-read"></select>
</div>
<div class="form-row">
<label for="node-input-interval">
<i class="fa fa-clock-o"></i> Poll every
</label>
<input type="text" id="node-input-interval" style="width: 80px" />
seconds (0 = only on input)
</div>
</script>

<script type="text/html" data-help-name="teslemetry-local-powerwall-read">
<p>
Reads a Powerwall gateway over your local network, with no internet
or Teslemetry in between. It polls the gateway itself and sends what
the gateway returns as it is.
</p>
<p>
It needs a <b>Local gateway</b>: a Teslemetry Local Powerwall config
node that is paired and verified. Node-RED must be on the same network
as the gateway.
</p>

<h3>Reads</h3>
<dl class="message-properties">
<dt>Live status</dt>
<dd>
Solar, battery, home and grid power, the battery level and the
grid status, in the shape of the cloud's <code>live_status</code>.
Values the gateway has no source for are <code>null</code>.
Built from three gateway reads.
</dd>
<dt>Meters (aggregates)</dt>
<dd>
The gateway's <code>/api/meters/aggregates</code>: power, energy
and voltage per meter (<code>site</code>, <code>battery</code>,
<code>load</code>, <code>solar</code>...).
</dd>
<dt>System status</dt>
<dd>
The gateway's status query: battery energy, grid connection
(islanding), meter power, alerts and more.
</dd>
<dt>Device controller</dt>
<dd>
The extended status query, with more device detail such as
solar inverters and remote meters.
</dd>
<dt>Grid status</dt>
<dd>A string, such as <code>SystemGridConnected</code>.</dd>
<dt>State of energy</dt>
<dd>The battery level as the Tesla app shows it, in percent.</dd>
<dt>State of energy (raw)</dt>
<dd>
The gateway's own battery level, which counts a 5% reserve buffer
and reads higher than the app.
</dd>
<dt>Gateway config</dt>
<dd>The gateway's <code>config.json</code>.</dd>
<dt>Components (Powerwall 3)</dt>
<dd>Powerwall 3 component data.</dd>
<dt>Firmware</dt>
<dd>Gateway firmware details.</dd>
<dt>Backup events</dt>
<dd>The active manual backup and any scheduled backup events.</dd>
</dl>

<h3>Inputs</h3>
<p>Any message reads the gateway once, whatever its content.</p>

<h3>Outputs</h3>
<dl class="message-properties">
<dt>payload <span class="property-type">object | string | number</span></dt>
<dd>What the gateway returned for the selected read.</dd>
<dt>topic <span class="property-type">string</span></dt>
<dd>The read's name, such as <code>meters_aggregates</code>.</dd>
</dl>

<h3>Details</h3>
<p>
<b>Poll every</b> sets how often the node reads the gateway on its
own: 10 seconds by default, from 2 to 86400 (24 hours). Set it to 0 to read only when
a message arrives. The node status shows the time of the last read,
or the error. A gateway that stays unreachable is logged once, not on
every poll, until a read succeeds again.
</p>
<p>
A message that fails to read goes to a <b>catch</b> node. Live status
and other cloud data still come from the Energy Event node; this node
does not merge the two.
</p>
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { Node, NodeAPI, NodeDef } from "node-red";
import { failInput, getErrorMessage } from "../shared";
import { pollInterval } from "../validation";
import type { LocalRead } from "../localPowerwall";
import { Msg } from "../types";
import type { TeslemetryLocalPowerwallNode } from "./teslemetry-local-powerwall";

export interface TeslemetryLocalPowerwallReadNodeDef extends NodeDef {
localGateway: string;
read: LocalRead;
/** Seconds between polls; 0 reads only on an input message. */
interval: string | number;
}

export default function (RED: NodeAPI) {
function TeslemetryLocalPowerwallReadNode(
this: Node,
config: TeslemetryLocalPowerwallReadNodeDef,
) {
RED.nodes.createNode(this, config);
const node = this;
const read = config.read || "live_status";
const gateway = RED.nodes.getNode(config.localGateway) as
| TeslemetryLocalPowerwallNode
| undefined;

async function readGateway(): Promise<unknown> {
if (!gateway?.local) {
throw new Error("Set up the Local gateway first");
}
const { LOCAL_READS } = await import("../localPowerwall");
if (!Object.prototype.hasOwnProperty.call(LOCAL_READS, read)) {
throw new Error(`Unknown read: ${read}`);
}
return LOCAL_READS[read](await gateway.local());
}

function showRead() {
node.status({
fill: "green",
shape: "dot",
text: new Date().toLocaleTimeString(),
});
}

let closed = false;
let timer: ReturnType<typeof setTimeout> | undefined;
/** Set while polls fail, so a gateway that stays down is logged once, not every poll. */
let failing = false;
const interval = pollInterval(config.interval);

async function poll() {
try {
const payload = await readGateway();
if (closed) return;
failing = false;
showRead();
node.send({ payload, topic: read });
} catch (error) {
if (closed) return;
const text = getErrorMessage(error);
node.status({ fill: "red", shape: "ring", text });
if (!failing) node.error(`Local Powerwall read failed: ${text}`);
failing = true;
}
// The next poll waits for this one, so slow replies never pile up.
if (!closed) timer = setTimeout(poll, interval);
}
if (interval) timer = setTimeout(poll, 0);

node.on("input", async (msg: Msg, send, done) => {
try {
const payload = await readGateway();
showRead();
send({ ...msg, payload, topic: read });
done();
} catch (error) {
failInput(node, done, error);
}
});

node.on("close", (done: () => void) => {
closed = true;
clearTimeout(timer);
done();
});
}
RED.nodes.registerType(
"teslemetry-local-powerwall-read",
TeslemetryLocalPowerwallReadNode,
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -255,11 +255,12 @@
<script type="text/html" data-help-name="teslemetry-local-powerwall">
<p>
Connects Node-RED to a Powerwall gateway on your local network, so
commands can reach the Powerwall without the internet.
commands and reads can reach the Powerwall without the internet.
</p>
<p>
To use it, pick this config node in the <b>Local gateway</b> field
of an Energy Command node.
of an Energy Command node, to send commands, or of a Local Read
node, to read the gateway.
</p>
<p>
Node-RED must be on the same network as the gateway. A Node-RED
Expand Down
18 changes: 18 additions & 0 deletions packages/node-red-contrib-teslemetry/src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,21 @@ export function validateParameters(msg: any, rules: ValidationRules): void {
throw new Error(errors.join("; "));
}
}

const MIN_POLL_SECONDS = 2;
const DEFAULT_POLL_SECONDS = 10;
// Above 2^31-1 ms setTimeout fires after 1 ms, which would hammer the gateway.
const MAX_POLL_SECONDS = 24 * 60 * 60;

/** A poll interval in seconds as milliseconds: 10 s when unset or invalid, 2 s to 24 h, and 0 for none. */
export function pollInterval(value: unknown): number {
if (value === "" || value === undefined || value === null) {
return DEFAULT_POLL_SECONDS * 1000;
}
const seconds = Number(value);
if (!Number.isFinite(seconds) || seconds < 0) {
return DEFAULT_POLL_SECONDS * 1000;
}
if (seconds === 0) return 0;
return Math.min(Math.max(seconds, MIN_POLL_SECONDS), MAX_POLL_SECONDS) * 1000;
}
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Resolved
Loading
Loading