<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>gpiozero Archives - VPN Expert</title>
	<atom:link href="https://vpn-expert.info/tag/gpiozero/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Life is too short to remove USB safely …</description>
	<lastBuildDate>Thu, 20 Jan 2022 16:17:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.2.2</generator>
	<item>
		<title>Astral — calculate sunrise, sunset, moon phases, golden / blue hour with Python</title>
		<link>https://vpn-expert.info/astral-calculate-sunrise-sunset-moon-phases-golden-blue-hour-with-python/</link>
					<comments>https://vpn-expert.info/astral-calculate-sunrise-sunset-moon-phases-golden-blue-hour-with-python/#comments</comments>
		
		<dc:creator><![CDATA[guyfawkes]]></dc:creator>
		<pubDate>Wed, 27 May 2020 12:38:55 +0000</pubDate>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[Raspberry Pi]]></category>
		<category><![CDATA[Astral]]></category>
		<category><![CDATA[Buster]]></category>
		<category><![CDATA[GPIO]]></category>
		<category><![CDATA[gpiozero]]></category>
		<category><![CDATA[Latitude]]></category>
		<category><![CDATA[Longitude]]></category>
		<category><![CDATA[Moon]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Sunrise]]></category>
		<category><![CDATA[Sunset]]></category>
		<guid isPermaLink="false">https://vpn-expert.info/?p=370</guid>

					<description><![CDATA[<p>Now that I have taken a closer look at astral, I really like it, I must say. So far, I have been able to get the data for sunrise and sunset online. But since the calculations with Astral hardly differ from the online results, I prefer an offline solution. I would like to emphasize again [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://vpn-expert.info/astral-calculate-sunrise-sunset-moon-phases-golden-blue-hour-with-python/">Astral — calculate sunrise, sunset, moon phases, golden / blue hour with Python</a> appeared first on <a rel="nofollow" href="https://vpn-expert.info">VPN Expert</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Now that I have taken a closer look at astral, I really like it, I must say. So far, I have been able to get the data for <a href="https://vpn-expert.info/sunrise-sunset-switch-raspberry-pi-with-python/">sunrise and sunset online</a>. But since the calculations with Astral hardly differ from the online results, I prefer an offline solution.</p>



<p>I would like to emphasize again that the Raspberry Pi does not have an RTC (Real Time Clock). In order for the Raspberry Pi to set the correct time at startup, it must be online. Of course, you can set the clock manually or you can solder an RTC. The difference is that the Pi only needs to be online for a short time. Another advantage is that the Python script is much shorter and therefore clearer.</p>



<p>Since Astral works with Python 3, you are not limited to a Raspberry Pi. But the Pi is well suited for smart home projects or just to experiment with it.</p>



<h2 class="wp-block-heading">Install Astral</h2>



<p>On the Raspberry Pi, Astral is quickly installed via <em>pip</em>, provided that this is available. If not – install it. Here are the commands for both:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo apt install python3-pip
pip3 install astral</code></pre>



<p>That&#8217;s it. Unlike in the desktop version, <em>gpiozero</em> is not installed on <em>Raspbian Lite</em>. Since I switch the GPIO pins with Astral at the end, I do this step right away:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo apt install python3-gpiozero</code></pre>



<p>Now I am good to go. By the way, my Raspberry Pi is running <em>Raspbian Buster</em>.</p>



<h2 class="wp-block-heading">My new script</h2>



<p>I would like to show you the script I am using now – at least with the concept of it. It looks lie this:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo
from astral.sun import sun
from datetime import datetime
from time import sleep
import pytz

utc=pytz.UTC

city = LocationInfo("London", "England", "Europe/London", 51.5, -0.116) # swap with your location

while True:

    s = sun(city.observer)
    time_now = utc.localize(datetime.now())
    sunrise = s["sunrise"]
    dusk = s["dusk"]

    if time_now > sunrise and time_now &lt; dusk: # am I in between sunset and dusk?
        print("Daylight")
    else:
        print("Switch on light")

    sleep(60)</code></pre>



<p>The script is very logical. In my case, it gets the data for sunrise and dusk. Then the program checks if the current time is between sunrise and dusk. If that is the case, it tells you that it is daylight — if not, it is dark.</p>



<p>This is an infinite loop that pauses for 60 seconds at the end of a run.</p>



<p>With my online solution I still checked the date and only made a query to the API when the date changed. I could do the same here, but the calculation is so fast that I don&#8217;t think it&#8217;s necessary.</p>



<h2 class="wp-block-heading">My night light with pfFace Digital and Astral</h2>



<p>Why I use a piFace Digital? Because I already have it and it was a birthday present — plus the thing works. Today I would rather use an Automation HAT, I think — or take a relay and switch it via GPIO.</p>



<p>My Raspberry Pi B with the piFace Digital now switches my night light as follows.</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo
from astral.sun import sun
from datetime import datetime
from time import sleep
import pifacedigitalio as p
import pytz

utc=pytz.UTC

pifacedigital = p.PiFaceDigital()
pifacedigital.output_pins[3].turn_on() # Schaltet bei einem Pi-Neustart an, ist nur ein Check

sleep(10)

city = LocationInfo("London", "England", "Europe/London", 51.5, -0.116) # swap with your location

while True:

    s = sun(city.observer)
    time_now = utc.localize(datetime.now())
    sunrise = s["sunrise"]
    dusk = s["dusk"]

    if time_now > sunrise and time_now &lt; dusk: # am I in between sunrise and dusk?
        if pifacedigital.output_pins[3].value == 1: # if the relay is not off
            pifacedigital.output_pins[3].turn_off() # switch it off
    else:
        if pifacedigital.output_pins[3].value != 1: # if the relay is not on
            pifacedigital.output_pins[3].turn_on() # switch it on

    sleep(60)</code></pre>



<p>In the <em>if-else</em>, the system checks whether the light is already switched on or not. With this I prevent a short flickering because otherwise the piFace Digital will switch the light.</p>



<p>I also convert <em>time_now</em> to UTC because otherwise I cannot compare. The date including time from Astral comes with a time zone specification and if I do not convert <em>time_now</em>, the program tells me: <em>TypeError: can&#8217;t compare offset-naive and offset-aware datetimes</em></p>



<p>This is basically: <em>you cannot compare apples with oranges</em>.</p>



<p>My Pi is running in the timezone UTC, just to make things easier. If you want to work with a time zone, you could for example use <em>timedelta</em> to adjust your current time by <em>x</em> hours to match your timezone. There are several possibilities at this point. Here an example with plus and minus 2 hours.</p>



<pre class="wp-block-code"><code lang="python" class="language-python">import datetime

tdplus = datetime.datetime.now() + datetime.timedelta(hours=2)
tdminus = datetime.datetime.now() - datetime.timedelta(hours=2)

print(tdplus)
print(tdminus)</code></pre>



<h2 class="wp-block-heading">Switching GPIO Pins with Astral</h2>



<p>The script can of course also be easily customized to switch GPIO pins. As said before, you can switch a suitable relay with it or you just experiment with an LED.</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo
from astral.sun import sun
from datetime import datetime
from time import sleep
from gpiozero import LED
import pytz

utc=pytz.UTC

led = LED(17)

city = LocationInfo("London", "England", "Europe/London", 51.5, -0.116) # swap with your location


while True:

    s = sun(city.observer)
    time_now = utc.localize(datetime.now())
    sunrise = s["sunrise"]
    dusk = s["dusk"]

    if time_now > sunrise and time_now &lt; dusk: # am I in between sunrise and dusk?
        led.off()
    else:
        led.on()

    sleep(60)</code></pre>



<p>In my case, I switch GPIO17 (pin 11).</p>



<p>Maybe I will change the behaviour to the end of the dawn. The advantage of this solution compared to a conventional timer is that I can really only switch the night light during the dark hours. Another advantage is that it is simply fun to fiddle with. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Astral can do a lot more</h2>



<p>While we are working with Astral let&#8217;s have a look at a few practical examples.</p>



<p>In the <a href="https://astral.readthedocs.io/en/latest/index.html">documentation</a> you can read that location data for various cities are available in a database. All capitals are included, plus a few additional cities from Great Britain and the USA. You can query the database as follows:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo
from astral.geocoder import database, lookup

city = lookup("Amsterdam", database())
print(city)</code></pre>



<p>This gives me the following output:</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://vpn-expert.info/wp-content/uploads/2020/05/astral-amsterdam-1024x38.png" alt="The database of Astral contains location information from all capitals" class="wp-image-371"/><figcaption>The database of Astral contains location information from all capitals</figcaption></figure>



<p>I can also query the values individually:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo
from astral.geocoder import database, lookup

city = lookup("Berlin", database())

print(city.name)
print(city.region)
print(city.timezone)
print(city.latitude)
print(city.longitude)</code></pre>



<p>But I don&#8217;t have to use the database, I <strong>can define my location</strong>. Of course, I don&#8217;t have to import <em>astral.geocoder</em> for this. If you want the calculation to be as exact as possible, it is best to define <em>latitude</em> and <em>longitude</em> yourself:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo

city = LocationInfo(name="Cordoba", region="Spain", timezone="Europe/Spain", latitude=37.8833333, longitude=-4.7666667)

print((
    f"Information for {city.name}/{city.region}\n"
    f"Timezone: {city.timezone}\n"
    f"Latitude: {city.latitude:.02f}; Longitude: {city.longitude:.02f}\n" ))</code></pre>



<p>OK, now we&#8217;ve defined our location. Let&#8217;s see what we can do with it.</p>



<h2 class="wp-block-heading">Sunrise, sunset, dawn and dusk</h2>



<p>With the location, Astral calculates the desired times, by default in UTC. This is relatively simple and looks like this:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo
from astral.sun import sun

city = LocationInfo(name="Cordoba", region="Spain", timezone="Europe/Spain", latitude=37.8833333, longitude=-4.7666667)

c_data = sun(city.observer)

print("Sunrise: " + str(c_data["sunrise"]))
print("Sunset: " + str(c_data["sunset"]))
print("Dawn: " + str(c_data["dawn"]))
print("Dusk: " + str(c_data["dusk"]))</code></pre>



<p>It looks like that:</p>



<figure class="wp-block-image size-large"><img decoding="async" loading="lazy" width="427" height="99" src="https://vpn-expert.info/wp-content/uploads/2020/05/astral-sunrinse-sunset-dawn-dusk.png" alt="With Astral I get sunrise, sunset, dawn and dusk – easy" class="wp-image-372" srcset="https://vpn-expert.info/wp-content/uploads/2020/05/astral-sunrinse-sunset-dawn-dusk.png 427w, https://vpn-expert.info/wp-content/uploads/2020/05/astral-sunrinse-sunset-dawn-dusk-300x70.png 300w" sizes="(max-width: 427px) 100vw, 427px" /><figcaption>With Astral I get sunrise, sunset, dawn and dusk — easy</figcaption></figure>



<p><strong>Note</strong>: The times are calculated when the sun breaks through the horizon in clear visibility — obstacles in the eye of the observer are ignored.</p>



<p>If you do <strong>not enter a date, Astral will calculate with the current date</strong>. You can also have the values calculated for a specific date. You only have to specify it when defining <em>c_data </em>and import <em>datetime</em>. Here is an example for October 21, 2019:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo
from astral.sun import sun

city = LocationInfo(name="Cordoba", region="Spain", timezone="Europe/Spain", latitude=37.8833333, longitude=-4.7666667)

c_data = sun(city.observer, date=datetime.date(2019, 10, 21))

print("Sunrise: " + str(c_data["sunrise"]))
print("Sunset: " + str(c_data["sunset"]))
print("Dawn: " + str(c_data["dawn"]))
print("Dusk: " + str(c_data["dusk"]))</code></pre>



<p>The documentation says that you can also display information about the <strong>golden hour</strong> and <strong>blue hour</strong>. Especially for photographers this is important information.</p>



<h2 class="wp-block-heading">Golden hour and blue hour</h2>



<p>The <strong>blue hour</strong> and the <strong>golden hour</strong> appear twice a day. In simple terms: blue hour > the sun is below the horizon and golden hour > just above. In the blue hour the blue light spectrum dominates and in the golden hour the colours are much softer and warmer.</p>



<figure class="wp-block-image size-large"><img decoding="async" loading="lazy" width="1024" height="682" src="https://vpn-expert.info/wp-content/uploads/2020/05/golden-hour-1024x682.jpg" alt="Golden hour" class="wp-image-373" srcset="https://vpn-expert.info/wp-content/uploads/2020/05/golden-hour-1024x682.jpg 1024w, https://vpn-expert.info/wp-content/uploads/2020/05/golden-hour-300x200.jpg 300w, https://vpn-expert.info/wp-content/uploads/2020/05/golden-hour-768x512.jpg 768w, https://vpn-expert.info/wp-content/uploads/2020/05/golden-hour.jpg 1400w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Golden hour</figcaption></figure>



<p>Unlike sunrise or sunset, <em>blue hour</em> and <em>golden hour</em> have two values: beginning and end. If you do not give an additional value, Astral calculates to the rising sun by default. Let&#8217;s get the data:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo
from astral.sun import golden_hour
from astral.sun import blue_hour

city = LocationInfo(name="Cordoba", region="Spain", timezone="Europe/Spain", latitude=37.8833333, longitude=-4.7666667)

gh = golden_hour(city.observer)
bh = blue_hour(city.observer)

print("Golden hour start: " + str(gh[0]))
print("Golden hour end: " + str(gh[1]))
print("Blue hour start: " + str(bh[0]))
print("Blue hour end: " + str(bh[1]))</code></pre>



<p>If I want to calculate the <em>golden hour</em> and the <em>blue hour</em> for the evening, I have to set the direction of the sun to <em>SETTING. RISING </em>is also available, but that is the default, as already mentioned. If I want to get the data for the evening this, the code looks like this (<em>golden hour </em>in the evening and <em>blue hour</em> in the morning):</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral import LocationInfo
from astral.sun import SunDirection
from astral.sun import golden_hour
from astral.sun import blue_hour
from datetime import datetime

city = LocationInfo(name="Cordoba", region="Spain", timezone="Europe/Spain", latitude=37.8833333, longitude=-4.7666667)

gh = golden_hour(city.observer, datetime.now().date(), SunDirection.SETTING)
bh = blue_hour(city.observer)

print("Golden hour start: " + str(gh[0]))
print("Golden hour end: " + str(gh[1]))
print("Blue hour start: " + str(bh[0]))
print("Blue hour end: " + str(bh[1]))</code></pre>



<p>You can also see that the <em>golden hour</em> and the <em>blue hour</em> are not really 60 minutes. It depends a lot on location and season. So, it&#8217;s good to know when to have your camera ready.</p>



<figure class="wp-block-image size-large"><img decoding="async" loading="lazy" width="1024" height="682" src="https://vpn-expert.info/wp-content/uploads/2020/05/blue_hour-1024x682.jpg" alt="Blue hour" class="wp-image-374" srcset="https://vpn-expert.info/wp-content/uploads/2020/05/blue_hour-1024x682.jpg 1024w, https://vpn-expert.info/wp-content/uploads/2020/05/blue_hour-300x200.jpg 300w, https://vpn-expert.info/wp-content/uploads/2020/05/blue_hour-768x512.jpg 768w, https://vpn-expert.info/wp-content/uploads/2020/05/blue_hour.jpg 1280w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Blue hour</figcaption></figure>



<p>By the way, we can also use Astral to get information about the moon.</p>



<h2 class="wp-block-heading">Calculate moon phases with Astral</h2>



<p>The tool can also output the moon phases. Using the date, the Python program spits out a number between 0 and 28. In the documentation we find how to interpret the numbers of the moon phases:</p>



<ul><li>0 – 6.99 — new moon</li><li>7 – 7.99 — waxing moon</li><li>14 – 20.99 — full moon</li><li>21 – 27.99 — waning moon</li></ul>



<p>To make things a bit more exciting, let&#8217;s have the moon phase of yesterday, today and tomorrow displayed. Especially the following day makes sense, if you want to know when the moon is at its fullest, for example:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral.moon import phase
import datetime

moon_today = phase()
moon_yesterday = phase(datetime.datetime.now() - datetime.timedelta(days=1))
moon_tomorrow = phase(datetime.datetime.now() + datetime.timedelta(days=1))

print("Mond gestern", end=": ")
print(moon_yesterday)
print("Mond heute", end=": ")
print(moon_today)
print("Mond morgen", end=": ")
print(moon_tomorrow)</code></pre>



<p>If you are into star photography you want to have as little moon as possible, right? With the following script we find out, for example, when the moon is the fullest and least visible in the next 365 days:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from astral.moon import phase
import datetime

moon_dic = {}

for var in list(range(365)):
    date_temp = datetime.datetime.now().date() + datetime.timedelta(days=(var))
    moon_phase = phase(date_temp)
    moon_dic[moon_phase] = date_temp

darkest = min(moon_dic)
print(moon_dic.get(darkest), end=": ")
print(darkest)

darkest2 = max(moon_dic)
print(moon_dic.get(darkest2), end=": ")
print(darkest2)</code></pre>



<p>Now I know that during the next 365 days the moon will be very little visible on September 17, 2020 and May 11, 2021.</p>



<p>When it&#8217;s at its fullest, I can&#8217;t say exactly. The tool tells me that between 14 – 20.99 is full moon — but not exactly when the moon is fullest. Is that exactly halfway, so 14? I&#8217;ll stare at the sky and try to find that out for myself at the next full moon.</p>



<figure class="wp-block-image size-large"><img decoding="async" loading="lazy" width="1024" height="682" src="https://vpn-expert.info/wp-content/uploads/2020/05/moon-1024x682.jpg" alt="Get the moon phases with Astral" class="wp-image-375" srcset="https://vpn-expert.info/wp-content/uploads/2020/05/moon-1024x682.jpg 1024w, https://vpn-expert.info/wp-content/uploads/2020/05/moon-300x200.jpg 300w, https://vpn-expert.info/wp-content/uploads/2020/05/moon-768x512.jpg 768w, https://vpn-expert.info/wp-content/uploads/2020/05/moon.jpg 1400w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Get the moon phases with Astral</figcaption></figure>



<p>The tool can calculate some other data. At the moment that is all I need. I can get what I want and have the data sent to my smartphone (with <a href="https://vpn-expert.info/coronavirus-beware-of-malware-better-make-own-update-ticker-monthofmaking/">pushover like my Coronavirus data</a>).</p>



<p>Now I have my <a href="https://vpn-expert.info/bitcoin-price-tracker-with-raspberry-pi-sense-hat-and-python/">Bitcoin Ticker</a>, a Coronavirus Ticker and a <strong>tool for sunrise, sunset, blue hour, golden hour and moon phases</strong>. I know that there are different apps for this, but I need to install less stuff on my smartphone and I can also customize the tools the way I want to. This way I can have very specific information sent to me.</p>



<h2 class="wp-block-heading">I hope that was clear</h2>



<p>I wrote this article to understand Astral a little better myself. A few things are not obvious to me yet, but on the whole I understand how to use Astral.</p>



<p>Maybe this article will help you to do something useful with the tool. Now that I understand how to use it, I really like it. In any case, there are many possibilities how to use the data calculated by Astral.</p>
<p>The post <a rel="nofollow" href="https://vpn-expert.info/astral-calculate-sunrise-sunset-moon-phases-golden-blue-hour-with-python/">Astral — calculate sunrise, sunset, moon phases, golden / blue hour with Python</a> appeared first on <a rel="nofollow" href="https://vpn-expert.info">VPN Expert</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://vpn-expert.info/astral-calculate-sunrise-sunset-moon-phases-golden-blue-hour-with-python/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Sunrise / Sunset switch Raspberry Pi with Python</title>
		<link>https://vpn-expert.info/sunrise-sunset-switch-raspberry-pi-with-python/</link>
					<comments>https://vpn-expert.info/sunrise-sunset-switch-raspberry-pi-with-python/#comments</comments>
		
		<dc:creator><![CDATA[guyfawkes]]></dc:creator>
		<pubDate>Sat, 29 Feb 2020 07:10:20 +0000</pubDate>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[Raspberry Pi]]></category>
		<category><![CDATA[GPIO]]></category>
		<category><![CDATA[gpiozero]]></category>
		<category><![CDATA[LED]]></category>
		<category><![CDATA[PiFace Digital]]></category>
		<category><![CDATA[Raspbian]]></category>
		<category><![CDATA[Relay]]></category>
		<category><![CDATA[Sunrise]]></category>
		<category><![CDATA[Sunset]]></category>
		<category><![CDATA[UTC]]></category>
		<category><![CDATA[VPN]]></category>
		<category><![CDATA[VPN Router]]></category>
		<guid isPermaLink="false">https://vpn-expert.info/?p=296</guid>

					<description><![CDATA[<p>After I rediscovered my PiFace Digital, I wanted to play with it a bit. I thought that I could switch a night light with one of the relays. But I didn&#8217;t want to estimate roughly when it is dark, I wanted to orientate by the current sunrise and sunset. Of course, it doesn&#8217;t matter what [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://vpn-expert.info/sunrise-sunset-switch-raspberry-pi-with-python/">Sunrise / Sunset switch Raspberry Pi with Python</a> appeared first on <a rel="nofollow" href="https://vpn-expert.info">VPN Expert</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>After I rediscovered my PiFace Digital, I wanted to play with it a bit. I thought that I could switch a night light with one of the relays. But I didn&#8217;t want to estimate roughly when it is dark, I wanted to orientate by the current <strong>sunrise</strong> and <strong>sunset</strong>.</p>



<p>Of course, it doesn&#8217;t matter what you switch with it. If the GPIO interface of the Raspberry Pi is sufficient, you can also switch an LED when it gets dark. This might even be enough for a night light, I have to test it. Since I have a PiFace Digital that gives me switchable 5V on the Raspberry Pi, I took this. With the GPIO interface you can also switch another relay. Other options would be you use IR or even switch the USB ports of the Raspberry Pi on and off.</p>



<p><strong>Note</strong>: I switched to Astral doing this. <a href="https://vpn-expert.info/astral-calculate-sunrise-sunset-moon-phases-golden-blue-hour-with-python/">Here is an in depth explanation how to do this and what Astral can do for you</a>.</p>



<h2 class="wp-block-heading">Sunrise off / Sunset on</h2>



<p>Three things were important to me for this project:</p>



<ol><li>Getting the time of sunrise and sunset of the given day.</li><li>Check if I am between sunrise and sunset because the relay should be off then.</li><li>Get the data again at the change of day. It is not necessary to retrieve the data continuously.</li></ol>



<figure class="wp-block-image size-large"><img decoding="async" src="https://vpn-expert.info/wp-content/uploads/2020/01/walking-man-1024x683.jpg" alt="Switch the night light on at sunset and off at sunrise" class="wp-image-128"/><figcaption>Switch the night light on at sunset and off at sunrise</figcaption></figure>



<h2 class="wp-block-heading">Where do I get the data for sunrise / sunset?</h2>



<p>Of course, we need the data for sunrise and sunset — otherwise the project is nonsense. I get the data via <a href="https://sunrise-sunset.org/api">sunrise-sunset.org</a>. For the city of London, for example, the relevant URL request looks like this:</p>



<pre class="wp-block-code"><code class="">https://api.sunrise-sunset.org/json?lat=51.517576&amp;lng=-0.07978&amp;formatted=0</code></pre>



<p>You must specify latitude (<strong>lat</strong>) and longitude (<strong>lng</strong>). The request above will give you these data:</p>



<figure class="wp-block-image size-large"><img decoding="async" loading="lazy" width="575" height="280" src="https://vpn-expert.info/wp-content/uploads/2020/02/sunrise-sunset-london.jpg" alt="Sunrise, dawn and sunset for London" class="wp-image-297" srcset="https://vpn-expert.info/wp-content/uploads/2020/02/sunrise-sunset-london.jpg 575w, https://vpn-expert.info/wp-content/uploads/2020/02/sunrise-sunset-london-300x146.jpg 300w" sizes="(max-width: 575px) 100vw, 575px" /><figcaption>Sunrise, dawn and sunset for London</figcaption></figure>



<p>You get the following information:</p>



<ul><li><strong>Sunrise</strong></li><li><strong>Sunset</strong></li><li><strong>Solar Noon</strong></li><li><strong>Day length</strong> (in seconds)</li><li><strong>Civil twilight</strong> — reading outside is still possible without problems</li><li><strong>Nautical twilight</strong></li><li><strong>Astronomical twilight</strong></li></ul>



<p>It is important <strong>that all times are given in UTC</strong>. The time zone is not considered, but I don&#8217;t care because I simply calculate everything in UTC. I just don&#8217;t change the time zone of the Pi and it will work. But you could also add or subtract with x hours (maybe with <em>timedelta(hours=x)</em> ) or define the time zone.</p>



<p>My script works with sunrise and sunset. In many cases, the civil twilight would probably be more suitable. But here you can experiment yourself.</p>



<h2 class="wp-block-heading">My script (Python 3) looks (currently) like this</h2>



<p>I let the <em>while</em> loop run every minute, hence the <em>sleep(60)</em> at the end. Since I don&#8217;t query the REST API from sunrise-sunset.org on every pass, I could run it more often. But the night light does not need to switch spot on the second.</p>



<p>The last two lines simply check if the string from the current date is different from the one from the URL query. If so, the program simply fetches new data. So, ideally the REST API of the website is queried only once a day.</p>



<p>Maybe checking the <em>status</em> would still be useful. If I get something other than OK, then jump into a loop, wait x seconds and query again.</p>



<p>For the relays this is similar. If they already have the desired status, the script simply jumps one step further.</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import requests
import json
from datetime import datetime, time, timedelta
from time import sleep
import pifacedigitalio as p # you only need it if you use PiFace Digital
pifacedigital = p.PiFaceDigital()
url = 'https://api.sunrise-sunset.org/json?lat=51.517576&amp;lng=-0.07978&amp;formatted=0' # URL, change lat and lng
r = requests.get(url) # query data

while True:
    d = datetime.now()
    today_date = d.date() # date today
    time_now = d.time() # time now
    data = json.loads(r.content)
    sunrise = data['results']['sunrise']
    sunset = data['results']['sunset']
    sunrise_time = time(int(sunrise[11:13]), int(sunrise[14:16])) # Change sunrise in time format
    sunset_time = time(int(sunset[11:13]), int(sunset[14:16])) # Change sunset into time format

    if time_now > sunrise_time and time_now &lt; sunset_time: # In between sunrise and sunset

        if pifacedigital.output_pins[1].value == 1: # If relay on, turn it off
            pifacedigital.output_pins[1].turn_off() # turn it off
    else:
        if pifacedigital.output_pins[1].value != 1: # If relay off, turn it on
            pifacedigital.output_pins[1].turn_on() # turn on

    sleep(60)

    if str(sunrise[0:10]) != str(today_date): # different date? Get new data
        r = requests.get(url)</code></pre>



<p>I saved the script as <em>sunrise-sunset.py</em>, made it executable</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">chmod +x sunrise-sunset.py</code></pre>



<p>and started it on the Raspberry Pi (it runs in the background)</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">nohup python3 ./sunrise-sunset.py &amp;</code></pre>



<p>You can end it by first finding out the PID (this gives you a number):</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">pgrep -f sunrise</code></pre>



<p>or you do that</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">ps -ef | grep "sunrise" | awk '{print $2}'</code></pre>



<p>If you have the correct number you <em>kill</em> the program:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">kill &lt;given PID / number></code></pre>



<p>That works as well</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">pkill -f sunrise</code></pre>



<p>In my case, this should not cause any problems because there is only one program with the keyword <em>sunrise</em> running.</p>



<p>Alternatively, you could call the program in a screen session and abort it with Ctrl + C if necessary.</p>



<h3 class="wp-block-heading">Improving the script</h3>



<p>The program is not perfect, I know that. For example, it aborts if the URL cannot be reached due to network errors, maintenance work and so on. I can catch the error with <em>except requests.exceptions.ConnectionError</em>. I will add a check if the received data is ok. If there is a network error, just wait x seconds and try again. The URL query would be better in a function I can use.</p>



<p>Furthermore, I would not have to set sunrise and sunset every time the while loop is run. Also here once a day is enough. If you create a function to query the URL, then setting the times would make sense here. I will refine my script while it is running.</p>



<h3 class="wp-block-heading">Change it as you like</h3>



<p>Of course, you can also use <em>sunrise_time</em> and <em>sunset_time</em> to define a time span yourself in which something should happen. Maybe you listen to the radio between 1 and 2 pm. Or take a buzzer and let yourself be woken up for 5 minutes 30 minutes after sunrise.</p>



<p>I&#8217;ve been running this for a few days now and it works. It does what it is supposed to do. I am open for suggestions for improvement, because I don&#8217;t program that much.</p>



<p>It would also have been possible, I just query the sunrise, switch off the relay, let the program sleep for the length of the daylight and then switch it on again. But I prefer my version, because I can vary more easily with the twilight.</p>



<p>Do you have a Sense HAT? Make a <a href="https://vpn-expert.info/bitcoin-price-tracker-with-raspberry-pi-sense-hat-and-python/">Bitcoin ticker &#8211; it&#8217;s easy</a>!</p>



<h2 class="wp-block-heading">Script with gpiozero</h2>



<p>For completeness, here is the script of how it might work with <a href="https://gpiozero.readthedocs.io/en/stable/">gpiozero</a> — GPIO(17) is switched.</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import requests
import json
from datetime import datetime, time, timedelta
from time import sleep
from gpiozero import LED

url = 'https://api.sunrise-sunset.org/json?lat=51.517576&amp;lng=-0.07978&amp;formatted=0'
r = requests.get(url)

led = LED(17)

while True:

    d = datetime.now()
    today_date = d.date()
    time_now = d.time()

    data = json.loads(r.content)
    sunrise = data['results']['sunrise']
    sunset = data['results']['sunset']
    sunrise_time = time(int(sunrise[11:13]), int(sunrise[14:16]))
    sunset_time = time(int(sunset[11:13]), int(sunset[14:16]))

    if time_now > sunrise_time and time_now &lt; sunset_time:
        if led.is_active:
            led.off()
    else:
        if not led.is_active:
            led.on()

    sleep(60)

    if str(sunrise[0:10]) != str(today_date):
        r = requests.get(url)</code></pre>



<p>You only have to change the script in a few places and can use it to switch the pins on your Raspberry Pi at sunrise and sunset.</p>



<p><em>Gpiozero</em> is preinstalled on Raspbian, but not on Raspbian Lite. If you run your Raspberry Pi headless with the Lite version, you may need to install gpiozero first:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo apt install python3-gpiozero</code></pre>



<p>Now it works. It&#8217;s amazing what you can do with a Raspberry Pi. Do you need more ideas? Why not build a <a href="https://vpn-expert.info/vpn-router-raspberry-pi-raspap-and-nordvpn-wi-fi-hotspot-access-point/">VPN router</a>.</p>
<p>The post <a rel="nofollow" href="https://vpn-expert.info/sunrise-sunset-switch-raspberry-pi-with-python/">Sunrise / Sunset switch Raspberry Pi with Python</a> appeared first on <a rel="nofollow" href="https://vpn-expert.info">VPN Expert</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://vpn-expert.info/sunrise-sunset-switch-raspberry-pi-with-python/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
	</channel>
</rss>
