logo elektroda
logo elektroda
X
logo elektroda

OpenBeken Scripting - Time and scheduling with NTP and addClockEvent

ilengyel  4 4797 Cool? (+3)
📢 Listen (AI):

TL;DR

  • OpenBeken scripting uses NTP timekeeping and addClockEvent to automate a porch light with sunrise/sunset-aware switching.
  • The script enables the ntp driver, sets a local server, timezone offset, and latitude/longitude, then waits for NTPState 1 before using time constants.
  • addClockEvent accepts TimerSeconds, HH:mm, HH:mm:ss, or sunrise/sunset, and daysOfWeek uses bit flags such as 0x01 for Sunday and 0x7f for every day.
  • A daily backlog recalculates '$sunset+1800', removes event 4, and re-adds it so lights turn on at the correct delayed sunset time.
  • Sunrise and sunset expressions must be refreshed daily, and daylight saving time adjustment is not supported yet.
Generated by the language model.
User interface for managing lighting with timer and LED controls

Initialising

To allow a device with no battery backup to keep time, NTP must be enabled and configured. The following script will configure an OpenBeken flashed device for a particular time zone and location.

// NTP driver must be enabled for its functions to work
startDriver ntp

// It might be useful to configure a local NTP server on your LAN so that devices do not need to connect to the internet
ntp_setServer 192.168.1.12

// Set the local timezone as NTP server only provide UTC time
ntp_timeZoneOfs 11

// Setting the devices location will allow for calculating sunrise and sunset times
ntp_setLatlong -33.729720 151.160990

// Time values are available once NTP finishes initializing
waitFor NTPState 1

- For setting up a local NTP server on a docker host you can consider: https://github.com/cturra/docker-ntp
- Useful website for finding latitude and longitude values for your location: https://tasmota-tz.cloudfree.io/
- Adjusting timezone offset for daylight saving is not supported yet. Might be able to be done in script, or add a Tasmota style function for this. I will try to solve by April or October :)

Time Constants

When the NTP driver is enabled, there are various time related constants available to use in scripts. They can be found at https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/constants.md. For most of the examples below I will use a porch light scenario which involves a wifi connected dimmable LED light connected to a regular light switch. When the device is switched on, time constants are useful set the initial state, eg during the day time the light will stay off, or switched on after dark the lights initial state is on. To perform calculations with the current time I find it easier to convert the current time to seconds from midnight. $sunrise and $sunset are already in this format.

// sunset is typically still bright enough to see quite well, add another 30 mins to set the time we want the light to be on
setChannel 10 $sunset+1800

// set the current time as seconds after midnight for easy calculations
setChannel 11 $hour*3600+$minute*60

// Set initial light state to match the above clock events
// sunset - 21:00   lights set to high (evening activities)
// 21:00 - 23:00    lights set to low (sleepy mode: warmest temperature and very dim)
// 23:00 - sunrise  lights on for a short period (bedtime the lights should be off, but can be forced on for a period by switching device off and on)
// sunrise - sunset lights turned off (day time the lights should be off)
if $CH11>=$CH10&&$hour<21 then high_lights
if $hour>=21&&$hour<23 then low_lights
if $hour>=23||$CH11<$sunrise then timer_on_lights
if $CH11>=$sunrise&&$CH11<$CH10 then off_lights


Scheduling

In my case I prefer to leave the device on and have the script to automatically turn on, dim and switch off at appropriate times daily. The addClockEvent function is the main driver of this behaviour. The various parameters are as follows:

addClockEvent <time> <daysOfWeek> <id> <command>
time - The time of day for the command to be triggered. This can be various formats: TimerSeconds representing seconds from midnight, Time strings, ie. HH:mm, HH:mm:ss, and sunrise / sunset.
daysOfWeek - bit flag where each bit represent a day of week easiest to specify as hexadecimal numbers eg 0x01 being Sunday, 0x02 is Monday, 0x7f or 0xff being every day of the week. (8th bit is ignored)
id - is a unique ID to remove the event later
command - action to perform at the defined time

Expressions are supported for the time and daysOfWeek parameters. Take care when specifying sunrise and sunset eg the following 2 events are not the same:

// The following will trigger the command at the correct sunset time every day
addClockEvent sunset 0xff 31 echo good night

// The following the first trigger will be correct sunset time, but the following days will use the same time and will deviate from proper sunset time.
addclockEvent $sunset 0xff 32 echo same time as yesterday


To continue my porch light example, we need to update the calculated event time every day:
 // Create an alias to recalculate and update the clock event to trigger at the correct delayed sunset time
alias calc_sunset backlog setChannel 10 $sunset+1800; removeClockEvent 4; addClockEvent $CH10 0xff 4 high_lights; echo Lights will turn on at $CH10

// Trigger the calculation well before sunset, its also a good idea to avoid when daylight savings time get applied eg 2am & 3am
addClockEvent 3:30 0xff 1 calc_sunset
addClockEvent 21:00 0xff 2 low_lights
addClockEvent 23:00 0xff 3 off_lights


Other scheduling examples:
 // multiple expansions in time strings
addClockEvent $hour:$minute:59 0xff 35 ScheduledSomethingAtTheEndOfTheMinute

// single numeric represents seconds
addClockEvent 7 0xff 36 Scheduled7SecondsAfterMidnight

// numeric values greater than 24x60x60 (24hours) the overflow only is considered
addClockEvent 24*60*60+7 0xff 37 Scheduled7SecondsAfterMidnight

// expressions in days of week, eg week days + week end = every day of the week
setChannel 12 0x3e
setChannel 13 0x41
addClockEvent 12:00 $CH12+$CH13 38 LongWayToScheduleNoonEveryDay


For reference here is the full listing of the autoexec.bat file for my porch light.
PowerSave 1
startDriver ntp
ntp_setServer 192.168.1.12
ntp_timeZoneOfs 11
ntp_setLatlong <latitude> <longitude>

// These log events tend to be very noisy when debugging my device.
logfeature 6 0
logfeature 7 0

// Channel 10: maintain sunset time (The time when the light should turn on)
setChannelLabel 10  "<b><span style='color:orange'\>Light ON (Civil Sunset)</span></b>"
setChannelType 10 TimerSeconds

// when using $sunset as an expression in addClockEvent, it needs to be re-calculated every day to take into account different sunset values
alias calc_sunset backlog setChannel 10 $sunset+1800; removeClockEvent 4; addClockEvent $CH10 0xff 4 high_lights; echo Lights will turn on at $CH10

// Channel 11: hidden register to store current time as TimerSeconds
setChannelType 11 TimerSeconds
setChannelPrivate 11 1
setChannelVisible 11 0

// Channel 12: trigger for timer_on_lights
setChannelLabel 12 "Light Timer"
setChannelType 12 Toggle
setChannel 12 0

alias timer_on_lights setChannel 12 1

// Channel 13: 3 way toggle for light settings
setChannelLabel 13 "Switch"
setChannelType 13 OffDimBright

alias off_lights setChannel 13 0
alias low_lights setChannel 13 1
alias high_lights setChannel 13 2

// timer trigger: lights will be on high for 5mins, then on low for a further 25mins, then turned off
addChangeHandler Channel12 == 1 backlog high_lights; addRepeatingEvent 300 1 low_lights; addRepeatingEvent 1500 1 off_lights

addChangeHandler Channel13 == 0 backlog led_enableAll 0; setChannel 12 0; echo lights_set_off
addChangeHandler Channel13 == 1 backlog led_temperature 500; led_dimmer 5; led_enableAll 1; echo lights_set_low
addChangeHandler Channel13 == 2 backlog led_temperature 300; led_dimmer 30; led_enableAll 1; echo lights_set_high

addClockEvent 3:30 0xff 1 calc_sunset
addClockEvent 21:00 0xff 2 low_lights
addClockEvent 23:00 0xff 3 off_lights

waitFor NTPState 1
waitFor MQTTState 1

calc_sunset

// set the current time as TimerSeconds in register for checks below
setChannel 11 $hour*3600+$minute*60

// Set initial light state to match the above clock events
// sunset - 21:00   lights set to high (evening activities)
// 21:00 - 23:00    lights set to low (sleepy mode: warmest temperature and very dim)
// 23:00 - sunrise  lights on for a short period (bedtime the lights should be off, but can be forced on for a period by switching off and on)
// sunrise - sunset lights turned off (day time the lights should be off)
if $CH11>=$CH10&&$hour<21 then high_lights
if $hour>=21&&$hour<23 then low_lights
if $hour>=23||$CH11<$sunrise then timer_on_lights
if $CH11>=$sunrise&&$CH11<$CH10 then off_lights

About Author
ilengyel wrote 20 posts with rating 9 , helped 1 times. Live in city Australia. Been with us since 2009 year.

Comments

p.kaczmarek2 03 Feb 2024 14:55

Thank you, that's a very interesting tutorial! I think I will use it myself soon to make some kind of slowly dimming up light effect along with sunrise, in a form of... wake up system for the bedroom. [Read more]

tomik67 24 Nov 2024 20:18

I have a problem with the sunset time updating. Despite the event being saved.: addClockEvent 3:30 0xff 1 calc_sunset only the sunrise time is updated, the sunset time remains constant every day. Only... [Read more]

ilengyel 28 Nov 2024 22:19

What was the script you used? The one above still works for me... For example, the echo command in the calc_sunset alias prints the following to the log: Info:CMD:Lights will turn on at 73140... [Read more]

ilengyel 19 Dec 2024 13:52

Can you also double check that you have the correct timezone set with the command? The sample value I have above 11 which is Australian Eastern Daylight Saving time. [Read more]

FAQ

TL;DR: Add 4 core settings before scheduling: start NTP, set a server, set timezone, and set latitude/longitude. As the tutorial notes, "NTP must be enabled" first. This FAQ helps OpenBeken users keep correct time, calculate sunrise/sunset, and run reliable daily events with addClockEvent. [#20942294]

Why it matters: Correct NTP, timezone, and event syntax decide whether your OpenBeken device turns lights on at the right daily time or drifts to yesterday’s schedule.

Option What updates daily Best use Main risk
addClockEvent sunset ... Sunset time itself Fixed sunset triggers No built-in delay
addClockEvent $sunset ... Only when recalculated Delayed sunset logic Can reuse an old value
Local LAN NTP server Device time without internet Faster local sync Extra server setup
Internet NTP server Device time from WAN Simpler setup Depends on internet access

Key insight: Use literal sunset for a true daily sunset event. If you use $sunset inside an expression, recalculate it every day and recreate the clock event.

Quick Facts

  • addClockEvent accepts HH:mm, HH:mm:ss, sunrise, sunset, or numeric seconds from midnight as the time parameter. [#20942294]
  • Day flags are bitmasks: 0x01 = Sunday, 0x02 = Monday, and 0x7f or 0xff means every day; the 8th bit is ignored. [#20942294]
  • The porch-light example recalculates delayed sunset at 03:30, dims at 21:00, and turns off at 23:00 every day. [#20942294]
  • The timed light sequence uses addRepeatingEvent 300 for 5 minutes high brightness, then 1500 for 25 minutes before off. [#20942294]
  • A numeric event time above 24×60×60 seconds wraps, so 24*60*60+7 still runs 7 seconds after midnight. [#20942294]

How do I configure NTP, timezone, and latitude/longitude in OpenBeken scripting so a device without battery backup keeps the correct time?

Configure NTP in four steps, then wait until time is valid. 1. Run startDriver ntp and set a server with ntp_setServer 192.168.1.12. 2. Set local offset with ntp_timeZoneOfs 11. 3. Set location with ntp_setLatlong -33.729720 151.160990, then waitFor NTPState 1. That gives the device UTC-based time plus local offset, and it enables sunrise and sunset calculations for that latitude and longitude. [#20942294]

What is addClockEvent in OpenBeken, and what do the time, daysOfWeek, id, and command parameters mean?

addClockEvent is OpenBeken’s scheduler for running a command at a chosen daily time. time can be sunrise, sunset, HH:mm, HH:mm:ss, or seconds from midnight. daysOfWeek is a bit flag such as 0x01 for Sunday or 0xff for every day. id is the unique event number used for later removal. command is the action to run, such as high_lights or echo good night. [#20942294]

Why does addClockEvent sunset update correctly every day, while addClockEvent $sunset can keep using yesterday's sunset time?

addClockEvent sunset updates correctly because sunset is resolved as a live daily time keyword. addClockEvent $sunset can freeze because $sunset is expanded to a numeric value when the event is created. The tutorial shows both forms and states they are not the same. The first keeps tracking the proper sunset each day, while the second can repeat the previous day’s seconds-from-midnight value until you recreate the event. [#20942294]

How can I recalculate a delayed sunset event every day in OpenBeken using an alias like calc_sunset?

Use an alias that recalculates the delayed time, removes the old event, and adds a new one. A working pattern is: alias calc_sunset backlog setChannel 10 $sunset+1800; removeClockEvent 4; addClockEvent $CH10 0xff 4 high_lights. Then schedule it daily with addClockEvent 3:30 0xff 1 calc_sunset. The extra 1800 seconds adds a 30-minute delay after sunset before switching lights to high. [#20942294]

What is TimerSeconds in OpenBeken, and why is it useful for comparing the current time with sunrise and sunset in scripts?

"TimerSeconds is a channel type that stores time as seconds from midnight, making clock values easy to compare, offset, and reuse in expressions." It is useful because $sunrise and $sunset already use that format. The example stores current time as $hour*3600+$minute*60 in Channel 11, then compares it against sunset plus 1800 seconds and against sunrise to choose high, low, timer, or off states. [#20942294]

Why might sunrise update daily in OpenBeken but sunset stay constant until reboot when using calc_sunset and addClockEvent 3:30 0xff 1 calc_sunset?

A stale sunset usually points to script logic or timezone setup, not to the daily scheduler syntax alone. In the follow-up, the original author said the same script still worked and asked for the exact script used. He also noted that calc_sunset should log a changing seconds-from-midnight value, such as 73140. If sunrise changes but sunset does not, verify that the alias actually runs and check the logged recalculated value each day. [#21324389]

Which timezone value should I use with ntp_timeZoneOfs in OpenBeken, and how can a wrong setting affect sunrise and sunset scheduling?

Use the timezone offset for your actual local time, not the sample value from the tutorial. The author later clarified that 11 in the example was Australian Eastern Daylight Saving Time. A wrong ntp_timeZoneOfs can shift calculated local time and make sunrise or sunset events fire at the wrong hour, even if NTP sync itself works. Double-check this first when scheduled sunset seems stuck or misaligned. [#21354826]

What's the best way to schedule porch lights in OpenBeken for sunset to 21:00 high brightness, 21:00 to 23:00 low brightness, and off after 23:00?

Schedule three daily actions and recalculate the sunset-based one. Use calc_sunset to set delayed sunset to $sunset+1800, then create event 4 for high_lights. Add fixed events at 21:00 for low_lights and 23:00 for off_lights. This matches the example behavior: high brightness from delayed sunset to 21:00, low from 21:00 to 23:00, then off after 23:00. [#20942294]

How do I set the initial light state at boot in OpenBeken based on the current time, sunrise, and sunset?

Calculate current time once at boot, then apply ordered if checks. The example stores current time in Channel 11 as $hour*3600+$minute*60. It then sets high lights from delayed sunset until 21:00, low lights from 21:00 to 23:00, timer mode from 23:00 until sunrise, and off from sunrise until delayed sunset. This restores the correct state immediately after power-up instead of waiting for the next scheduled event. [#20942294]

What is NTPState in OpenBeken, and why should scripts waitFor NTPState 1 before using time-based constants?

"NTPState is a status value that shows whether the OpenBeken NTP driver has finished initializing, which matters because time constants are only valid after sync completes." Scripts should call waitFor NTPState 1 before using $hour, $minute, $sunrise, or $sunset. Without that wait, a boot script can read incomplete time data and create wrong initial states or wrong scheduled events. [#20942294]

How do days-of-week bit flags work in OpenBeken addClockEvent, and how do values like 0x01, 0x3e, 0x41, and 0xff map to actual days?

Days-of-week flags use one bit per day. The tutorial states 0x01 is Sunday, 0x02 is Monday, and 0x7f or 0xff means every day; the 8th bit is ignored. In the example, 0x3e represents weekdays and 0x41 represents weekend days, then both are added to schedule noon every day. This bitmask approach lets scripts combine days with hex math instead of listing names. [#20942294]

What happens in OpenBeken if I schedule addClockEvent with a numeric time greater than 24 hours, such as 24*60*60+7?

OpenBeken uses only the overflowed time within the 24-hour day. The example shows that addClockEvent 24*60*60+7 0xff 37 ... still schedules the action 7 seconds after midnight. That means values above 86400 seconds wrap rather than creating a next-day delay. Use this carefully, because it can hide mistakes in time arithmetic. [#20942294]

How can I use addChangeHandler together with addRepeatingEvent in OpenBeken to build a timed lighting sequence like high for 5 minutes, low for 25 minutes, then off?

Trigger the sequence from a channel change, then queue one-shot timed actions. The example uses addChangeHandler Channel12 == 1 backlog high_lights; addRepeatingEvent 300 1 low_lights; addRepeatingEvent 1500 1 off_lights. That gives high brightness immediately, low brightness after 300 seconds, and off after 1500 seconds. The same script maps Channel 13 states to actual LED commands, including dimmer and temperature settings. [#20942294]

Where can I find accurate latitude and longitude for OpenBeken sunrise and sunset calculations, and how precise do those coordinates need to be?

Use a latitude/longitude lookup site, then enter the values with ntp_setLatlong. The tutorial recommends the CloudFree timezone tool and shows coordinates with 6 decimal places: -33.729720 151.160990. That level of precision is clearly accepted by the script examples. OpenBeken uses those coordinates specifically to calculate sunrise and sunset times for your location. [#20942294]

What are the pros and cons of using a local LAN NTP server such as docker-ntp versus syncing OpenBeken devices directly over the internet?

A local LAN NTP server reduces internet dependence, while direct internet sync needs less infrastructure. The tutorial suggests a local server so devices do not need to connect to the internet and points to a Docker-based option for that role. The trade-off is extra setup on your network. Direct internet NTP is simpler, but it adds an external dependency for devices that only need local timekeeping. [#20942294]
Generated by the language model.
%}