Skip to content

Instantly share code, notes, and snippets.

@ccutrer
Last active July 30, 2019 17:38
Show Gist options
  • Save ccutrer/8aaadb3c10fbcea8488c71281ee9197a to your computer and use it in GitHub Desktop.
Save ccutrer/8aaadb3c10fbcea8488c71281ee9197a to your computer and use it in GitHub Desktop.
DoorBird motion and ring notifications
Contact Doorbird_Contact "Doorbell" { expire="30s" }
#!/usr/bin/env ruby
require 'net/http'
require 'openssl'
require 'uri'
doorbird_host = "192.168.85.143"
openhab_host = "http://127.0.0.1:8080/"
item_mapping = {
"doorbell" => "Doorbird_Contact"
}
VALUE_MAPPING = {
"L" => "CLOSED",
"H" => "OPEN"
}
doorbird_uri = URI.parse("https://#{doorbird_host}/bha-api/monitor.cgi?ring=doorbell,motionsensor")
doorbird_http = Net::HTTP.new(doorbird_uri.host, doorbird_uri.port)
doorbird_http.use_ssl = true
doorbird_http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(doorbird_uri.request_uri)
request.basic_auth("user", "password")
doorbird_http.request(request) do |response|
content_type_header = response['Content-Type']
content_type, content_type_params_string = content_type_header.split('; ', 2)
raise "Unknown response content type #{content_type}" unless content_type == "multipart/x-mixed-replace"
content_type_params = content_type_params_string.split(",").map { |x| x.split('=', 2) }.to_h
boundary = content_type_params['boundary']
raise "No boundary" unless boundary
response.read_body do |chunk|
chunk.split("#{boundary}\r\n").each do |line|
next if line.empty?
io = Net::BufferedIO.new(StringIO.new("HTTP 200 OK\r\n#{line}"))
sub_response = Net::HTTPResponse.read_new(io)
body = sub_response.reading_body(io, true) { sub_response.body }
attribute, value = body.strip.split(":", 2)
next unless VALUE_MAPPING.key?(value)
item = item_mapping[attribute]
next unless item
openhab_uri = URI.parse("#{openhab_host}rest/items/#{item}/state")
puts "doing request to #{openhab_uri}"
openhab_http = Net::HTTP.new(openhab_uri.host, openhab_uri.port)
openhab_request = Net::HTTP::Put.new(openhab_uri.request_uri)
openhab_request.body = VALUE_MAPPING[value]
openhab_request.content_type = 'text/plain'
openhab_response = openhab_http.request(openhab_request)
puts openhab_response.code
puts openhab_response['Location']
end
end
end
[Unit]
Description=Monitor Doorbird
[Service]
User=cody
ExecStart=/var/lib/openhab2/monitor_doorbird.rb
Restart=always
RestartSec=3s
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment