The Magic starts at 3:30AM... because at 3:30AM every day, a cron task runs on the chicken coop computer to determine when the coop door should open and close later that day. For most of my weather needs I had been using the http://wunderground.com API, but for some reason, they don't offer access to twilight data through the API and I didn't want to write a webpage scraper to harvest the data from their website.
Fortunately for me, hamweather.com has a wonderful API accessible weather service with great documentation, all at a very reasonable price (free, if making less than 750 API calls per day).
For this piece of the project, I decided to use civil twilight as the opening and closing times. Then it was just a matter of reading the hamweather API documentation for sun and moon data and then hacking together some code. Since the majority of the code is written in Python, I opted to use python for this script.
Enter the Python
client_id = "MY_CLIENT_ID"
client_secret = "MY_CLIENT_SECRET"
url="http://api.aerisapi.com/sunmoon/MY_CLOSEST_TOWN?client_id=%s&client_secret=%s" % (client_id, client_secret)
script_dir = os.path.dirname( os.path.realpath(__file__) )
data_file = os.path.join(script_dir, 'sunmoon.json')
open_script = os.path.join(script_dir,"open_door.sh")
close_script = os.path.join(script_dir,"close_door.sh")
#read the data from the url and write it to a file
response = urllib.urlopen(url)
data = response.read()
f = open(data_file, "w")
#something failed, open the old data file
f = open(data_file,'r')
data = f.read()
#load the json into an object
json_object = json.loads(data)
#get the twilight from the json object
twilight = json_object['response']['sun']['twilight']
#get the twilight start and end
civilbegin = twilight['civilBegin']
civilend = twilight['civilEnd']
#format the start and end times in Hour:Minute format
twilight_start = time.strftime("%H:%M", time.localtime(civilbegin))
twilight_end = time.strftime("%H:%M",time.localtime(civilend))
#create commands based on the times
open_cmd = "at -f "+open_script +' '+twilight_start
close_cmd = "at -f "+close_script +' '+ twilight_end
#run the commands as a subprocess
During the event loop of my door controller, a file is checked to see if the door should open or close, and the door behaves accordingly. This twilight fetching script will determine when to open and close the door, and submits a command to at, which then handles the timing for running the open or close script.
The chickens will be going into their new home next weekend, and the close time will probably need to be adjusted, but that just means I need to hang out in the hammock at sunset/twilight and see if all the chickens go in the coop before the door closes.
Now quit reading, and go make something that can only be tested by relaxing in a hammock at sunset. :)