Sunrise and sunset events
[wakeup.git] / src / sunrise.cpp
1 // Caluculate the time of sunrise and sunset
2
3 #include <math.h>
4 #include <date.h>
5 #include <iostream>
6
7 #include "location.h"
8
9 // Calculate the time of sunrise in timezone UTC.
10
11 hour Location::calculate_sunrise(date when)
12 {
13    float Declanation;
14    float solaroffset;
15    float h0;
16
17    hour midday(12, 0, 0);
18
19    double labda_y = latitude * M_PI / 180.0;
20
21    // Declanation of the sun  as determined by the tilt of the earth's axis.
22
23    Declanation = -23.44 * cos(2 * M_PI * (when.YearDay() + 10) / 365);
24
25    // The earth rotates 15 degrees in 1 hour
26
27    solaroffset = longitude / 15.0 * 3600;   // In seconds
28
29    h0 = acos ( (-1 * tan (labda_y) * tan (Declanation * M_PI / 180.0)));
30
31    long sunseconds = h0 * 12.0 / M_PI * 3600;
32    hour  sunhours(sunseconds / 3600, (sunseconds / 60) % 60, sunseconds % 60);
33
34    // Calculate the time of sunrise
35
36    hour sunrise = midday - sunseconds;
37    sunrise = sunrise - hour(long(solaroffset));
38    return sunrise;
39
40 }
41
42 // Calculate the time of sunset in timezone UTC.
43
44 hour Location::calculate_sunset(date when)
45 {
46    float Declanation;
47    float solaroffset;
48    float h0;
49
50    hour midday(12, 0, 0);
51
52    double labda_y = latitude * M_PI / 180.0;
53
54    // Declanation of the sun  as determined by the tilt of the earth's axis.
55
56    Declanation = -23.44 * cos(2 * M_PI * (when.YearDay() + 10) / 365);
57
58    // The earth rotates 15 degrees in 1 hour
59
60    solaroffset = longitude / 15.0 * 3600;   // In seconds
61
62    h0 = acos ( (-1 * tan (labda_y) * tan (Declanation * M_PI / 180.0)));
63
64    long sunseconds = h0 * 12.0 / M_PI * 3600;
65    hour  sunhours(sunseconds / 3600, (sunseconds / 60) % 60, sunseconds % 60);
66
67    // Calculate the time of sunset
68
69    hour sunset = midday + sunseconds;
70    sunset = sunset - hour(long(solaroffset));
71    return sunset;
72
73 }
74
75 UTC Location::utc_to_localtime(date when, hour utc_time)
76 {
77    struct tm tp_utc;
78    time_t    utc_t;
79    struct tm *local_tm;
80
81
82    tp_utc.tm_year = when.Year() - 1900;
83    tp_utc.tm_mon  = when.Month() - 1;
84    tp_utc.tm_mday = when.Day();
85    tp_utc.tm_hour = utc_time.Hour();
86    tp_utc.tm_min  = utc_time.Minute();
87    tp_utc.tm_sec  = utc_time.Second();
88    tp_utc.tm_isdst = -1;
89
90    utc_t = timegm(&tp_utc);
91
92    local_tm = localtime(&utc_t);
93    UTC local_time(mktime(local_tm));
94
95    return local_time;
96
97 }
98