Skip to content

Commit

Permalink
suntime: Add MidnightSunException, PolarNightException
Browse files Browse the repository at this point in the history
Instead of just raising SunTimeException, report
whether we have midnight sun or polar night.

Implemented in a backwards-compatible way by
subclassing SunTimeException.

That catching SunTimeException still works as before
is verified by extending the tests.

Fixes SatAgro/suntime#32

Upstream PR:
SatAgro/suntime@0b59d7b
  • Loading branch information
rfjakob committed Jul 12, 2024
1 parent d0d73d5 commit 447b878
Showing 1 changed file with 23 additions and 12 deletions.
35 changes: 23 additions & 12 deletions Suntime.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,29 @@ class SunTimeException(Exception):
pass


class MidnightSunException(SunTimeException):
"""
Sun is always up (24h of daylight)
"""
pass


class PolarNightException(SunTimeException):
"""
Sun is always down (0h of daylight)
"""
pass


class Sun:
"""
Original: https://github.com/SatAgro/suntime/blob/master/suntime/suntime.py
Ported to Micropython 20.02.2021: Divergentti / Jari Hiltunen
Replaced: date utils. Method call use hour difference to UTC as timezone! This will be added to return.
Updated July 2024 for https://github.com/rfjakob/ntpstrip :
* Integrate MidnightSunException, PolarNightException ( https://github.com/SatAgro/suntime/pull/33 )
"""

def __init__(self, lat, lon, tzone):
Expand All @@ -29,10 +46,8 @@ def get_sunrise_time(self, date=None):

date = localtime() if date is None else date
sr = self._calc_sun_time(date, True)
if sr is None:
raise SunTimeException('The sun never rises on this location (on the specified date)')
else:
return sr
return sr


def get_sunset_time(self, date=None):
"""
Expand All @@ -43,10 +58,8 @@ def get_sunset_time(self, date=None):
"""
date = localtime() if date is None else date
ss = self._calc_sun_time(date, False)
if ss is None:
raise SunTimeException('The sun never sets on this location (on the specified date)')
else:
return ss
return ss


def _calc_sun_time(self, date, isrisetime=True, zenith=90.8):
"""
Expand Down Expand Up @@ -106,11 +119,9 @@ def _calc_sun_time(self, date, isrisetime=True, zenith=90.8):
cosdec * math.cos(to_rad * self._lat))

if cosh > 1:
print("always night")
return None # The sun never rises on this location (on the specified date)
raise PolarNightException("The sun is always down on this location on the specified date")
if cosh < -1:
print("always day")
return None # The sun never sets on this location (on the specified date)
raise MidnightSunException("The sun is always up on this location on the specified date")

# 7b. finish calculating H and convert into hours

Expand Down

0 comments on commit 447b878

Please sign in to comment.