Created
December 27, 2018 07:00
-
-
Save dulldusk/3a6c3c31c75c6aed018ca26316049b37 to your computer and use it in GitHub Desktop.
Script created for use on MotionEyeOs, to change configurations for day and night. https://github.com/ccrisan/motioneyeos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# Script created for use on MotionEyeOs, to change configurations for day and night | |
# https://github.com/ccrisan/motioneyeos | |
# Crontab execute every 5 min | |
# 02,07,12,17,22,27,32,37,42,47,52,57 * * * * /usr/bin/python /data/dayornight.py >> /var/log/dayornight.log | |
from math import floor, ceil, pi, atan, tan, sin, asin, cos, acos | |
from datetime import date, datetime, timedelta | |
from time import mktime | |
import sys | |
import time | |
import os | |
import os.path | |
import shutil | |
import subprocess | |
def get_sunrise(lat, lng, dt, utc_offset): | |
return sun_rise_set_calc(lat, lng, dt, utc_offset, True) | |
def get_sunset(lat, lng, dt, utc_offset): | |
return sun_rise_set_calc(lat, lng, dt, utc_offset, False) | |
def sun_rise_set_calc(lat, lng, dt, utc_offset, get_sunrise): | |
# by Ankit Haldar | |
# https://github.com/ankithaldar | |
dayOfYear = (floor(275*dt.month/9) - (floor((dt.month+9)/12) * (1+floor((dt.year-4*floor(dt.year/4)+2)/3))) + dt.day - 30) | |
d2r = pi/180 | |
#convert the longitude to hour value and calculate an approximate time | |
lngH = lng/15 | |
t = dayOfYear + ((6 if get_sunrise else 18) - lngH)/24 | |
#m => Sun's mean anomaly | |
m = (0.9856 * t) - 3.289 | |
#l => Sun's true longitude | |
l = m + (1.916 * sin(m*d2r)) + (0.020 * sin(2 * m*d2r)) + 282.634 | |
l += -360 if l > 360 else 360 if l < 360 else 0 | |
#ra = Sun's right ascension (right ascension value needs to be in the same quadrant as L) | |
ra = atan(0.91764 * tan(l*d2r))/d2r | |
ra += -360 if ra > 360 else 360 if ra < 360 else 0 | |
ra += (floor(l/90) - floor(ra/90)) * 90 | |
ra /= 15 | |
#sinDec, cosDec => Sine and Cosine of Sun's declination | |
sinDec = 0.39782 * sin(l*d2r) | |
cosDec = cos(asin(sinDec)) | |
#Sun's local hour angle | |
cosH = (cos(90.8333333333333*d2r) - (sinDec * sin(lat*d2r))) / (cosDec * cos(lat*d2r)) | |
if get_sunrise and cosH > 1: print('the sun never rises on this location (on the specified date)'); sys.exit() | |
elif not get_sunrise and cosH < -1: print('the sun never sets on this location (on the specified date)'); sys.exit() | |
h = ((360 - (acos(cosH)/d2r)) if get_sunrise else (acos(cosH)/d2r))/15 | |
#Local mean time of rising/setting | |
meanT = h + ra - (0.06571 * t) - 6.622 | |
#adjust back to local standard time | |
local = meanT - lngH + utc_offset | |
local += 24 if local < 0 else -24 if local > 24 else 0 | |
local *= 3600 | |
return(local) | |
def restart_MotionEye(): | |
os.system("/etc/init.d/S84streameye restart") | |
os.system("/etc/init.d/S85motioneye restart") | |
def file_get_contents(path): | |
if not os.path.isfile(path): return "" | |
f = open(path, "r") | |
data = f.read() | |
f.close() | |
return data | |
def file_put_contents(path, data): | |
f = open(path, "w") | |
f.write(data) | |
f.close() | |
if __name__ == '__main__': | |
debug = False | |
# Get yout lat/lng from http://maps.google.com | |
lat = -22.6823 | |
lng = -59.1343 | |
# Fine adjust: Set the time it takes after the sunrise or sunset, for light change to occur. | |
day_lightin_delay = 20 #min | |
day_lightout_delay = 20 #min | |
# For Telegram config change notifications | |
telegram_bot_api_token = '' | |
telegram_chat_id = '' | |
logStr = '' | |
ts_now = time.time() | |
utc_offset = ((datetime.fromtimestamp(ts_now) - datetime.utcfromtimestamp(ts_now)).total_seconds())/60/60 # includes daylight saving time | |
#utc_offset = (-time.timezone)/60/60 # does not include daylight saving time | |
dt_now = datetime.now() | |
day_sunrise_secs = get_sunrise(lat, lng, dt_now, utc_offset) | |
day_sunset_secs = get_sunset(lat, lng, dt_now, utc_offset) | |
ts_day_start = mktime(datetime.strptime(datetime.fromtimestamp(ts_now).strftime("%Y-%m-%d 00:00"),"%Y-%m-%d %H:%M").timetuple()) | |
ts_day_sunrise = ts_day_start + day_sunrise_secs | |
ts_day_sunset = ts_day_start + day_sunset_secs | |
td_day_hours = timedelta(seconds = (ts_day_sunset - ts_day_sunrise)) | |
ts_day_lightin = ts_day_sunrise + (day_lightin_delay * 60) | |
ts_day_lightout = ts_day_sunset + (day_lightout_delay * 60) | |
lastStateFile = '/var/spool/dayornightState' | |
lastState = file_get_contents(lastStateFile) | |
currentState = '' | |
if (ts_now >= ts_day_lightin and ts_now <= ts_day_lightout): | |
currentState = 'day' | |
else: | |
currentState = 'night' | |
logStr = datetime.fromtimestamp(ts_now).strftime("%Y-%m-%d %H:%M") | |
logStr += ' (daylight from '+datetime.fromtimestamp(ts_day_lightin).strftime("%H:%M")+' to '+datetime.fromtimestamp(ts_day_lightout).strftime("%H:%M")+') = ' | |
if lastState != currentState: | |
logStr += lastState+' > '+currentState | |
else: | |
logStr += currentState | |
if (debug): | |
print('-------------------------------\n{}\n-------------------------------'.format(datetime.fromtimestamp(ts_now).strftime("%Y-%m-%d %H:%M"))) | |
print('lat: {} lng: {}'.format(lat,lng)) | |
print('utc_offset with daylight saving time: {}'.format(utc_offset)) | |
print('day_sunrise: {}'.format(datetime.fromtimestamp(ts_day_sunrise).strftime("%H:%M"))) | |
print('day_sunset: {}'.format(datetime.fromtimestamp(ts_day_sunset).strftime("%H:%M"))) | |
print('hours of day: {:02d}:{:02d}'.format(td_day_hours.seconds/3600,td_day_hours.seconds%3600/60)) | |
print('day_lightin: {}'.format(datetime.fromtimestamp(ts_day_lightin).strftime("%H:%M"))) | |
print('day_lightout: {}'.format(datetime.fromtimestamp(ts_day_lightout).strftime("%H:%M"))) | |
else: | |
print(logStr) | |
if lastState != currentState: | |
if (telegram_bot_api_token != '' and telegram_chat_id != ''): | |
telegram_cmd = 'curl -s -X POST "https://api.telegram.org/bot'+telegram_bot_api_token+'/sendMessage" -F chat_id='+telegram_chat_id+' -F text="'+logStr+'"' | |
telegram_cmd_subprocess = subprocess.Popen(telegram_cmd, shell=True, stdout=subprocess.PIPE) | |
(stdoutdata, stderrdata) = telegram_cmd_subprocess.communicate() | |
if (debug): | |
print(stdoutdata) | |
if os.path.isfile("/data/etc/thread-1.conf"): | |
if (lastState != ''): | |
shutil.copyfile("/data/etc/thread-1.conf", "/data/etc-"+lastState+"/thread-1.conf") | |
shutil.copyfile("/data/etc-"+currentState+"/thread-1.conf", "/data/etc/thread-1.conf") | |
print('updated config files, restarting motioneye...') | |
restart_MotionEye() | |
file_put_contents(lastStateFile, currentState) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment