-
Notifications
You must be signed in to change notification settings - Fork 2
/
opendtu-medium.js
243 lines (208 loc) · 7.02 KB
/
opendtu-medium.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
const configFileName = "opendtu-config.json"; // Name of the config file
// This function handles loading settings
async function loadSettings() {
let fm = FileManager.iCloud();
let dir = fm.documentsDirectory();
let path = fm.joinPath(dir, configFileName);
if (fm.fileExists(path)) {
// Read existing settings file
let raw = await fm.readString(path);
return JSON.parse(raw);
} else {
// First time run, create a default settings file
let defaultSettings = {
dtuApiUrl: "http://change-me/api/livedata/status/", // Make sure to add a trailing slash for the medium widget to work!
dtuUser: "changeme",
dtuPass: "changeme",
powermeter: "tasmota",
tasmotaApiUrl: "http://change-me/cm?cmnd=status%208",
tasmotaUser: "changeme",
tasmotaPass: "changeme",
shellyApiUrl: "https://change-me/",
shellyUser: "changeme",
shellyPass: "changeme",
showPowerDraw: 0,
powerDrawThreshold: 0,
redThreshold: 220,
yellowThreshold: 260,
greenThreshold: 400,
inverterSerial: "XXXXXXXXXXXX",
};
await fm.writeString(path, JSON.stringify(defaultSettings));
return defaultSettings;
}
}
let settings = await loadSettings(); // Load settings
// Here the script continues, replacing the hardcoded variables
// with settings.dtuApiUrl, settings.dtuUser, etc.
async function fetchData(apiUrl, username, password, timeoutMillis) {
let request = new Request(`${apiUrl}?inv=${settings.inverterSerial}`);
const auth = `${username}:${password}`;
const base64Auth = btoa(auth);
request.headers = {
Authorization: `Basic ${base64Auth}`,
};
try {
let response = await request.loadJSON();
return response;
} catch (error) {
console.error(`Could not fetch data: ${error}`);
return null;
}
}
// Helper function to retrieve power draw value from the API response
function getPowerDrawValue(powerDrawData) {
if (settings.powermeter === "tasmota") {
// Handle Tasmota API response structure
if (
powerDrawData &&
powerDrawData.StatusSNS &&
powerDrawData.StatusSNS.hasOwnProperty("")
) {
return parseFloat(powerDrawData.StatusSNS[""]["current"]) || 0;
}
} else if (settings.powermeter === "shelly") {
// Handle Shelly API response structure
if (
powerDrawData &&
powerDrawData.meters &&
powerDrawData.meters.length > 0
) {
return parseFloat(powerDrawData.meters[0].power) || 0;
}
}
return 0;
}
async function createWidget(data, powerDrawData) {
let widget = new ListWidget();
let settings = await loadSettings();
let startColor = new Color("#434C5E");
let endColor = new Color("#2E3440");
let gradient = new LinearGradient();
gradient.colors = [startColor, endColor];
gradient.locations = [0, 1];
widget.backgroundGradient = gradient;
let title = widget.addText("OpenDTU☀️");
title.textColor = Color.white();
title.font = Font.boldSystemFont(16);
let powerData = parseFloat(data.inverters[0].AC["0"].Power.v);
let yieldDayData = (
parseFloat(data.inverters[0].DC["0"].YieldDay.v) / 1000
).toFixed(2);
let yieldTotalData = parseFloat(
data.inverters[0].DC["0"].YieldTotal.v
).toFixed(2);
widget.addSpacer(2);
let gridStack = widget.addStack();
gridStack.layoutHorizontally();
let leftStack = gridStack.addStack();
leftStack.layoutVertically();
let powerLabel = leftStack.addText(`Power:`);
powerLabel.textColor = Color.white();
powerLabel.font = Font.systemFont(8);
let powerText = leftStack.addText(`${powerData.toFixed(2)} W`);
powerText.font = Font.systemFont(13);
if (powerData < settings.redThreshold) {
powerText.textColor = Color.red();
} else if (
powerData >= settings.redThreshold &&
powerData < settings.yellowThreshold
) {
powerText.textColor = Color.yellow();
} else {
powerText.textColor = Color.green();
}
let yieldDayLabel = leftStack.addText(`Yield Day: `);
yieldDayLabel.textColor = Color.white();
yieldDayLabel.font = Font.systemFont(8);
let yieldDayText = leftStack.addText(`${yieldDayData} kWh`);
yieldDayText.textColor = Color.white();
yieldDayText.font = Font.systemFont(13);
let yieldTotalLabel = leftStack.addText(`Yield Total: `);
yieldTotalLabel.textColor = Color.white();
yieldTotalLabel.font = Font.systemFont(8);
let yieldTotalText = leftStack.addText(`${yieldTotalData} kWh `);
yieldTotalText.textColor = Color.white();
yieldTotalText.font = Font.systemFont(13);
let dcStack = gridStack.addStack();
dcStack.layoutVertically();
const dcOutputs = data.inverters[0].DC;
for (let key in dcOutputs) {
let dcName = dcOutputs[key].name.u;
let dcPower = parseFloat(dcOutputs[key].Power.v);
let dcLabel = dcStack.addText(`${dcName}: `);
dcLabel.textColor = Color.white();
dcLabel.font = Font.systemFont(8);
let dcText = dcStack.addText(`${dcPower.toFixed(2)} W`);
dcText.font = Font.systemFont(13);
dcText.textColor = Color.white();
}
let rightStack = gridStack.addStack();
rightStack.layoutVertically();
if (settings.showPowerDraw) {
let powerDrawDataValue = powerDrawData
? getPowerDrawValue(powerDrawData)
: 0;
let powerDrawLabel = rightStack.addText(`Power Draw: `);
powerDrawLabel.textColor = Color.white();
powerDrawLabel.font = Font.systemFont(8);
let powerDrawText = rightStack.addText(`${powerDrawDataValue} W`);
powerDrawText.font = Font.systemFont(13);
if (powerDrawDataValue > settings.powerDrawThreshold) {
powerDrawText.textColor = Color.yellow();
} else {
powerDrawText.textColor = Color.green();
}
}
let timeStampStack = widget.addStack();
timeStampStack.layoutVertically();
let dateText = timeStampStack.addDate(new Date());
dateText.textColor = Color.white();
dateText.applyRelativeStyle();
dateText.font = Font.systemFont(8);
let agoText = timeStampStack.addText(" ago");
agoText.textColor = Color.white();
agoText.font = Font.systemFont(8);
return widget;
}
// Main script
async function run() {
try {
let data = await fetchData(
settings.dtuApiUrl,
settings.dtuUser,
settings.dtuPass,
10000
);
let powerDrawData = settings.showPowerDraw
? await fetchData(
settings.powermeter === "tasmota"
? settings.tasmotaApiUrl
: settings.shellyApiUrl,
settings.powermeter === "tasmota"
? settings.tasmotaUser
: settings.shellyUser,
settings.powermeter === "tasmota"
? settings.tasmotaPass
: settings.shellyPass,
10000
)
: null;
let widget = await createWidget(data, powerDrawData);
if (config.runsInWidget) {
Script.setWidget(widget);
} else {
widget.presentMedium();
}
} catch (error) {
console.error(error.message);
let widget = new ListWidget();
widget.addText("Error: Unable to connect to powermeter");
if (config.runsInWidget) {
Script.setWidget(widget);
} else {
widget.presentMedium();
}
}
}
await run();