I’d love to see your code. I just use Sun elevation (also from astro). I’d like to also do it based on light level, e.g. when it’s very overcast / raining during the day, switch it to night profile too. I haven’t figured out how to determine the light level. I’d like to do it based on the camera / camera feed itself, and not have to use extra external lux sensors.
Here’s my current code, written in JRuby OpenHAB Rules System
require 'openhab'
require 'net/http'
require 'net/http/digest_auth'
SUN_ELEVATION_THRESHOLD = 5 # Threshold for switching camera profile to day/night
def http_digest_get(url, user:, pass:)
digest_auth = Net::HTTP::DigestAuth.new
uri = URI(url)
uri.user = CGI.escape(user)
uri.password = CGI.escape(pass)
h = Net::HTTP.new uri.host, uri.port
req = Net::HTTP::Get.new uri.request_uri
res = h.request req
# res is a 401 response with a WWW-Authenticate header
auth = digest_auth.auth_header uri, res['www-authenticate'], 'GET'
# create a new request with the Authorization header
req = Net::HTTP::Get.new uri.request_uri
req.add_field 'Authorization', auth
# re-issue request with Authorization
h.request req
end
def dahua_set_profile(ip, profile, user, pass)
profile = { day: '0', night: '1' }[profile]
http_digest_get("http://#{ip}/cgi-bin/configManager.cgi?action=setConfig&VideoInMode[0].Config[0]=#{profile}",
user: user, pass: pass)
end
rule 'Dahua: Profile switch to day' do
changed Sun_Elevation
on_start
run do |event|
if Sun_Elevation > SUN_ELEVATION_THRESHOLD && (event.nil? || event.was <= SUN_ELEVATION_THRESHOLD)
profile = :day
elsif Sun_Elevation < SUN_ELEVATION_THRESHOLD && (event.nil? || event.was >= SUN_ELEVATION_THRESHOLD)
profile = :night
else
next
end
logger.info("DAHUA PROFILE switched to: #{profile}")
dahua_set_profile(CAMERA_IP['Street'], profile, CAM_USER, CAM_PASS)
end
end