Skip to content

Instantly share code, notes, and snippets.

@dozigden
Forked from m33x/hass.js
Last active June 29, 2024 15:06
Show Gist options
  • Select an option

  • Save dozigden/7443b0e1fdb0a8a6c43bf37a2f9338c1 to your computer and use it in GitHub Desktop.

Select an option

Save dozigden/7443b0e1fdb0a8a6c43bf37a2f9338c1 to your computer and use it in GitHub Desktop.
Simple Home Assistant (HASS) iOS Widget via Scriptable App
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: light-gray; icon-glyph: magic;
let widget = await createWidget();
if (!config.runsInWidget) {
await widget.presentLarge();
}
Script.setWidget(widget);
Script.complete();
async function createWidget(items) {
let req = new Request("https://<HASS>/api/states")
req.headers = { "Authorization": "Bearer <token>", "content-type": "application/json" }
let haState = await req.loadJSON();
const sensorsIds = ['sensor.e2m_temp1', 'sensor.e2m_humidity1', 'sensor.e2m_soilmoisture2', 'sensor.e2m_soilmoisture3', 'sensor.e2m_soilmoisture1', 'binary_sensor.esphm5matrix01_battery_low', 'input_select.home_state'];
const widget = new ListWidget();
widget.backgroundColor = new Color("#03a9f4", 1.0);
const titleStack = widget.addStack();
const titleLabel = titleStack.addText("Garden Stats");
titleStack.setPadding(2, 0, 6, 0);
titleLabel.font = Font.heavyMonospacedSystemFont(16);
titleLabel.textColor = Color.white();
const bodyStack = widget.addStack();
bodyStack.layoutVertically();
const width = 30;
sensorsIds.forEach(sensorId => {
let entity = haState.find((e) => e.entity_id == sensorId);
if (entity) {
let displayName = entity?.attributes?.friendly_name ?? sensorId;
let state = entity.state;
let units = entity?.attributes?.unit_of_measurement ?? '';
let entityStack = bodyStack.addStack()
let padding = width - displayName.length;
let text = entityStack.addText(`${displayName}:`);
text.font = Font.mediumMonospacedSystemFont(14);
text.textColor = Color.black();
text.textOpacity = 0.8;
text.leftAlignText();
entityStack.addSpacer();
let displayState = isNaN(state) ? state : Math.round(state);
text = entityStack.addText(`${displayState}`);
text.font = Font.mediumMonospacedSystemFont(14);
text.textColor = Color.white();
text.textOpacity = 1;
text.rightAlignText();
text = entityStack.addText(`${units}`);
text.font = Font.mediumMonospacedSystemFont(10);
text.textColor = Color.white();
text.textOpacity = 0.6;
text.rightAlignText();
}
else {
let text = bodyStack.addText(`EntityId '${sensorId}' not found`);
text.font = Font.mediumMonospacedSystemFont(14);
text.textColor = Color.red();
text.textOpacity = 0.8;
}
});
return widget;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment