ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
sun.cpp
Go to the documentation of this file.
1#include "sun.h"
2#include "esphome/core/log.h"
3#include <numbers>
4
5/*
6The formulas/algorithms in this module are based on the book
7"Astronomical algorithms" by Jean Meeus (2nd edition)
8
9The target accuracy of this implementation is ~1min for sunrise/sunset calculations,
10and 6 arcminutes for elevation/azimuth. As such, some of the advanced correction factors
11like exact nutation are not included. But in some testing the accuracy appears to be within range
12for random spots around the globe.
13*/
14
15namespace esphome {
16namespace sun {
17
18using namespace esphome::sun::internal;
19
20static const char *const TAG = "sun";
21
22#undef degrees
23#undef radians
24#undef sq
25
26inline num_t degrees(num_t rad) { return rad * 180 / std::numbers::pi; }
27inline num_t radians(num_t deg) { return deg * std::numbers::pi / 180; }
28inline num_t arcdeg(num_t deg, num_t minutes, num_t seconds) { return deg + minutes / 60 + seconds / 3600; }
29inline num_t sq(num_t x) { return x * x; }
30inline num_t cb(num_t x) { return x * x * x; }
31
38
40 // p. 59
41 // UT -> JD, TT -> JDE
42 int y = moment.year;
43 int m = moment.month;
44 num_t d = moment.day_of_month;
45 d += moment.hour / 24.0;
46 d += moment.minute / (24.0 * 60);
47 d += moment.second / (24.0 * 60 * 60);
48 if (m <= 2) {
49 y -= 1;
50 m += 12;
51 }
52 int a = y / 100;
53 int b = 2 - a + a / 4;
54 return ((int) (365.25 * (y + 4716))) + ((int) (30.6001 * (m + 1))) + d + b - 1524.5;
55}
57 // approximation for 2005-2050 from NASA (https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html)
58 int t = moment.year - 2000;
59 return 62.92 + t * (0.32217 + t * 0.005589);
60}
61// Perform a fractional module operation where the result will always be positive (wrapping around)
63 num_t res = fmod(x, y);
64 if (res < 0)
65 res += y;
66 return res;
67}
68
69num_t internal::Moment::jd() const { return julian_day(dt); }
70
72 // dt is in UT1, but JDE is based on TT
73 // so add deltaT factor
74 return jd() + delta_t(dt) / (60 * 60 * 24);
75}
76
77struct SunAtTime {
78 num_t jde;
79 num_t t;
80
81 // eq 25.1, p. 163; julian centuries from the epoch J2000.0
82 SunAtTime(num_t jde) : jde(jde), t((jde - 2451545) / 36525.0) {}
83
84 num_t mean_obliquity() const {
85 // eq. 22.2, p. 147; mean obliquity of the ecliptic
86 num_t epsilon_0 = (+arcdeg(23, 26, 21.448) - arcdeg(0, 0, 46.8150) * t - arcdeg(0, 0, 0.00059) * sq(t) +
87 arcdeg(0, 0, 0.001813) * cb(t));
88 return epsilon_0;
89 }
90
91 num_t omega() const {
92 // eq. 25.8, p. 165; correction factor for obliquity of the ecliptic
93 // in degrees
94 num_t omega = 125.05 - 1934.136 * t;
95 return omega;
96 }
97
98 num_t true_obliquity() const {
99 // eq. 25.8, p. 165; correction factor for obliquity of the ecliptic
100 num_t delta_epsilon = 0.00256 * cos(radians(omega()));
101 num_t epsilon = mean_obliquity() + delta_epsilon;
102 return epsilon;
103 }
104
105 num_t mean_longitude() const {
106 // eq 25.2, p. 163; geometric mean longitude = mean equinox of the date in degrees
107 num_t l0 = 280.46646 + 36000.76983 * t + 0.0003032 * sq(t);
108 return wmod(l0, 360);
109 }
110
111 num_t eccentricity() const {
112 // eq 25.4, p. 163; eccentricity of earth's orbit
113 num_t e = 0.016708634 - 0.000042037 * t - 0.0000001267 * sq(t);
114 return e;
115 }
116
117 num_t mean_anomaly() const {
118 // eq 25.3, p. 163; mean anomaly of the sun in degrees
119 num_t m = 357.52911 + 35999.05029 * t - 0.0001537 * sq(t);
120 return wmod(m, 360);
121 }
122
123 num_t equation_of_center() const {
124 // p. 164; sun's equation of the center c in degrees
125 num_t m_rad = radians(mean_anomaly());
126 num_t c = ((1.914602 - 0.004817 * t - 0.000014 * sq(t)) * sin(m_rad) + (0.019993 - 0.000101 * t) * sin(2 * m_rad) +
127 0.000289 * sin(3 * m_rad));
128 return wmod(c, 360);
129 }
130
131 num_t true_longitude() const {
132 // p. 164; sun's true longitude in degrees
133 num_t x = mean_longitude() + equation_of_center();
134 return wmod(x, 360);
135 }
136
137 num_t true_anomaly() const {
138 // p. 164; sun's true anomaly in degrees
139 num_t x = mean_anomaly() + equation_of_center();
140 return wmod(x, 360);
141 }
142
143 num_t apparent_longitude() const {
144 // p. 164; sun's apparent longitude = true equinox in degrees
145 num_t x = true_longitude() - 0.00569 - 0.00478 * sin(radians(omega()));
146 return wmod(x, 360);
147 }
148
149 EquatorialCoordinate equatorial_coordinate() const {
150 num_t epsilon_rad = radians(true_obliquity());
151 // eq. 25.6; p. 165; sun's right ascension alpha
152 num_t app_lon_rad = radians(apparent_longitude());
153 num_t right_ascension_rad = atan2(cos(epsilon_rad) * sin(app_lon_rad), cos(app_lon_rad));
154 num_t declination_rad = asin(sin(epsilon_rad) * sin(app_lon_rad));
155 return EquatorialCoordinate{degrees(right_ascension_rad), degrees(declination_rad)};
156 }
157
158 num_t equation_of_time() const {
159 // chapter 28, p. 185
160 num_t epsilon_half = radians(true_obliquity() / 2);
161 num_t y = sq(tan(epsilon_half));
162 num_t l2 = 2 * mean_longitude();
163 num_t l2_rad = radians(l2);
164 num_t e = eccentricity();
165 num_t m = mean_anomaly();
166 num_t m_rad = radians(m);
167 num_t sin_m = sin(m_rad);
168 num_t eot = (y * sin(l2_rad) - 2 * e * sin_m + 4 * e * y * sin_m * cos(l2_rad) - 1 / 2.0 * sq(y) * sin(2 * l2_rad) -
169 5 / 4.0 * sq(e) * sin(2 * m_rad));
170 return degrees(eot);
171 }
172
173 void debug() const {
174 // debug output like in example 25.a, p. 165
175 ESP_LOGV(TAG, "jde: %f", jde);
176 ESP_LOGV(TAG, "T: %f", t);
177 ESP_LOGV(TAG, "L_0: %f", mean_longitude());
178 ESP_LOGV(TAG, "M: %f", mean_anomaly());
179 ESP_LOGV(TAG, "e: %f", eccentricity());
180 ESP_LOGV(TAG, "C: %f", equation_of_center());
181 ESP_LOGV(TAG, "Odot: %f", true_longitude());
182 ESP_LOGV(TAG, "Omega: %f", omega());
183 ESP_LOGV(TAG, "lambda: %f", apparent_longitude());
184 ESP_LOGV(TAG, "epsilon_0: %f", mean_obliquity());
185 ESP_LOGV(TAG, "epsilon: %f", true_obliquity());
186 ESP_LOGV(TAG, "v: %f", true_anomaly());
187 auto eq = equatorial_coordinate();
188 ESP_LOGV(TAG, "right_ascension: %f", eq.right_ascension);
189 ESP_LOGV(TAG, "declination: %f", eq.declination);
190 }
191};
192
193struct SunAtLocation {
194 GeoLocation location;
195
196 num_t greenwich_sidereal_time(Moment moment) const {
197 // Return the greenwich mean sidereal time for this instant in degrees
198 // see chapter 12, p. 87
199 num_t jd = moment.jd();
200 // eq 12.1, p.87; jd for 0h UT of this date
201 ESPTime moment_0h = moment.dt;
202 moment_0h.hour = moment_0h.minute = moment_0h.second = 0;
203 num_t jd0 = Moment{moment_0h}.jd();
204 num_t t = (jd0 - 2451545) / 36525;
205 // eq. 12.4, p.88
206 num_t gmst = (+280.46061837 + 360.98564736629 * (jd - 2451545) + 0.000387933 * sq(t) - (1 / 38710000.0) * cb(t));
207 return wmod(gmst, 360);
208 }
209
210 HorizontalCoordinate true_coordinate(Moment moment) const {
211 auto eq = SunAtTime(moment.jde()).equatorial_coordinate();
212 num_t gmst = greenwich_sidereal_time(moment);
213 // do not apply any nutation correction (not important for our target accuracy)
214 num_t nutation_corr = 0;
215
216 num_t ra = eq.right_ascension;
217 num_t alpha = gmst + nutation_corr + location.longitude - ra;
218 alpha = wmod(alpha, 360);
219 num_t alpha_rad = radians(alpha);
220
221 num_t sin_lat = sin(location.latitude_rad());
222 num_t cos_lat = cos(location.latitude_rad());
223 num_t sin_elevation = (+sin_lat * sin(eq.declination_rad()) + cos_lat * cos(eq.declination_rad()) * cos(alpha_rad));
224 num_t elevation_rad = asin(sin_elevation);
225 num_t azimuth_rad = atan2(sin(alpha_rad), cos(alpha_rad) * sin_lat - tan(eq.declination_rad()) * cos_lat);
226 return HorizontalCoordinate{degrees(elevation_rad), degrees(azimuth_rad) + 180};
227 }
228
229 optional<ESPTime> sunrise(ESPTime date, num_t zenith) const { return event(true, date, zenith); }
230 optional<ESPTime> sunset(ESPTime date, num_t zenith) const { return event(false, date, zenith); }
231 optional<ESPTime> event(bool rise, ESPTime date, num_t zenith) const {
232 // couldn't get the method described in chapter 15 to work,
233 // so instead this is based on the algorithm in time4j
234 // https://github.com/MenoData/Time4J/blob/master/base/src/main/java/net/time4j/calendar/astro/StdSolarCalculator.java
235 auto m = local_event_(date, 12); // noon
236 num_t jde = julian_day(m);
237 num_t new_h = 0, old_h;
238 do {
239 old_h = new_h;
240 auto x = local_hour_angle_(jde + old_h / 86400, rise, zenith);
241 if (!x.has_value())
242 return {};
243 new_h = *x;
244 } while (std::abs(new_h - old_h) >= 15);
245 time_t new_timestamp = m.timestamp + (time_t) new_h;
246 return ESPTime::from_epoch_local(new_timestamp);
247 }
248
249 protected:
250 optional<num_t> local_hour_angle_(num_t jde, bool rise, num_t zenith) const {
251 auto pos = SunAtTime(jde).equatorial_coordinate();
252 num_t dec_rad = pos.declination_rad();
253 num_t lat_rad = location.latitude_rad();
254 num_t num = cos(radians(zenith)) - (sin(dec_rad) * sin(lat_rad));
255 num_t denom = cos(dec_rad) * cos(lat_rad);
256 num_t cos_h = num / denom;
257 if (cos_h > 1 || cos_h < -1)
258 return {};
259 num_t hour_angle = degrees(acos(cos_h)) * 240;
260 if (rise)
261 hour_angle *= -1;
262 return hour_angle;
263 }
264
265 ESPTime local_event_(ESPTime date, int hour) const {
266 // input date should be in UTC, and hour/minute/second fields 0
267 num_t added_d = hour / 24.0 - location.longitude / 360;
268 num_t jd = julian_day(date) + added_d;
269
270 num_t eot = SunAtTime(jd).equation_of_time() * 240;
271 time_t new_timestamp = (time_t) (date.timestamp + added_d * 86400 - eot);
272 return ESPTime::from_epoch_utc(new_timestamp);
273 }
274};
275
277 SunAtLocation sun{location_};
278 Moment m{time_->utcnow()};
279 if (!m.dt.is_valid())
280 return HorizontalCoordinate{NAN, NAN};
281
282 // uncomment to print some debug output
283 /*
284 SunAtTime st{m.jde()};
285 st.debug();
286 */
287 return sun.true_coordinate(m);
288}
289optional<ESPTime> Sun::calc_event_(ESPTime date, bool rising, double zenith) {
290 SunAtLocation sun{location_};
291 if (!date.is_valid())
292 return {};
293 // Calculate UT1 timestamp at 0h
294 auto today = date;
295 today.hour = today.minute = today.second = 0;
296 today.recalc_timestamp_utc();
297
298 auto it = sun.event(rising, today, zenith);
299 if (it.has_value() && it->timestamp < date.timestamp) {
300 // We're calculating *next* sunrise/sunset, but calculated event
301 // is today, so try again tomorrow
302 time_t new_timestamp = today.timestamp + 24 * 60 * 60;
303 today = ESPTime::from_epoch_utc(new_timestamp);
304 it = sun.event(rising, today, zenith);
305 }
306 return it;
307}
308optional<ESPTime> Sun::calc_event_(bool rising, double zenith) {
309 auto it = Sun::calc_event_(this->time_->utcnow(), rising, zenith);
310 return it;
311}
312
313optional<ESPTime> Sun::sunrise(double elevation) { return this->calc_event_(true, 90 - elevation); }
314optional<ESPTime> Sun::sunset(double elevation) { return this->calc_event_(false, 90 - elevation); }
315optional<ESPTime> Sun::sunrise(ESPTime date, double elevation) { return this->calc_event_(date, true, 90 - elevation); }
316optional<ESPTime> Sun::sunset(ESPTime date, double elevation) { return this->calc_event_(date, false, 90 - elevation); }
317double Sun::elevation() { return this->calc_coords_().elevation; }
318double Sun::azimuth() { return this->calc_coords_().azimuth; }
319
320} // namespace sun
321} // namespace esphome
uint8_t m
Definition bl0906.h:1
optional< ESPTime > calc_event_(bool rising, double zenith)
Definition sun.cpp:308
double elevation()
Definition sun.cpp:317
internal::HorizontalCoordinate calc_coords_()
Definition sun.cpp:276
optional< ESPTime > sunset(double elevation)
Definition sun.cpp:314
optional< ESPTime > sunrise(double elevation)
Definition sun.cpp:313
double azimuth()
Definition sun.cpp:318
uint8_t hour
const char *const TAG
Definition spi.cpp:8
num_t delta_t(ESPTime moment)
Definition sun.cpp:56
num_t wmod(num_t x, num_t y)
Definition sun.cpp:62
num_t degrees(num_t rad)
Definition sun.cpp:26
num_t arcdeg(num_t deg, num_t minutes, num_t seconds)
Definition sun.cpp:28
num_t radians(num_t deg)
Definition sun.cpp:27
num_t cb(num_t x)
Definition sun.cpp:30
num_t julian_day(ESPTime moment)
Definition sun.cpp:39
num_t sq(num_t x)
Definition sun.cpp:29
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
A more user-friendly version of struct tm from time.h.
Definition time.h:15
uint8_t minute
minutes after the hour [0-59]
Definition time.h:21
uint8_t second
seconds after the minute [0-60]
Definition time.h:19
uint8_t hour
hours since midnight [0-23]
Definition time.h:23
time_t timestamp
unix epoch time (seconds since UTC Midnight January 1, 1970)
Definition time.h:37
bool is_valid() const
Check if this ESPTime is valid (all fields in range and year is greater than 2018)
Definition time.h:59
static ESPTime from_epoch_utc(time_t epoch)
Convert an UTC epoch timestamp to a UTC time ESPTime instance.
Definition time.h:92
uint8_t day_of_month
day of the month [1-31]
Definition time.h:27
uint16_t year
year
Definition time.h:33
uint8_t month
month; january=1 [1-12]
Definition time.h:31
uint16_t x
Definition tt21100.cpp:5
uint16_t y
Definition tt21100.cpp:6