logo elektroda
logo elektroda
X
logo elektroda
Dostępna jest polska wersja

Czy wolisz polską wersję strony elektroda?

Nie, dziękuję Przekieruj mnie tam

[BK7231N] I'm thinking about adding sunrise and sunset to NTP events, anyone interested?

rickbronson 6753 60
Best answers

How can sunrise and sunset be added to NTP-based events in OpenBK7231N, and what is the right way to set it up?

Yes — sunrise and sunset can be added to NTP events, and the feature was eventually merged after testing [#20869378][#20906485] Use a single `ntp_setLatlong` command instead of separate latitude/longitude commands, and keep the code behind a `#define` in `obk_config.h`; if you want to avoid breaking config downgrades, do not add new config fields and use globals/statics set from `autoexec.bat` instead [#20819240][#20843876][#20846866] In `autoexec.bat`, start NTP, set the timezone and coordinates, then `waitFor NTPState 1` before creating `addClockEvent sunrise ...` and `addClockEvent sunset ...`, otherwise the events may be created before the timezone change has taken effect [#20823027][#20828244] The implementation was reported to be accurate to about ±1–2 minutes versus published sunrise/sunset times, which was considered acceptable [#20823018][#20869623] If you want a sunset delay like Tasmota’s civil sunset, the simplest workaround suggested was a one-shot `addRepeatingEvent` delay of 30 minutes after the sunset event, but it will not survive a reboot during that delay [#20879370]
ADVERTISEMENT
  • #1 20819097
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    I'm thinking about adding sunrise and sunset to NTP events, anyone interested? Attached is a patch that I haven't tried yet. Any feedback is greatly appreciated.

    Rick
    Attachments:
    • OpenBK7231N-diff-2.patch.zip (4.63 KB) You must be logged in to download this attachment.
  • ADVERTISEMENT
  • #2 20819101
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    The format would be something like this:

    // Example: do event every Thursday at sunrise
    // addClockEvent sunrise 0x08 12 POWER OFF

    The code I used is borrowed heavily from Tasmota, hope there isn't any licensing issue.
  • #3 20819240
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    Very good job, GPL license is okay. My only concern would be memory size, but we can put that in the obk_config.h as a conditional include. Can you open a pull request on Github so we can review it?

    On a code review side, I would suggest some little changes, for a start, I'd think it's better to merge ntp_setLatitude with ntp_setLongitude into one command, you know, we are limited by flash memory, there is no need for two separate command I think
    Helpful post? Buy me a coffee.
  • #4 20820503
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    Okay, thanks for the feedback. I folded both latitude and longitude into one command. I was worried about code space too but was very surprised that the whole thing took less than 900 bytes (not counting any possible increase in math library use via all the trig functions it uses, like atanf, sinf, etc). I'll be testing it during the coming week, these kinds of things take a while to test :)

    Cheers,

    Rick
  • ADVERTISEMENT
  • #5 20823018
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    I've tested the sunrise/sunset algorithm with various cities around the world and it seems to be accurate within +-2 minutes. Not good enough for a space launch blastoff time but maybe good enough for us? There might be an issue with setting it up in the autoexec.bat however. Maybe you have an idea how to fix it. Seems like we might need a "set event when network is live after boot". Also might need to force NTP when the timezone is set instead of doing:

    Info:NTP:NTP offset set, wait for next ntp packet to apply changes

    The above message means that I can't do this in my autoexec.bat:

    PowerSave 1
    addRepeatingEvent 10 1 backlog startDriver NTP; ntp_timeZoneOfs -8; NTP_SetLatlong 44.002130 -123.091473; addClockEvent sunrise 0x7f 12 POWER OFF; addClockEvent sunset 0x7f 13 POWER ON

    Since the offset won't have taken place when I do "addClockEvent sunrise" and I could (potentially) be in the wrong timezone.

    Any ideas about fixing the above is greatly appreciated.

    Rick
  • #6 20823027
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    Hello, are you aware about:
    
    waitFor NTPState 1
    

    style of syntax?

    See random sample script with waitFor here: https://www.elektroda.com/rtvforum/topic4011890-30.html#20822736

    EDIT: Altough.... your question may not be strictly related to that, maybe we just need to recalculate the time in-place at the time of command execution... idk, take OLD offset, subtract it from current time and add a new one...?

    Added after 44 [minutes]:

    EDIT: I did it:
    https://github.com/openshwprojects/OpenBK7231...mmit/55e6ca9ac6a5891470b145c015ee6f3094e6096b
    Helpful post? Buy me a coffee.
  • #7 20824823
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    >> EDIT: I did it:

    Thanks for that! And for the "waitFor NTPState 1" tip. I'll give it a try.

    I've been seeing these happen randomly (in groups of 10):
    Info:NTP:NTP_CheckForReceive: Error while receiving server's msg

    Any ideas?

    BTW, my server is:

    Info:NTP:Server=217.147.223.78, Time offset=-28800
  • #8 20824897
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    Why do you think it's a problem? I've a looked at code and it seems normal, it happens when recv fails. It's UDP, it's not reliable, it may fail to receive data sometimes.
    Helpful post? Buy me a coffee.
  • #9 20828244
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    >> Why do you think it's a problem? I've looked at the code and it seems normal, it happens when recv fails. It's UDP, it's not reliable, it may fail to receive data sometimes.

    I guess maybe I was misled by the "Error" in the message, to me "Error" means there is a problem. But before you change the message verbiage, I have some NTP poll suggestions:
    - increase NTP poll time from 1 minute to ~15 minutes, judging from info on the web 1 minute is too fast.
    - remove polling (and error msg) each second for 10 seconds if poll fails, just quietly wait until the next polling period. If it fails for 5 polls in a row, issue a warning.

    Added after 8 [minutes]:

    I've been testing the sunrise/sunset code and it seems to work well. I've attached a patch to version 1.17.308. Please tell me if there are any issues.

    Here is an example autoexec on how to use it:

    PowerSave 1
    startDriver ntp
    ntp_timeZoneOfs -8
    waitFor NTPState 1
    ntp_SetLatLong 44.002130 -123.091473
    addClockEvent sunrise 0x7f 12 POWER OFF
    addClockEvent sunset 0x7f 13 POWER ON
    Attachments:
    • OpenBK7231N-diff-7.patch.zip (5.29 KB) You must be logged in to download this attachment.
  • #10 20828276
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1
    I have some unrelated questions:

    - Do you know where I can get a *real* BK7231N datasheet. The ones in the forum are helpful but not the real thing.
    - is there way to put pin config's into autoexec, I'm looking for a way to setup the entire config in one file.

    Oh and by the way, I made a mistake in the amount of added space for the sunrise/sunset, it's actually around 11k. Maybe some of that comes from the trig functions that are used. I got this number from looking at the .asm file ending address for 1.17.308 vs my mods.

    Thanks for all the help

    Rick
  • #11 20843843
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    Did you get a chance to look at the patch? If you think the 11k is too much I could #ifdef it with a config setting.

    Rick
  • #12 20843876
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    Sorry for the late reply. I've checked the code, it's good, but why are you adding new fields to config structure? If config size changes between versions, then downgrade will not be possible.
    If you really need to use config structure, maybe reuse those fields:
    Code: C / C++
    Log in, to see the code


    Or maybe just use global variables and expect user to set them in autoexec.bat every time?

    The BK7231 information on our forum is all we know.

    You can use setPinRole to set pins via autoexec.bat : https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/commands.md

    All sunset/sunrise code should be within #define put in obk_config.h
    Helpful post? Buy me a coffee.
  • #13 20846823
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    > Sorry for the late reply.
    No problem.

    > I've checked the code, it's good, but why are you adding new fields to the config structure? If the config size changes between versions, then downgrade will not be possible.
    > If you really need to use the config structure, maybe reuse those fields:
    > Code: c Expand Select all Copy to clipboard

    I did it that way because I thought it was the "right" way to do it. I don't really know this code that well, so how about you tell me the way you think it should be done, and I'll do it.

    > The BK7231 information on our forum is all we know.
    > You can use setPinRole to set pins via autoexec.bat: https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/commands.md

    Thanks much for the info.

    > All sunset/sunrise code should be within #define put in obk_config.h

    Okay, I'll work on that.
  • ADVERTISEMENT
  • #14 20846866
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    If you are unsure about config save, then just let's use global variables and assume that it should be put in autoexec.bat and set on every startup that way
    Helpful post? Buy me a coffee.
  • #15 20851746
    omniron
    Level 11  
    Posts: 114
    Help: 1
    Rate: 6
    Is sunrise and sunset working?
    Would be great!
  • #16 20851758
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    Yes, what is the state of that? Can I merge?
    Helpful post? Buy me a coffee.
  • #18 20852637
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    commands.md is autogenerated from JSON comments in code, do you have a Github account?
    Helpful post? Buy me a coffee.
  • #19 20852775
    omniron
    Level 11  
    Posts: 114
    Help: 1
    Rate: 6

    Thank you Rickbronson for this!
    Wow that is 11K (byte?), sorry.
  • #20 20852974
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    >>20852637
    I do have a GitHub account: github.com/rickbronson
  • #21 20853401
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    Can you open a pull request with your code changes?
    Just move the variables from config to globals (or statics), and let's just assume they will be set every session through autoexec.bat
    Helpful post? Buy me a coffee.
  • #22 20854181
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    Never done a git pull request but would like to try it. Before I do that, please take a quick look at the patch and see if you notice anything you'd like changed.
  • #23 20854213
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1
    Here is the patch.
    Attachments:
    • OpenBK7231N-diff-9.patch.zip (7.2 KB) You must be logged in to download this attachment.
  • #24 20854291
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    It's 99% okay and you can open pull request, however, I forgot to mention, that if you want to add autoexec to docs, you do not need to modify the MD file, you just modify the source json:
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/json/autoexecExamples.json
    and put autoexec there:
    https://github.com/openshwprojects/OpenBK7231T_App/tree/main/docs/autoexecs
    then if you run:
    [BK7231N] I'm thinking about adding sunrise and sunset to NTP events, anyone interested?
    it will generate new MDs based on that info

    But again, it's not a problem, it's just documentation related, the code seems good now
    Helpful post? Buy me a coffee.
  • #25 20855621
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    You'll have to excuse my ignorance of git. I've only used it a little. Here is what I get (on Debian):

    rick@laptop:~/boards/tuya-temp-humidity/OpenBK7231T_App$ git push -u origin sunevent_branch
    Username for 'https://github.com': rickbronson
    Password for 'https://rickbronson@github.com':
    remote: Permission to openshwprojects/OpenBK7231T_App.git denied to rickbronson.
    fatal: unable to access 'https://github.com/openshwprojects/OpenBK7231T_App/': The requested URL returned error: 403
    r
  • #26 20855929
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    I haven't used git command line in a very long time, but don't you need first to push to your local cloned branch, like:
    
    https://github.com/rickbronson/OpenBK7231T_App/
    

    (I modified URL, so it's on your account now) and then open the pull request?

    These days I am using Github GUI 100% time, it is much easier, maybe you can try it out as well.
    Helpful post? Buy me a coffee.
  • #27 20856861
    rickbronson
    Level 3  
    Posts: 29
    Rate: 1

    Yeah, I tried the GUI first but found it very confusing.
    I went to: https://github.com/openshwprojects/OpenBK7231T_App/pulls
    and hit "New pull request" and then, very confusingly, it went to a "Compare changes" page. There was a "create pull request" on that page but it was grayed out. Here is the latest patch, just FYI

    Added after 1 [minutes]:

    Patch
    Attachments:
    • OpenBK7231N-diff-10.patch.zip (6.16 KB) You must be logged in to download this attachment.
  • ADVERTISEMENT
  • #29 20859018
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14649
    Help: 655
    Rate: 12660
    Both Github GUI and Github itself should propose making you a pull request from your branch to parent repository, I think
    Helpful post? Buy me a coffee.
  • #30 20861889
    omniron
    Level 11  
    Posts: 114
    Help: 1
    Rate: 6

    Does sunrise/set work? I can try it out if experimental

    Added after 1 [minutes]:

    Settings panel with options to enable timers and choose sunrise or sunset, along with save options.

Topic summary

✨ A feature to add sunrise and sunset events to NTP-based scheduling on BK7231N devices was proposed and developed, with code inspired by Tasmota and integrated into the OpenBK7231T_App firmware. The implementation includes commands to set latitude and longitude in a single command to save flash memory, and sunrise/sunset events can be added as clock events triggering device actions such as powering relays on or off. Testing showed the sunrise/sunset calculations are accurate within ±2 minutes globally. Challenges addressed include handling NTP synchronization timing, timezone offsets, and ensuring correct event triggering after device reboot or power outages. The code footprint increased by about 11 KB, mainly due to trigonometric calculations. The feature was merged into the main repository with ongoing improvements such as self-tests and documentation updates. Users shared example autoexec.bat scripts demonstrating how to configure the feature, including setting timezone, coordinates, and clock events for controlling lights. Discussions also covered handling manual overrides and state persistence across reboots using LFS commands. The feature is fully functional and available in the latest OpenBK7231T_App firmware, with additional pull requests extending functionality to expose next sunrise/sunset times as constants.

FAQ

TL;DR: OpenBK7231 sunrise/sunset NTP events are now fully functional, add about 1 minute of typical timing error, and were described as "fully acceptable" in self-tests. This FAQ helps BK7231N/BK7231T users automate relays at dawn and dusk, avoid autoexec timing mistakes, and document or submit the feature correctly. [#20869623]

Why it matters: Sunrise/sunset scheduling solves a real automation problem: lights and relays follow local daylight instead of fixed clock times, with workable accuracy and known startup limits.

Approach Best use Main requirement Known limitation
addClockEvent sunrise/sunset Daily daylight-based switching Valid timezone, latitude/longitude, NTP sync First-day edge cases can occur after initial setup
Fixed-time addClockEvent HH:MM Stable manual schedules Only local clock time Does not track seasonal daylight changes
addRepeatingEvent after sunset Simple delay like +30 minutes Sunset event must run first Reboot during delay loses the pending action

Key insight: Put timezone and location in autoexec.bat, then wait for NTP before creating sunrise or sunset events. That ordering prevents wrong-time calculations and makes the feature reliable after daily rescheduling. [#20823027]

Quick Facts

  • The sunrise/sunset code was first estimated at <900 bytes, but later measured at roughly 11 kB, likely due to trig functions such as atanf and sinf. [#20828276]
  • Test results across cities such as Tokyo, Hawaii, São Paulo, New York, Cairo, Moscow, and Sydney showed about ±2 minutes error in manual checks. [#20870355]
  • Built-in self-tests later reported sunrise/sunset timestamp discrepancy of about 1 minute versus official websites, which was accepted for automation use. [#20869623]
  • A failed NTP receive can appear in bursts of 10 messages because UDP is not reliable and recv may fail without indicating a firmware fault. [#20824897]
  • OpenBK7231 documentation examples are generated from JSON sources, including autoexecExamples.json, not by editing Markdown directly. [#20854291]

How do I set up sunrise and sunset NTP events in OpenBK7231T_App using autoexec.bat?

Use autoexec.bat to start NTP, set timezone and coordinates, wait for sync, then add the events. 1. startDriver ntp and ntp_timeZoneOfs .... 2. Set ntp_setLatlong <lat> <long> and run waitFor NTPState 1. 3. Add addClockEvent sunrise ... and addClockEvent sunset ..., for example event IDs 12 and 13. A working sample turns POWER OFF at sunrise and POWER ON at sunset after the wait step. [#20828244]

Why does addClockEvent sunrise or sunset fail if I set ntp_timeZoneOfs in autoexec.bat before NTP has fully synced?

It fails because the new timezone offset is not applied immediately to the current NTP time. The firmware explicitly reports, NTP offset set, wait for next ntp packet to apply changes, so a sunrise or sunset event created right away can use the wrong timezone. That produces the wrong local event time until the next NTP packet arrives. [#20823018]

What is waitFor NTPState 1 in OpenBK7231T_App, and when should I use it in an autoexec script?

waitFor NTPState 1 is a script gate that pauses execution until NTP is live. Use it before any command that depends on correct local time, especially addClockEvent sunrise and addClockEvent sunset. In this thread, it was recommended specifically to fix startup ordering in autoexec.bat. [#20823027]

What is SafeMode in OpenBK7231T_App, and how do I enter it without adding an OnHold event handler?

SafeMode is a recovery mode that lets you regain control after a bad script or configuration. You do not need an OnHold event for it. Enter it by doing 5 quick power off/on cycles, which makes the extra addEventHandler OnHold 8 SafeMode line unnecessary for normal sunrise/sunset automation. [#20950287]

Why does OpenBK7231T_App show "Info:NTP:NTP_CheckForReceive: Error while receiving server's msg" in groups, and is that normal for UDP NTP polling?

Yes, that can be normal because NTP here uses UDP, and UDP does not guarantee delivery. The maintainer checked the code and said the message appears when recv fails. One user noticed the messages arriving in groups of 10, but that alone did not indicate a firmware bug. [#20824897]

How accurate are the OpenBK7231 sunrise and sunset calculations compared with official sunrise/sunset times?

They are accurate enough for home automation, usually around 1 minute in self-tests and up to about ±2 minutes in broader city checks. One maintainer wrote that a 1 minute discrepancy versus official websites was "fully acceptable." That makes the feature suitable for lights, relays, and similar daily triggers. [#20869623]

What's the best way to turn a relay on at sunset and off at sunrise on a BK7231N or BK7231T device?

Use two sunrise/sunset clock events after NTP sync, because that tracks seasonal daylight automatically. For relay 2, a tested pattern is addClockEvent sunrise 0x7f 12 POWER2 OFF and addClockEvent sunset 0x7f 13 POWER2 ON, preceded by timezone, coordinates, and waitFor NTPState 1. That is better than hard-coded times when daylight changes through the year. [#20950188]

How can I make a device restore the correct day or night state after a reboot or power outage if it missed the sunrise or sunset transition?

Use time constants after NTP sync to set the initial state at boot, then let sunrise/sunset events handle later transitions. A posted script compared $hour and $minute with $sunset_hour and $sunset_minute to choose the correct startup mode. "Time constants" are runtime variables that expose computed clock values, including next solar event times, so scripts can restore state after reboot instead of waiting for the next transition. [#20878116]

What is the proper way to add sunrise/sunset documentation and example autoexec files to the OpenBK7231T_App docs system on GitHub?

Update the JSON doc sources, not the generated Markdown file. Put the example script in docs/autoexecs, add its metadata to docs/json/autoexecExamples.json, and then run the docs generation step. The maintainer said commands.md is autogenerated from JSON comments, so direct Markdown edits are not the preferred path. [#20854291]

How do I create a GitHub pull request for OpenBK7231T_App from my own fork if pushing to the main repository gives a 403 permission error?

Push your branch to your own fork first, then open a pull request from that fork to the parent repository. The 403 happened because direct push access to openshwprojects/OpenBK7231T_App.git was denied. After pushing to the personal fork, the contributor successfully created PR #1001 from branch sunrise_sunset_NTP. [#20865847]

Why should sunrise/sunset latitude and longitude settings use globals or autoexec.bat instead of adding fields to the OpenBK7231 config structure?

Use globals or autoexec.bat to avoid changing the persistent config structure size across firmware versions. The maintainer warned that if config size changes, downgrade compatibility breaks. He recommended globals or statics and simply setting latitude and longitude on every startup through autoexec.bat. [#20843876]

OpenBK7231 sunrise/sunset vs Tasmota timers: which approach is better for offset events like civil sunset or delayed light switching?

Use native OpenBK7231 sunrise/sunset events for exact dawn and dusk switching, but Tasmota-style offset behavior is more convenient for civil sunset. In this thread, offset support was not implemented directly. The suggested OpenBK7231 workaround was to trigger a delayed action from the sunset event, which works but is less robust than a built-in offset model. [#20879370]

How can I delay a sunset-triggered action by 30 minutes in OpenBK7231T_App, and what happens if the device reboots during that delay?

Trigger a one-shot repeating event from the sunset event with a 30 minute delay, or 30×60 seconds. That is the simplest workaround for civil-sunset-like behavior. The downside is clear: if the device reboots during that delay window, the pending delayed action is lost because the temporary timer is not preserved across reboot. [#20879370]

Where can I find a real BK7231N datasheet, and what official hardware information is actually available?

You likely cannot get a full public BK7231N datasheet from this project, because the maintainer said the forum information is all they know. In other words, the practical hardware reference here is the project’s forum and command documentation, not an official vendor datasheet package. That was the direct answer given in the thread. [#20843876]

Why is BL602 apparently ignored by the sunrise/sunset implementation in OpenBK7231T_App, and what needs to change to make sunset calculation work there?

The thread raises the BL602 issue but does not answer it, so the exact reason is unresolved here. The only concrete clue is a 2025-01-12 report pointing to a commit in PR #1030 and asking why BL602 was excluded from sunset calculation. From this thread alone, the next step is to inspect that commit and add the missing BL602-specific path or guard changes there. [#21389444]
ADVERTISEMENT