Skip to content

Commit 0feecde

Browse files
authored
165 templating content for all types (#170)
Submitting as an initial draft in order to guage feedback on the style. In particular the solution to adding the code to the `toggle` menu item, which has incurred duplication of code as I can't inherit from two classes.
2 parents 08829da + d387152 commit 0feecde

10 files changed

+406
-174
lines changed

HISTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@
3131
| 2.16 | Bug fix for lack of phone connection when starting the application. Includes new activity reporting features from [KPWhiver](https://github.com/KPWhiver) covering steps, heart rate, floors climbed and descended, and respiration rate. |
3232
| 2.17 | Bug fix for reporting activity metrics that are not found on some devices. |
3333
| 2.18 | Bug fix for reporting activity metrics that might be `null` sometimes. This is unsimulatable situation, so this version is a change based on an informed guess. |
34+
| 2.19 | A template to evaluate is now optionally allowed on both `group` and `toggle` menu items. The template to evaluate is non-optional on a `template` menu item. |

config.schema.json

+31-22
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,16 @@
2222
"$ref": "#/$defs/entity"
2323
},
2424
"name": {
25-
"title": "Your familiar name",
26-
"type": "string"
25+
"$ref": "#/$defs/name"
2726
},
2827
"type": {
29-
"title": "Menu item type",
30-
"description": "One of 'tap', 'template', 'toggle' or 'group'.",
28+
"$ref": "#/$defs/type",
3129
"const": "toggle"
3230
},
31+
"content": {
32+
"$ref": "#/$defs/content",
33+
"description": "Optional in a toggle."
34+
},
3335
"tap_action": {
3436
"type": "object",
3537
"properties": {
@@ -55,16 +57,13 @@
5557
"description": "Use 'tap_action' instead to mirror Home Assistant."
5658
},
5759
"name": {
58-
"title": "Your familiar name",
59-
"type": "string"
60+
"$ref": "#/$defs/name"
6061
},
6162
"content": {
62-
"title": "What to display (template)",
63-
"type": "string"
63+
"$ref": "#/$defs/content"
6464
},
6565
"type": {
66-
"title": "Menu item type",
67-
"description": "One of 'tap', 'template', 'toggle' or 'group'.",
66+
"$ref": "#/$defs/type",
6867
"const": "template"
6968
}
7069
},
@@ -78,16 +77,13 @@
7877
"$ref": "#/$defs/entity"
7978
},
8079
"name": {
81-
"title": "Your familiar name",
82-
"type": "string"
80+
"$ref": "#/$defs/name"
8381
},
8482
"content": {
85-
"title": "What to display (template)",
86-
"type": "string"
83+
"$ref": "#/$defs/content"
8784
},
8885
"type": {
89-
"title": "Menu item type",
90-
"description": "One of 'tap', 'template', 'toggle' or 'group'.",
86+
"$ref": "#/$defs/type",
9187
"const": "template"
9288
},
9389
"tap_action": {
@@ -106,12 +102,10 @@
106102
"$ref": "#/$defs/entity"
107103
},
108104
"name": {
109-
"title": "Your familiar name",
110-
"type": "string"
105+
"$ref": "#/$defs/name"
111106
},
112107
"type": {
113-
"title": "Menu item type",
114-
"description": "One of 'tap', 'template', 'toggle' or 'group'.",
108+
"$ref": "#/$defs/type",
115109
"const": "tap"
116110
},
117111
"service": {
@@ -153,17 +147,24 @@
153147
"type": "string"
154148
},
155149
"type": {
156-
"title": "Menu item type",
157-
"description": "One of 'tap', 'template', 'toggle' or 'group'.",
150+
"$ref": "#/$defs/type",
158151
"const": "group"
159152
},
153+
"content": {
154+
"$ref": "#/$defs/content",
155+
"description": "Optional in a group."
156+
},
160157
"items": {
161158
"$ref": "#/$defs/items"
162159
}
163160
},
164161
"required": ["name", "title", "type", "items"],
165162
"additionalProperties": false
166163
},
164+
"type": {
165+
"title": "Menu item type",
166+
"description": "One of 'tap', 'template', 'toggle' or 'group'."
167+
},
167168
"items": {
168169
"type": "array",
169170
"maxItems": 16,
@@ -184,6 +185,10 @@
184185
]
185186
}
186187
},
188+
"name": {
189+
"title": "Your familiar name",
190+
"type": "string"
191+
},
187192
"entity": {
188193
"type": "string",
189194
"title": "Home Assistant entity name",
@@ -213,6 +218,10 @@
213218
},
214219
"required": ["service"]
215220
},
221+
"content": {
222+
"title": "Jinja2 template defining the text to display.",
223+
"type": "string"
224+
},
216225
"confirm": {
217226
"type": "boolean",
218227
"default": false,

examples/Templates.md

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ In order to provide the most functionality possible the content of the menu item
1010
- `{{` ... `}}` for Expressions to print to the template output
1111
- `{#` ... `#}` for Comments not included in the template output
1212

13+
> [!IMPORTANT]
14+
> In order to avoid "Template Error" being displayed as the return value, make sure your Jinja2 template returns a `string`, not a number of some variety. _All numbers must be formatted to strings_ so the application does not need to distinguish an `integer` from a `float`.
15+
1316
## States
1417

1518
In this example we get the battery level of the device and add the percent sign. *Very simple*

source/HomeAssistantApp.mc

+4-5
Original file line numberDiff line numberDiff line change
@@ -429,12 +429,11 @@ class HomeAssistantApp extends Application.AppBase {
429429
// We need to spread out the API calls so as not to overload the results queue and cause Communications.BLE_QUEUE_FULL
430430
// (-101) error. This function is called by a timer every Globals.menuItemUpdateInterval ms.
431431
function updateNextMenuItemInternal() as Void {
432-
var itu = mItemsToUpdate as Lang.Array<HomeAssistantToggleMenuItem>;
433-
if (itu != null) {
432+
if (mItemsToUpdate != null) {
434433
// System.println("HomeAssistantApp updateNextMenuItemInternal(): Doing update for item " + mNextItemToUpdate + ", mIsInitUpdateCompl=" + mIsInitUpdateCompl);
435-
itu[mNextItemToUpdate].getState();
436-
// mNextItemToUpdate = (mNextItemToUpdate + 1) % itu.size() - But with roll-over detection
437-
if (mNextItemToUpdate == itu.size()-1) {
434+
mItemsToUpdate[mNextItemToUpdate].getState();
435+
// mNextItemToUpdate = (mNextItemToUpdate + 1) % mItemsToUpdate.size() - But with roll-over detection
436+
if (mNextItemToUpdate == mItemsToUpdate.size()-1) {
438437
// Last item completed return to the start of the list
439438
mNextItemToUpdate = 0;
440439
mIsInitUpdateCompl = true;

source/HomeAssistantGroupMenuItem.mc

+10-6
Original file line numberDiff line numberDiff line change
@@ -14,27 +14,31 @@
1414
//
1515
// Description:
1616
//
17-
// Menu button with an icon that opens a sub-menu, i.e. group.
17+
// Menu button with an icon that opens a sub-menu, i.e. group, and optionally renders
18+
// a Home Assistant Template.
1819
//
1920
//-----------------------------------------------------------------------------------
2021

2122
using Toybox.Lang;
2223
using Toybox.WatchUi;
2324

24-
class HomeAssistantGroupMenuItem extends WatchUi.IconMenuItem {
25+
class HomeAssistantGroupMenuItem extends TemplateMenuItem {
2526
private var mMenu as HomeAssistantView;
2627

2728
function initialize(
2829
definition as Lang.Dictionary,
30+
template as Lang.String,
2931
icon as WatchUi.Drawable,
3032
options as {
3133
:alignment as WatchUi.MenuItem.Alignment
32-
} or Null) {
34+
} or Null
35+
) {
3336

34-
WatchUi.IconMenuItem.initialize(
37+
TemplateMenuItem.initialize(
3538
definition.get("name") as Lang.String,
36-
null,
37-
null,
39+
template,
40+
// Now this feels very "closely coupled" to the application, but it is the most reliable method instead of using a timer.
41+
getApp().method(:updateNextMenuItem),
3842
icon,
3943
options
4044
);

source/HomeAssistantMenuItemFactory.mc

+12-2
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,12 @@ class HomeAssistantMenuItemFactory {
6767
function toggle(
6868
label as Lang.String or Lang.Symbol,
6969
entity_id as Lang.String or Null,
70+
template as Lang.String or Null,
7071
confirm as Lang.Boolean
7172
) as WatchUi.MenuItem {
7273
return new HomeAssistantToggleMenuItem(
7374
label,
75+
template,
7476
confirm,
7577
{ "entity_id" => entity_id },
7678
mMenuItemOptions
@@ -145,7 +147,15 @@ class HomeAssistantMenuItemFactory {
145147
);
146148
}
147149

148-
function group(definition as Lang.Dictionary) as WatchUi.MenuItem {
149-
return new HomeAssistantGroupMenuItem(definition, mGroupTypeIcon, mMenuItemOptions);
150+
function group(
151+
definition as Lang.Dictionary,
152+
template as Lang.String or Null
153+
) as WatchUi.MenuItem {
154+
return new HomeAssistantGroupMenuItem(
155+
definition,
156+
template,
157+
mGroupTypeIcon,
158+
mMenuItemOptions
159+
);
150160
}
151161
}

source/HomeAssistantTemplateMenuItem.mc

+13-126
Original file line numberDiff line numberDiff line change
@@ -26,35 +26,34 @@ using Toybox.Lang;
2626
using Toybox.WatchUi;
2727
using Toybox.Graphics;
2828

29-
class HomeAssistantTemplateMenuItem extends WatchUi.IconMenuItem {
29+
class HomeAssistantTemplateMenuItem extends TemplateMenuItem {
3030
private var mHomeAssistantService as HomeAssistantService;
31-
private var mTemplate as Lang.String;
3231
private var mService as Lang.String or Null;
3332
private var mConfirm as Lang.Boolean;
3433
private var mData as Lang.Dictionary or Null;
3534

3635
function initialize(
37-
label as Lang.String or Lang.Symbol,
38-
template as Lang.String,
39-
service as Lang.String or Null,
40-
confirm as Lang.Boolean,
41-
data as Lang.Dictionary or Null,
42-
icon as Graphics.BitmapType or WatchUi.Drawable,
43-
options as {
36+
label as Lang.String or Lang.Symbol,
37+
template as Lang.String,
38+
service as Lang.String or Null,
39+
confirm as Lang.Boolean,
40+
data as Lang.Dictionary or Null,
41+
icon as Graphics.BitmapType or WatchUi.Drawable,
42+
options as {
4443
:alignment as WatchUi.MenuItem.Alignment
4544
} or Null,
46-
haService as HomeAssistantService
45+
haService as HomeAssistantService
4746
) {
48-
WatchUi.IconMenuItem.initialize(
47+
TemplateMenuItem.initialize(
4948
label,
50-
null,
51-
null,
49+
template,
50+
// Now this feels very "closely coupled" to the application, but it is the most reliable method instead of using a timer.
51+
getApp().method(:updateNextMenuItem),
5252
icon,
5353
options
5454
);
5555

5656
mHomeAssistantService = haService;
57-
mTemplate = template;
5857
mService = service;
5958
mConfirm = confirm;
6059
mData = data;
@@ -79,116 +78,4 @@ class HomeAssistantTemplateMenuItem extends WatchUi.IconMenuItem {
7978
}
8079
}
8180

82-
// Callback function after completing the GET request to fetch the status.
83-
// Terminate updating the toggle menu items via the chain of calls for a permanent network
84-
// error. The ErrorView cancellation will resume the call chain.
85-
//
86-
function onReturnGetState(responseCode as Lang.Number, data as Null or Lang.Dictionary) as Void {
87-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() Response Code: " + responseCode);
88-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() Response Data: " + data);
89-
90-
var status = WatchUi.loadResource($.Rez.Strings.Unavailable) as Lang.String;
91-
switch (responseCode) {
92-
case Communications.BLE_HOST_TIMEOUT:
93-
case Communications.BLE_CONNECTION_UNAVAILABLE:
94-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() Response Code: BLE_HOST_TIMEOUT or BLE_CONNECTION_UNAVAILABLE, Bluetooth connection severed.");
95-
ErrorView.show(WatchUi.loadResource($.Rez.Strings.NoPhone) as Lang.String + ".");
96-
break;
97-
98-
case Communications.BLE_QUEUE_FULL:
99-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() Response Code: BLE_QUEUE_FULL, API calls too rapid.");
100-
ErrorView.show(WatchUi.loadResource($.Rez.Strings.ApiFlood) as Lang.String);
101-
break;
102-
103-
case Communications.NETWORK_REQUEST_TIMED_OUT:
104-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() Response Code: NETWORK_REQUEST_TIMED_OUT, check Internet connection.");
105-
ErrorView.show(WatchUi.loadResource($.Rez.Strings.NoResponse) as Lang.String);
106-
break;
107-
108-
case Communications.INVALID_HTTP_BODY_IN_NETWORK_RESPONSE:
109-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() Response Code: INVALID_HTTP_BODY_IN_NETWORK_RESPONSE, check JSON is returned.");
110-
ErrorView.show(WatchUi.loadResource($.Rez.Strings.NoJson) as Lang.String);
111-
break;
112-
113-
case Communications.NETWORK_RESPONSE_OUT_OF_MEMORY:
114-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() Response Code: NETWORK_RESPONSE_OUT_OF_MEMORY, are we going too fast?");
115-
var myTimer = new Timer.Timer();
116-
// Now this feels very "closely coupled" to the application, but it is the most reliable method instead of using a timer.
117-
myTimer.start(getApp().method(:updateNextMenuItem), Globals.scApiBackoff, false);
118-
// Revert status
119-
status = getApp().getApiStatus();
120-
break;
121-
122-
case 404:
123-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() Response Code: 404, page not found. Check API URL setting.");
124-
ErrorView.show(WatchUi.loadResource($.Rez.Strings.ApiUrlNotFound) as Lang.String);
125-
break;
126-
127-
case 400:
128-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() Response Code: 400, bad request. Template error.");
129-
ErrorView.show(WatchUi.loadResource($.Rez.Strings.TemplateError) as Lang.String);
130-
break;
131-
132-
case 200:
133-
status = WatchUi.loadResource($.Rez.Strings.Available) as Lang.String;
134-
var label = data.get("request");
135-
if (label == null) {
136-
setSubLabel($.Rez.Strings.Empty);
137-
} else if(label instanceof Lang.String) {
138-
setSubLabel(label);
139-
} else if(label instanceof Lang.Dictionary) {
140-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState() label = " + label);
141-
if (label.get("error") != null) {
142-
setSubLabel($.Rez.Strings.TemplateError);
143-
} else {
144-
setSubLabel($.Rez.Strings.PotentialError);
145-
}
146-
}
147-
requestUpdate();
148-
// Now this feels very "closely coupled" to the application, but it is the most reliable method instead of using a timer.
149-
getApp().updateNextMenuItem();
150-
break;
151-
152-
default:
153-
// System.println("HomeAssistantTemplateMenuItem onReturnGetState(): Unhandled HTTP response code = " + responseCode);
154-
ErrorView.show(WatchUi.loadResource($.Rez.Strings.UnhandledHttpErr) as Lang.String + responseCode);
155-
}
156-
getApp().setApiStatus(status);
157-
}
158-
159-
function getState() as Void {
160-
if (! System.getDeviceSettings().phoneConnected) {
161-
// System.println("HomeAssistantTemplateMenuItem getState(): No Phone connection, skipping API call.");
162-
ErrorView.show(WatchUi.loadResource($.Rez.Strings.NoPhone) as Lang.String + ".");
163-
getApp().setApiStatus(WatchUi.loadResource($.Rez.Strings.Unavailable) as Lang.String);
164-
} else if (! System.getDeviceSettings().connectionAvailable) {
165-
// System.println("HomeAssistantTemplateMenuItem getState(): No Internet connection, skipping API call.");
166-
ErrorView.show(WatchUi.loadResource($.Rez.Strings.NoInternet) as Lang.String + ".");
167-
getApp().setApiStatus(WatchUi.loadResource($.Rez.Strings.Unavailable) as Lang.String);
168-
} else {
169-
// https://developers.home-assistant.io/docs/api/native-app-integration/sending-data/#render-templates
170-
var url = Settings.getApiUrl() + "/webhook/" + Settings.getWebhookId();
171-
// System.println("HomeAssistantTemplateMenuItem getState() URL=" + url + ", Template='" + mTemplate + "'");
172-
Communications.makeWebRequest(
173-
url,
174-
{
175-
"type" => "render_template",
176-
"data" => {
177-
"request" => {
178-
"template" => mTemplate
179-
}
180-
}
181-
},
182-
{
183-
:method => Communications.HTTP_REQUEST_METHOD_POST,
184-
:headers => {
185-
"Content-Type" => Communications.REQUEST_CONTENT_TYPE_JSON
186-
},
187-
:responseType => Communications.HTTP_RESPONSE_CONTENT_TYPE_JSON
188-
},
189-
method(:onReturnGetState)
190-
);
191-
}
192-
}
193-
19481
}

0 commit comments

Comments
 (0)