{"id":1816,"date":"2023-04-17T12:08:39","date_gmt":"2023-04-17T12:08:39","guid":{"rendered":"https:\/\/www.creatingsmarthome.com\/?p=1816"},"modified":"2024-08-14T11:21:38","modified_gmt":"2024-08-14T11:21:38","slug":"home-assistant-setting-up-time-schedules-to-shelly-devices-gen1-and-gen2","status":"publish","type":"post","link":"https:\/\/www.creatingsmarthome.com\/index.php\/2023\/04\/17\/home-assistant-setting-up-time-schedules-to-shelly-devices-gen1-and-gen2\/","title":{"rendered":"Home Assistant: Setting up time schedules to Shelly devices (gen1 and gen2)"},"content":{"rendered":"\n<p>Since my transformation to dynamic electricity prices are ongoing, I need to try to tackle up all the corner cases that comes with it. In <a rel=\"noreferrer noopener\" href=\"https:\/\/www.creatingsmarthome.com\/index.php\/2023\/04\/12\/home-assistant-advanced-nord-pool-cheapest-hours-with-local-calendar-support\/\" data-type=\"URL\" data-id=\"https:\/\/www.creatingsmarthome.com\/index.php\/2023\/04\/12\/home-assistant-advanced-nord-pool-cheapest-hours-with-local-calendar-support\/\" target=\"_blank\">previous article<\/a> I introduced more advanced cheapest hours automation that can handle devices which can be transferred to use the cheap electricity.<\/p>\n\n\n\n<p>Anyhow, some devices (like the <strong>water boiler<\/strong>) are still too much dependant of the system failures! Let me give you an example: My <a href=\"https:\/\/ui.com\" data-type=\"URL\" data-id=\"https:\/\/ui.com\" target=\"_blank\" rel=\"noreferrer noopener\">Unifi devices<\/a> are automatically updated every night at 01:00 and that might cause my WiFi network to go offline for few minutes. And my water boiler is controlled with <a href=\"https:\/\/www.amazon.de\/-\/en\/Controlled-Intelligent-Measurement-Compatible-Monitoring\/dp\/B0918NR3YC?&amp;_encoding=UTF8&amp;tag=creatingsmart-21&amp;linkCode=ur2&amp;linkId=91db0f1e0091247ff55001d0d1cf205c&amp;camp=1638&amp;creative=6742\" data-type=\"URL\" data-id=\"https:\/\/www.shelly.cloud\/en\/products\/shop\/shelly-3-em-1\" target=\"_blank\" rel=\"noreferrer noopener\">Shelly EM3<\/a> that uses Wifi.. do you already guess where this is going? If the cheapest hours begins at 01:00 <strong>AND<\/strong> Unifi update happens, no control signal will be transferred to the Shelly and water boiler won&#8217;t start heating at all for that night. I think I would <strong>REALLY<\/strong> get some feedback from my wife if there&#8217;s no hot water for the upcoming day \ud83d\ude00<br><br>Well, I think I&#8217;ve found a solution for this corner case as well. Shelly supports internal schedules, but unfortunately <a href=\"https:\/\/www.home-assistant.io\/integrations\/shelly\/\" data-type=\"URL\" data-id=\"https:\/\/www.home-assistant.io\/integrations\/shelly\/\" target=\"_blank\" rel=\"noreferrer noopener\">Shellys Home Assistant integration<\/a> is not supporting them at the moment. However, we can use custom HTTP or MQTT commands for that. <\/p>\n\n\n\n<p>So here&#8217;s the plan what will happen after this enhancement: <\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Next day electricity prices are received and calculated by <a href=\"https:\/\/www.creatingsmarthome.com\/index.php\/2023\/04\/12\/home-assistant-advanced-nord-pool-cheapest-hours-with-local-calendar-support\/\" data-type=\"URL\" data-id=\"https:\/\/www.creatingsmarthome.com\/index.php\/2023\/04\/12\/home-assistant-advanced-nord-pool-cheapest-hours-with-local-calendar-support\/\">cheapest hours automation<\/a><\/li>\n\n\n\n<li>Home Assistant will send command through to set the next active schedule to the Shelly directly<\/li>\n\n\n\n<li>Shelly will handle the relay switch when the time is right<\/li>\n<\/ol>\n\n\n\n<p>In this way we get rid of the dependency with Home Assistant, WiFi and Shelly. Of course there&#8217;s a possibility that during the set schedule sequence, the WiFi is down or Home Assistant is broken (never happened though). But on such special case, Shelly would use previous days schedule, so water would still be heated, even though it might not be the cheapest price at the moment.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Create functionality to set the schedules<\/h2>\n\n\n\n<p>Shelly Gen 1 and Gen2 are totally different from each other by the software. Therefore I&#8217;ve made actually two guides how to achieve schedule settings: one for gen 1 and one for gen 2. For exact list of devices that are gen 1 can be found from <a rel=\"noreferrer noopener\" href=\"https:\/\/shelly-api-docs.shelly.cloud\/gen1\/#shelly-family-overview\" data-type=\"URL\" data-id=\"https:\/\/shelly-api-docs.shelly.cloud\/gen1\/#shelly-family-overview\" target=\"_blank\">Shelly official website<\/a>. If the device you are using is not listed, the device is most probably gen 2.<\/p>\n\n\n\n<p>So depending of your Shelly device, jump either into <strong>Shelly Gen 1<\/strong> or <strong>Shelly Gen 2<\/strong> part of this article!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How-To: Shelly Gen 1<\/h3>\n\n\n\n<p>First generation Shelly devices only supports settings changes by <strong>HTTP POST<\/strong> commands and MQTT is (mostly) just receiving data. So for this operation we can&#8217;t use MQTT, but have to rely on HTTP REST requests instead. <\/p>\n\n\n\n<p>For the REST commands to work, a static ip needs be set to the Shelly device used. <strong>Static ip<\/strong> can (usually) be set from your network router, so please see the manual of the network router used. Once the IP is set as static, mark it down somewhere. We will use it on next step.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.home-assistant.io\/integrations\/rest_command\/\" data-type=\"URL\" data-id=\"https:\/\/www.home-assistant.io\/integrations\/rest_command\/\" target=\"_blank\" rel=\"noreferrer noopener\">Rest commands<\/a> can be used by creating e.g. <strong>rest_command.yaml<\/strong> file and adding the commands into. Just remember to include the file in the main <strong>configuration.yaml<\/strong> file by adding <em>&#8216;rest_command: !include rest_command.yaml&#8217;<\/em> -line into it.<\/p>\n\n\n\n<p>Now that the Shelly is ready and we have the support to add rest command, let&#8217;s create one<a href=\"https:\/\/www.home-assistant.io\/integrations\/rest_command\/\" data-type=\"URL\" data-id=\"https:\/\/www.home-assistant.io\/integrations\/rest_command\/\"> <\/a>to to do what we want to:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>shelly_set_schedule:\n  url: http:\/\/{{deviceip}}\/settings\/relay\/0\n  method: POST\n  payload: 'schedule={{schedule}}&amp;schedule_rules={{rules}}'<\/code><\/pre>\n\n\n\n<p>In the url we need to set the Shelly <strong>endpoint<\/strong> that receives the command, using parameter <em>&#8216;deviceip&#8217;<\/em> in here that will later be provided by the automation. <\/p>\n\n\n\n<p>Depending on your Shelly device and usage, you might want to change relay number to something else (at the end of url line). I&#8217;m using Shelly EM3 that has only one relay, so I&#8217;m using relay index 0.<\/p>\n\n\n\n<p>Second is the method. POST is generally used to <strong>change data<\/strong>, so that&#8217;s what we are using now.<\/p>\n\n\n\n<p>Third is the <strong>payload<\/strong>. We want to set <strong>schedule<\/strong> (on \/ off) and <strong>rules<\/strong> (times) and those comes in as parameters from Home Assistant automations later on. <\/p>\n\n\n\n<p>Rules needs to be in format <strong>HHMM-ddddddd-ff<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>HH<\/strong> = Hour of the schedule<\/li>\n\n\n\n<li><strong>MM<\/strong> = Minute of the schedule<\/li>\n\n\n\n<li><strong>ddddddd<\/strong> = which days should contain the rules, format as in indexed weekday numbers  (<strong>0123456<\/strong> will contain ALL weekdays)<\/li>\n\n\n\n<li><strong>ff<\/strong> = function of the relay. Basically on or off.<\/li>\n<\/ul>\n\n\n\n<p>Now that we know the format, we need to make <strong>two<\/strong> schedules for the cheapest hours: one to turn on and another one to turn off.<\/p>\n\n\n\n<p>I&#8217;m using the same package as used in <a rel=\"noreferrer noopener\" href=\"https:\/\/www.creatingsmarthome.com\/index.php\/2023\/04\/12\/home-assistant-advanced-nord-pool-cheapest-hours-with-local-calendar-support\/\" data-type=\"URL\" data-id=\"https:\/\/www.creatingsmarthome.com\/index.php\/2023\/04\/12\/home-assistant-advanced-nord-pool-cheapest-hours-with-local-calendar-support\/\" target=\"_blank\">calculating the cheapest hours<\/a> and just replacing the action of creating a calendar entry for <strong>cheapest hours<\/strong> by setting the data directly into a Shelly!<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>action:\n  - service: rest_command.shelly_set_schedule\n    data:\n      deviceip: '192.168.1.100'\n      schedule: 'true'\n      rules: &gt;\n        {%- set sensorId = 'sensor.cheapest_hours_energy_water_boiler' -%}\n        {{ as_timestamp(states(sensorId)) |&nbsp;timestamp_custom('%H%M') }}-0123456-on,\n        {{- (as_timestamp(states(sensorId)) + (3600 * state_attr(sensorId, 'number_of_sequential_hours') | float)) |&nbsp;timestamp_custom('%H%M') }}-0123456-off<\/code><\/pre>\n\n\n\n<p>Here&#8217;s another <strong>generic example<\/strong> that set&#8217;s the start time to 00 and end time to 05:00:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>action:\n  - service: rest_command.shelly_set_schedule\n    data:\n      deviceip: '192.168.1.100'\n      schedule: 'true'\n      rules: &gt;\n        {{ as_timestamp(today_at(\"00:00\")) |&nbsp;timestamp_custom('%H%M') }}-0123456-on,\n        {{- as_timestamp(today_at(\"05:00\")) |&nbsp;timestamp_custom('%H%M') }}-0123456-off<\/code><\/pre>\n\n\n\n<p>One more thing, if you are using authentication with the Shellies on a local network, you need also to send <strong>Authorization header<\/strong> with the REST API call. By default, the authentication is disabled on a brand new Shelly so most probably you don&#8217;t need to worry about it.<\/p>\n\n\n\n<p>That&#8217;s it! Simple automation action to set the start and end times directly to Shelly Gen 1 device! <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How-To: Shelly Gen 2<\/h3>\n\n\n\n<p>Shelly Gen 2 is in software perspective totally different device compared to first generation! It has much more versatile API and MQTT can be used to set values to the relay.<\/p>\n\n\n\n<p>For Shelly Gen 2 we are going to use <strong>MQTT<\/strong> for setting the values, so enabling MQTT and connecting it to the local MQTT broker is essential for this to work. If you don&#8217;t have Shelly connected to the broker or don&#8217;t have a MQTT broker at all, you can find guides from <a rel=\"noreferrer noopener\" href=\"https:\/\/www.home-assistant.io\/integrations\/mqtt\/\" data-type=\"URL\" data-id=\"https:\/\/www.home-assistant.io\/integrations\/mqtt\/\" target=\"_blank\">Setting up MQTT on Home Assistant <\/a>and <a rel=\"noreferrer noopener\" href=\"https:\/\/shelly-api-docs.shelly.cloud\/gen2\/ComponentsAndServices\/Mqtt\/\" data-type=\"URL\" data-id=\"https:\/\/shelly-api-docs.shelly.cloud\/gen2\/ComponentsAndServices\/Mqtt\/\" target=\"_blank\">Configuring MQTT on Shelly Gen 2<\/a>. I won&#8217;t be going through these steps on this guide, but if you need any help, please drop a comment in the comment section below.<\/p>\n\n\n\n<p>Once Shelly is connected and verified to work with the local MQTT broker, we are ready to continue. First we need to know the <strong>Shelly Id<\/strong> that is used to communicate with corresponding device through MQTT. So go to your <strong>Shelly configuration page -&gt; settings -&gt; MQTT<\/strong> and check the device id in the corresponding field. Write it down somewhere, we are going to need it in the next step!<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"675\" height=\"395\" src=\"https:\/\/www.creatingsmarthome.com\/wp-content\/uploads\/2023\/04\/Screenshot-2023-04-17-at-14.18.33-small.jpg\" alt=\"\" class=\"wp-image-1852\"\/><\/figure>\n\n\n\n<p>Ok, next let&#8217;s start by making a <a rel=\"noreferrer noopener\" href=\"https:\/\/www.home-assistant.io\/integrations\/script\/\" data-type=\"URL\" data-id=\"https:\/\/www.home-assistant.io\/integrations\/script\/\" target=\"_blank\">Home Assistant script<\/a> that will: <strong>1. clear all schedules<\/strong>, <strong>2. create a new start time<\/strong> and <strong>3. create a new end time<\/strong>. So add a new script from the UI or by editing your <strong>configuration.yaml<\/strong> (or scripts.yaml if using as included) and add the below code on it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mqtt_set_shelly_schedule:\n  alias: 'Set new Shelly (gen 2) schedules using mqtt'\n  sequence:\n    - service: mqtt.publish\n      data:\n        topic: \"{{shellyid}}\/rpc\"\n        payload: '{\"id\": 1, \"src\": \"cheapesthours\", \"method\": \"Schedule.DeleteAll\"}'\n    - service: mqtt.publish\n      data:\n        topic: \"{{shellyid}}\/rpc\"\n        payload: '{\"id\": 2, \"src\": \"cheapesthours\", \"method\": \"Schedule.Create\", \"params\": { \"timespec\": \"0 0 {{start}} * * 0,1,2,3,4,5,6\", \"calls\": &#091;{ \"method\": \"Switch.Set\", \"params\":{\"id\":0,\"on\":true} }]}}'\n    - service: mqtt.publish\n      data:\n        topic: \"{{shellyid}}\/rpc\"\n        payload: '{\"id\": 3, \"src\": \"cheapesthours\", \"method\": \"Schedule.Create\", \"params\": { \"timespec\": \"0 0 {{end}} * * 0,1,2,3,4,5,6\", \"calls\": &#091;{ \"method\": \"Switch.Set\", \"params\":{\"id\":0,\"on\":false} }]}}'<\/code><\/pre>\n\n\n\n<p><strong><sub>Note 14.8.2024: Since &#8216;latest&#8217; Shelly gen 2 fw update the schedule syntax has changed. Old &#8216;SUN,MON,TUE,WED,THU,FRI,SAT&#8217; format is no longer acceptable and weekdays as integers are rquired &#8216;0,1,2,3,4,5,6&#8217; (0 = Sunday).<\/sub><\/strong><\/p>\n\n\n\n<p>Now that we have our script in place, it can be called with <em>service.mqtt_set_shelly_schedule<\/em> and setting data parameters <em>shellyid, start and end<\/em>. There&#8217;s a catch in the script though, Shelly schedules don&#8217;t like the leading zeros. When calling the script, we <strong>can&#8217;t<\/strong> use hours like &#8220;01&#8221;, but it needs to be formatted as &#8220;1&#8221;. That will be handled on the automation part.<\/p>\n\n\n\n<p>Let&#8217;s start creating the automation to set the schedule next. As same as with the gen 1 device guide above, I&#8217;m going to use the same package used in <a rel=\"noreferrer noopener\" href=\"https:\/\/www.creatingsmarthome.com\/index.php\/2023\/04\/12\/home-assistant-advanced-nord-pool-cheapest-hours-with-local-calendar-support\/\" data-type=\"URL\" data-id=\"https:\/\/www.creatingsmarthome.com\/index.php\/2023\/04\/12\/home-assistant-advanced-nord-pool-cheapest-hours-with-local-calendar-support\/\" target=\"_blank\">calculating the cheapest hours<\/a> and just replacing the action of creating a calendar entry for cheapest hour by setting the data directly into a Shelly!<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>action:\n- service: script.mqtt_shelly_set_schedule\n  data:\n    shellyid: shellypro2pm-ec621000f200\n        start: &gt;\n          {%- set sensorId = 'sensor.cheapest_hours_energy_water_boiler' -%}\n          {{ as_timestamp(states(sensorId)) | timestamp_custom('%-H') }} \n        end: &gt;\n          {%- set sensorId = 'sensor.cheapest_hours_energy_water_boiler' -%}\n          {{ (as_timestamp(states(sensorId)) + (3600 * state_attr(sensorId, 'number_of_sequential_hours') | float)) |&nbsp;timestamp_custom('%-H') }} <\/code><\/pre>\n\n\n\n<p>In above automation we are calling the mqtt_shelly_set_schedule script we create earlier and defining the target to be &#8216;<em>shellypro2pm-ec621000f200<\/em>&#8216;. Start and end times will be received from our <em>sensorId<\/em> variable defined in the cheapest hours package. To use it with any other automations, just set the timestamps corresponding for the start and end times.<\/p>\n\n\n\n<p>Another thing to notice in above automation is &#8216;<strong>%-H<\/strong>&#8216; timestamp format. That will strip the possibly leading zero out of the string coming out from the template.<\/p>\n\n\n\n<p>If everything went as expected, automation should be active working as long as you remember to reload your scripts and automations from the developer tools (or restarting the Home Assistant).<\/p>\n\n\n\n<p>And here&#8217;s another more <strong>generic<\/strong> <strong>example<\/strong> to set the on schedule from 00:00 to 05:00:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>action:\n- service: script.mqtt_shelly_set_schedule\n  data:\n    shellyid: shellypro2pm-ec621000f200\n        start: &gt;\n          {{ as_timestamp(today_at(\"00:00\"))|&nbsp;timestamp_custom('%-H') }} \n        end: &gt;\n          {{ as_timestamp(today_at(\"05:00\"))|&nbsp;timestamp_custom('%-H') }} <\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>After this modification for my water boiler automation, I think it&#8217;s going to be even more reliable than before (not that it has failed yet), but I&#8217;m just afraid how much of a &#8216;<em>feedback<\/em>&#8216; I would receive from my wife if the water was not heated during the night  \ud83d\ude00<br><br>Anyhow, it&#8217;s possible and rather simple to make schedules using Shelly APIs directly without using ANY cloud services.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n<div style=\"border: 3px dashed #abb8c3; border-radius: 0%; background-color: inherit; \" class=\"ub-styled-box ub-bordered-box wp-block-ub-styled-box\" id=\"ub-styled-box-36f8f022-f40b-41c2-99a1-5788ebe9d811\">\n<p id=\"ub-styled-box-bordered-content-bb279d18-4252-4029-943f-19d4ca6dec32\"><h5 class=\"wp-block-heading has-text-align-center\">Did you find this guide helpful? You can keep the blog going by bidding me a coffee!<\/h5>\r\n<center>\r\n<script type=\"text\/javascript\" src=\"https:\/\/cdnjs.buymeacoffee.com\/1.0.0\/button.prod.min.js\" data-name=\"bmc-button\" data-slug=\"tokorhon\" data-color=\"#FFDD00\" data-emoji=\"\"  data-font=\"Cookie\" data-text=\"Buy me a coffee\" data-outline-color=\"#000000\" data-font-color=\"#000000\" data-coffee-color=\"#ffffff\" ><\/script>\r\n<\/center><\/p>\n\n\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Since my transformation to dynamic electricity prices are ongoing, I need to try to tackle up all the corner cases that comes with it. In&hellip;<\/p>\n","protected":false},"author":1,"featured_media":1839,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[100],"tags":[105,224,106,7,104,275,274,18],"class_list":["post-1816","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-home-assistant","tag-automation","tag-cheapest-hours","tag-energy-saving","tag-home-assistant","tag-mqtt","tag-rest-api","tag-shelly","tag-wifi","has-post-thumbnail-archive"],"acf":[],"featured_image_src":"https:\/\/www.creatingsmarthome.com\/wp-content\/uploads\/2023\/04\/shelly_schedules.jpg","author_info":{"display_name":"Toni","author_link":"https:\/\/www.creatingsmarthome.com\/index.php\/author\/topsy\/"},"_links":{"self":[{"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/posts\/1816","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/comments?post=1816"}],"version-history":[{"count":42,"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/posts\/1816\/revisions"}],"predecessor-version":[{"id":3336,"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/posts\/1816\/revisions\/3336"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/media\/1839"}],"wp:attachment":[{"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/media?parent=1816"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/categories?post=1816"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.creatingsmarthome.com\/index.php\/wp-json\/wp\/v2\/tags?post=1816"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}