Skip to content

Instantly share code, notes, and snippets.

@reid
Created July 26, 2023 22:11
Show Gist options
  • Save reid/8df77d68806314085411d10f33828943 to your computer and use it in GitHub Desktop.
Save reid/8df77d68806314085411d10f33828943 to your computer and use it in GitHub Desktop.
Respond to successful UniFi Access door entry from NFC or PIN codes using Pyscript and Home Assistant
'''
Copyright 2023 Reid Burke <reid@reidburke.com>
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
import aiohttp
import re
from datetime import datetime, timezone
username = pyscript.app_config['username']
password = pyscript.app_config['password']
async def login(session, base_url) -> str:
async with session.request("post", f"{base_url}/api/auth/login", json={'username': username, 'password': password}, ssl=False) as response:
return response.headers
headers = {
'content-type': 'application/json',
'accept': 'application/json'
}
@state_trigger("binary_sensor.backyard_gate == 'on' and alarm_control_panel.security_panel != 'disarmed'")
async def verify_unifi_access():
base_url = f"https://{pyscript.app_config['host']}"
async with aiohttp.ClientSession(headers=headers) as session:
arh = login(session, base_url)
setCookie = arh['Set-Cookie']
regex = re.compile("TOKEN=(.+); path")
cookies = {
'TOKEN': regex.match(setCookie).group(1)
}
hdr = {
'X-CSRF-Token': arh['X-CSRF-Token']
}
payload = {
'filter': 'event.type eq "access.door.unlock" and target.id eq "door_entry_method" and target.display_name eq "entry" and event.result eq "ACCESS" and (authentication.credential_provider eq "NFC" or authentication.credential_provider eq "PIN_CODE")',
'show_avatar': False
}
async with session.post(f"{base_url}/proxy/access/ulp-go/api/logs/search?page_num=1&page_size=1", json=payload, ssl=False, cookies=cookies, headers=hdr) as response:
log.info(response.text())
json = response.json()
for hits in json['data']['hits']:
access_timestamp = hits['@timestamp']
access_time = datetime.fromisoformat(access_timestamp).timestamp()
now = datetime.now().timestamp()
elapsed_time = now - access_time
log.info(elapsed_time)
if elapsed_time < 10:
log.info('OK')
alarm_control_panel.alarm_disarm(entity_id='alarm_control_panel.security_panel')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment