Files
rsmsn_blog/public/posts/birdnet_homeassistant.html

510 lines
58 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en" dir="auto">
<head><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="robots" content="index, follow">
<title>Creating a BirdNetPi Dashboard in HomeAssistant - Part 1 | Norm-working Packets 💾</title>
<meta name="keywords" content="homeassistant, python, diy">
<meta name="description" content="Learn how to take BirdNET-Pi Detections to create and display entities in HomeAssistant.">
<meta name="author" content="Me">
<link rel="canonical" href="../posts/birdnet_homeassistant.html">
<link crossorigin="anonymous" href="../assets/css/stylesheet.5cfc680b1eeaeef9efbced92d46c2a9e876b72ee14fba85846afc4cff9e6e6f8.css" integrity="sha256-XPxoCx7q7vnvvO2S1Gwqnodrcu4U&#43;6hYRq/Ez/nm5vg=" rel="preload stylesheet" as="style">
<script defer crossorigin="anonymous" src="../assets/js/highlight.f413e19d0714851f6474e7ee9632408e58ac146fbdbe62747134bea2fa3415e0.js" integrity="sha256-9BPhnQcUhR9kdOfuljJAjlisFG&#43;9vmJ0cTS&#43;ovo0FeA="
onload="hljs.initHighlightingOnLoad();"></script>
<link rel="icon" href="../favicon.ico">
<link rel="icon" type="image/png" sizes="16x16" href="../favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="../rsmsncircles.ico">
<link rel="apple-touch-icon" href="../apple-touch-icon.png">
<link rel="mask-icon" href="../safari-pinned-tab.svg">
<meta name="theme-color" content="#2e2e33">
<meta name="msapplication-TileColor" content="#2e2e33">
<noscript>
<style>
#theme-toggle,
.top-link {
display: none;
}
</style>
</noscript>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-X8VR5M0K20"></script>
<script>
var doNotTrack = false;
if (!doNotTrack) {
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-X8VR5M0K20', { 'anonymize_ip': false });
}
</script>
<meta property="og:title" content="Creating a BirdNetPi Dashboard in HomeAssistant - Part 1" />
<meta property="og:description" content="Learn how to take BirdNET-Pi Detections to create and display entities in HomeAssistant." />
<meta property="og:type" content="article" />
<meta property="og:url" content="/posts/birdnet_homeassistant.html" />
<meta property="og:image" content="/birdnet-homeassistant.png" /><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2023-09-25T12:51:55-04:00" />
<meta property="article:modified_time" content="2023-09-25T12:51:55-04:00" /><meta property="og:site_name" content="Norm-working Packets" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="/birdnet-homeassistant.png" />
<meta name="twitter:title" content="Creating a BirdNetPi Dashboard in HomeAssistant - Part 1"/>
<meta name="twitter:description" content="Learn how to take BirdNET-Pi Detections to create and display entities in HomeAssistant."/>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{
"@type": "ListItem",
"position": 1 ,
"name": "Creating a BirdNetPi Dashboard in HomeAssistant - Part 1",
"item": "/posts/birdnet_homeassistant.html"
}
]
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": "Creating a BirdNetPi Dashboard in HomeAssistant - Part 1",
"name": "Creating a BirdNetPi Dashboard in HomeAssistant - Part 1",
"description": "Learn how to take BirdNET-Pi Detections to create and display entities in HomeAssistant.",
"keywords": [
"homeassistant", "python", "diy"
],
"articleBody": "This is Part One of a Two Part Series. You can find Part Two, here.\nWhat you will need BirdNET-Pi HomeAssistant AppDaemon MQTT Broker (I use Mosquitto) Background In early 2023, at the height of the Raspberry Pi shortage I felt like a king with an extra Rpi laying around, not being used. Im a big fan of any sort of passive intake of information and had been looking around for various citizen science-style projects that can capture information from the world around me. Since Im already running an ADS-B antenna with Flight Aware, I figured this next project would deal with radio waves/transmissions. Instead, to my amazement, I discovered BirdNET-Pi!\nWhat is BirdNET-Pi? In case you didnt click the links above, BirdNET-Pi is an app built specifically made for Rapsberry Pi devices, that builds off the BirdNET Framework. BirdNET is one of the most advanced acoustic monitoring tools available for passively monitoring bird diversity populations. Where BirdNET-Pi takes it to the next level is the ability to setup an SBC - hopefully enclosed in a waterproof space! - and monitor birds in your local environment over time.\nI think this project is beyond neat. It runs a bit slow on a Raspberry Pi 3, but overall it runs smoothly. I was even able to contribute a PR to the project in April when I noticed a bug in the platform after a hard reset of my Pi.\nBirdNET-PI Notification Setup - MQTT Once you have BirdNET-Pi up and running, youll need to head over to the Settings and setup the correct MQTT payloads. Here are the possible variables you can pass in an MQTT payload:\n$sciname: Scientific Name $comname: Common Name $confidence: Confidence Score $confidencepct: Confidence Score as a percentage (eg. 0.91 =\u003e 91) $listenurl: A link to the detection $date: Date $time: Time $week: Week $latitude: Latitude $longitude: Longitude $cutoff: Minimum Confidence set in “Advanced Settings” $sens: Sigmoid Sensitivity set in “Advanced Settings” $overlap: Overlap set in “Advanced Settings” $flickrimage: A preview image of the detected species from Flickr. Set your API key below. For our purposes, we will only be using $comname, $sciname, $date, $time, $week, and $confidence. However, this entire process is extremely customizable, which youll learn more about in the AppDaemon section. Please expand on it and include information that is pertinent to your own uses.\nHere is how Ive setup my MQTT payload from BirdNET-Pi Settings:\nHere it is in text form:\nNotification Title: $comname, Notification Body: $sciname, $date, $time, $week, $confidence [ ] Notify each new infrequent species detection (\u003c 5 visits per week) [ ] Notify each new species first detection of the day [X] Notify each new detection [X] Send weekly report Minimum time between notifications of the same species (sec): 5 To test my MQTT notifications, I use the iOS client “MQTTool”. After signing up, head to “Subscribe” and type birdnet as the topic and then click Subscribe. If everything is setup correctly and there are birds being recorded by the BirdNET-Pis microphone, you should start seeing those detections in the MQTTool app. If so, fantastic news! Lets move onto AppDaemon.\nAppDaemon Script Now that we have the Pi communicating via MQTT, its time to get that information into HomeAssistant. Ive shared the full script at the bottom of this page, but lets jump into each section. This is not a full tutorial of how to use AppDaemon, but it may help fill in any knowledge gaps with the system.\nImports First, were going to import time and requests. Were going to use time as a backup to the $time component in the payload. This can be helpful to see if there delays, or if BirdNET-Pi stopped detecting. Were then going to use requests to pull from Wikipedias API and grab a description for our HomeAssistant Dashboard.\nClass Definition To start any AppDaemon app, you need to include a Class that is defined in the apps.yaml file. This is also where we initialize and define the various items that will be used in the remainder of the script.\nclass birdnet(adbase.ADBase): def initialize(self): self.hassapi = self.get_plugin_api(\"HASS\") self.adapi = self.get_ad_api() self.mqttapi = self.get_plugin_api(\"MQTT\") self.birdnet_mqtt = \"birdnet\" self.mqttapi.listen_event( self.birdnet_message, \"MQTT_MESSAGE\", topic=self.birdnet_mqtt ) For this script, we need to use a lot of the AppDaemon APIs across more than just HomeAssistant, so were going to be using ADBase. By using that, we can initialize the various APIs, which we do in the next 3 lines. In these 3 lines we need to get access to HomeAssistants APIs, AppDaemons APIs, and MQTT APIs - the first and third items are plugins of AppDaemon, and AppDaemon is… well… AppDaemon! Here are a few reference docs:\nMQTT AppDaemon API HomeAssistant AppDaemon API AppDaemon API These will indispensable to you as you leverage AppDaemon and expand this little script.\nOnce we have access to that, we need to setup the main topic for MQTT from BirdNET-Pi and finally, what event we are listening for that will trigger the functions in the rest of the script. self.birdnet_mqtt = \"birdnet\" is the definition for the MQTT topic. Lets breakdown the last line of the class.\nHeres a breakdown of each of the items in that last line. You can find the official documentation here.\nself.mqttapi.listen_event - this is what we use in AppDaemon to listen for an MQTT event in order to trigger a function. self.birdnet_message - the name of the function youd like to trigger \"MQTT_MESSAGE\" - The default event in AppDaemons MQTT API plugin. This is used because MQTT doesnt keep a state in this plugin. topic=self.birdnet_mqtt - The topic that will be received to trigger the function. Defined on the previous line. In other words, what we are telling AppDaemon is the following: “When AppDaemons MQTT API plugin receives a message with the topic of birdnet, run the function birdnet_message.”\nbirdnet_message Function Part 1: Variables Management Now we get into our first function of the script. The first portion of this script is splitting up the payload that we defined from the BirdNET-Pi UI into individual variables that we can better manage later on. If you test this script out by adding print() statements at various points, youll notice that the payload is received with the following json formatting:\n{ \"payload\": { \"data\": \"data\" } } As such, we need to look inside the payload to begin grabbing the data. The pre_split variable is now just looking at the data inside the payload and the rest of the variables take all the date into the payload, split it by the comma, and then grab the string by their index. If you remember what we did above above, youll see that we have the various BirdNET information at each of the indexes in the AppDaemon script - 0 through 5.\nPart 2: Re-Publishing MQTT Payloads This next section is shooting all the variables we just defined back via MQTT. The reason why we do it this way is because we need HomeAssistant to grab each of these variables as individual sensors. BirdNET doesnt give us that capability - its a single message with all the information in one. [Here is the documentation from AppDaemon](## BirdNET-PI Notification Setup - MQTT ) on mqtt_publish. Later on, Ill show you how to ensure that HomeAssistant takes those topic payloads and adds them as entities in your HA setup.\nPart 3: Wikipedia Sensor The next eight lines are a fairly straightforward API call to Wikipedia. We start out by passing the science_name into the URL. The rest of the flags that we are passing into the URL comes from Wikipedias Docs. url = f\"https://en.wikipedia.org/w/api.php?format=json\u0026action=query\u0026prop=extracts\u0026exintro\u0026explaintext\u0026redirects=1\u0026titles={science_name}\"\nOnce thats done we call it with response.get(url) and format it with response.json(). Wikipedia returns the json payload with the top level of query (which was our action in the url ;) ), and were looking for the value within that query.\nAll thats left is to take that query value and push it to HomeAssistant! We can do that with the self.hassapi.set_state function. Within the parenthesis we define the name of the sensor (sensor.birdnet_wiki), what its state should be (on), and any attributes associated with the entity. Since we cant assign a long description to the basic status of the entity, were adding an attribute with the key of description and the value will be the wikipedia description garnered from the API call.\nurl = f\"https://en.wikipedia.org/w/api.php?format=json\u0026action=query\u0026prop=extracts\u0026exintro\u0026explaintext\u0026redirects=1\u0026titles={science_name}\" response = requests.get(url) response = response.json() for value in response['query']['pages']: wiki_desc = response['query']['pages'][value]['extract'] self.hassapi.set_state(\"sensor.birdnet_wiki\", state='on', attributes = {\"description\": wiki_desc}) Part 4: Generate Picture for Detection (Optional) This part is optional but I noticed that BirdNET-Pi was already grabbing a Flickr Picture for its front end, so I took the code from the BirdNET code base and adjusted it a bit for my needs. This will work very similarly to the Wikipedia API call, the main difference here being that you need an API key for Flickr. You can find more information here.\nGiven Flickrs fairly robust API, by passing in the detected birds common name, we get amazing results from the community of various pictures of the same species of bird. Ever since Ive set this up, Ive not seen a mislabeled picture in my dashboard!\nThe most confusion portion of this section is the image_url as youll notice a bunch of data[\"value\"] strings at various portions of the URL. The short answer to this is in the previous line with the data variable. A successful query has Flickr returning a large payload of information. Were specifically using this Flickr API endpoint. While you can pass a lot of variables for your needs, if you scroll down, you can see that the example response contains multiple photos in a single response. Were passing per_page=5 to limit some of those response items. Left out of that response, though, is a one-stop-shop for a URL to that photo. Thankfully, Flickr can help us put together a URL from the data in the response.\nNote: Full Transparency that I only learned about this after reading through BirdNET-Pis code base. Full credit goes to mcguirepr89. For additional reference, here is Flickrs official page on construction photo image URLS\nWith this response, we now have the variables we need to construct the URL to actually render the image. Those variables are: Farm ID, Server ID, ID and Secret. I havent yet looked into why we need “farm” when the official documentation doesnt state anything about it.\nAlmost there! We now do the same as we did with the Wikipedia API response. We create a sensor in HomeAssistant! Were calling this sensor sensor.birdpic, ensuring the state=on, and giving it the attributes of the image_url as garnered from Flickr.\nheaders = {'User-Agent': 'Python_Flickr/1.0'} flickr_api = \"enter_your_api_key\" flickr_url = f\"https://www.flickr.com/services/rest/?method=flickr.photos.search\u0026api_key={flickr_api}\u0026text={common_name} bird\u0026sort=relevance\u0026per_page=5\u0026media=photos\u0026format=json\u0026nojsoncallback=1\" flickr_resp = requests.get(url=flickr_url, headers=headers) data = flickr_resp.json()[\"photos\"][\"photo\"][0] image_url = 'https://farm'+str(data[\"farm\"])+'.static.flickr.com/'+str(data[\"server\"])+'/'+str(data[\"id\"])+'_'+str(data[\"secret\"])+'_n.jpg' self.hassapi.set_state(\"sensor.birdpic\", state='on', attributes={\"image\": image_url}) In Part 2 of this article, well take a look at Home Assistant, see what these sensors look like, and create a rudimentary dashboard.\nBirdnet AppDaemon Script import time import requests class birdnet(adbase.ADBase): def initialize(self): self.hassapi = self.get_plugin_api(\"HASS\") self.adapi = self.get_ad_api() self.mqttapi = self.get_plugin_api(\"MQTT\") self.birdnet_mqtt = \"birdnet\" self.mqttapi.listen_event( self.birdnet_message, \"MQTT_MESSAGE\", topic=self.birdnet_mqtt ) def birdnet_message(self, event_name, data, kwargs): pre_split = data[\"payload\"] common_name = pre_split.split(',')[0].strip() science_name = pre_split.split(',')[1].strip() date_seen = pre_split.split(',')[2].strip() time_seen = pre_split.split(',')[3].strip() week_seen = pre_split.split(',')[4].strip() confidence = pre_split.split(',')[5].strip() # print(f\"A {common_name} was seen on {date_seen} at {time_seen}. Confidence is {confidence}.\") self.mqttapi.mqtt_publish(\"birdnet/sensors/common_name\", common_name) self.mqttapi.mqtt_publish(\"birdnet/sensors/science_name\", science_name) self.mqttapi.mqtt_publish(\"birdnet/sensors/time_seen\", time_seen) self.mqttapi.mqtt_publish(\"birdnet/sensors/date_seen\", date_seen) self.mqttapi.mqtt_publish(\"birdnet/sensors/confidence\", confidence) url = f\"https://en.wikipedia.org/w/api.php?format=json\u0026action=query\u0026prop=extracts\u0026exintro\u0026explaintext\u0026redirects=1\u0026titles={science_name}\" response = requests.get(url) response = response.json() for value in response['query']['pages']: wiki_desc = response['query']['pages'][value]['extract'] self.hassapi.set_state(\"sensor.birdnet_wiki\", state='on', attributes = {\"description\": wiki_desc}) headers = {'User-Agent': 'Python_Flickr/1.0'} flickr_api = \"enter_your_api_key\" flickr_url = f\"https://www.flickr.com/services/rest/?method=flickr.photos.search\u0026api_key={flickr_api}\u0026text={common_name} bird\u0026sort=relevance\u0026per_page=5\u0026media=photos\u0026format=json\u0026nojsoncallback=1\" flickr_resp = requests.get(url=flickr_url, headers=headers) data = flickr_resp.json()[\"photos\"][\"photo\"][0] image_url = 'https://farm'+str(data[\"farm\"])+'.static.flickr.com/'+str(data[\"server\"])+'/'+str(data[\"id\"])+'_'+str(data[\"secret\"])+'_n.jpg' self.hassapi.set_state(\"sensor.birdpic\", state='on', attributes={\"image\": image_url}) ",
"wordCount" : "1953",
"inLanguage": "en",
"image":"/birdnet-homeassistant.png","datePublished": "2023-09-25T12:51:55-04:00",
"dateModified": "2023-09-25T12:51:55-04:00",
"author":{
"@type": "Person",
"name": "Me"
},
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "/posts/birdnet_homeassistant.html"
},
"publisher": {
"@type": "Organization",
"name": "Norm-working Packets 💾",
"logo": {
"@type": "ImageObject",
"url": "/favicon.ico"
}
}
}
</script>
</head>
<body class=" dark" id="top">
<script>
if (localStorage.getItem("pref-theme") === "light") {
document.body.classList.remove('dark')
}
</script>
<header class="header">
<nav class="nav">
<div class="logo">
<a href="../" accesskey="h" title="Norm-working Packets 💾 (Alt + H)">Norm-working Packets 💾</a>
<div class="logo-switches">
<button id="theme-toggle" accesskey="t" title="(Alt + T)">
<svg id="moon" xmlns="http://www.w3.org/2000/svg" width="24" height="18" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
</svg>
<svg id="sun" xmlns="http://www.w3.org/2000/svg" width="24" height="18" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round">
<circle cx="12" cy="12" r="5"></circle>
<line x1="12" y1="1" x2="12" y2="3"></line>
<line x1="12" y1="21" x2="12" y2="23"></line>
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
<line x1="1" y1="12" x2="3" y2="12"></line>
<line x1="21" y1="12" x2="23" y2="12"></line>
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
</svg>
</button>
</div>
</div>
<ul id="menu">
</ul>
</nav>
</header>
<main class="main">
<article class="post-single">
<header class="post-header">
<div class="breadcrumbs"><a href="../">Home</a></div>
<h1 class="post-title">
Creating a BirdNetPi Dashboard in HomeAssistant - Part 1
</h1>
<div class="post-description">
Learn how to take BirdNET-Pi Detections to create and display entities in HomeAssistant.
</div>
<div class="post-meta"><span title='2023-09-25 12:51:55 -0400 EDT'>September 25, 2023</span>&nbsp;·&nbsp;10 min&nbsp;·&nbsp;1953 words&nbsp;·&nbsp;Me
</div>
</header> <div class="toc">
<details >
<summary accesskey="c" title="(Alt + C)">
<span class="details">Table of Contents</span>
</summary>
<div class="inner"><nav id="TableOfContents">
<ul>
<li><a href="#what-you-will-need">What you will need</a></li>
<li><a href="#background">Background</a></li>
<li><a href="#what-is-birdnet-pi">What is BirdNET-Pi?</a></li>
<li><a href="#birdnet-pi-notification-setup---mqtt">BirdNET-PI Notification Setup - MQTT</a></li>
<li><a href="#appdaemon-script">AppDaemon Script</a>
<ul>
<li><a href="#imports">Imports</a></li>
<li><a href="#class-definition">Class Definition</a></li>
<li><a href="#birdnet_message-function">birdnet_message Function</a></li>
</ul>
</li>
<li><a href="#birdnet-appdaemon-script">Birdnet AppDaemon Script</a></li>
</ul>
</nav>
</div>
</details>
</div>
<div class="post-content"><p><em>This is Part One of a Two Part Series. You can find Part Two, here.</em></p>
<h2 id="what-you-will-need">What you will need<a hidden class="anchor" aria-hidden="true" href="#what-you-will-need">#</a></h2>
<ul>
<li><a href="https://github.com/mcguirepr89/BirdNET-Pi">BirdNET-Pi</a></li>
<li><a href="https://www.home-assistant.io/">HomeAssistant</a></li>
<li><a href="https://appdaemon.readthedocs.io/en/latest/">AppDaemon</a></li>
<li>MQTT Broker (I use <a href="https://mosquitto.org/">Mosquitto</a>)</li>
</ul>
<h2 id="background">Background<a hidden class="anchor" aria-hidden="true" href="#background">#</a></h2>
<p>In early 2023, at the height of the <a href="https://www.tomshardware.com/news/raspberry-pi-availability-analysis">Raspberry Pi
shortage</a> I felt like a king with an extra Rpi laying
around, not being used. I&rsquo;m a big fan of any sort of passive intake of information and had been looking around for various
citizen science-style projects that can capture information from the world around me. Since I&rsquo;m already running an ADS-B
antenna with <a href="https://www.flightaware.com/">Flight Aware</a>, I figured this next project would deal with radio
waves/transmissions. Instead, to my amazement, I discovered <a href="https://github.com/mcguirepr89/BirdNET-Pi">BirdNET-Pi</a>!</p>
<h2 id="what-is-birdnet-pi">What is BirdNET-Pi?<a hidden class="anchor" aria-hidden="true" href="#what-is-birdnet-pi">#</a></h2>
<p>In case you didn&rsquo;t click the links above, <a href="https://github.com/mcguirepr89/BirdNET-Pi">BirdNET-Pi</a> is an app built specifically
made for Rapsberry Pi devices, that builds off the <a href="https://github.com/kahst/BirdNET-Analyzer">BirdNET Framework</a>. BirdNET is
one of the most advanced acoustic monitoring tools available for passively monitoring bird diversity populations.
Where BirdNET-Pi takes it to the next level is the ability to setup an SBC - hopefully enclosed in a waterproof space! - and
monitor birds in your local environment over time.</p>
<p>I think this project is beyond neat. It runs a bit slow on a Raspberry Pi 3, but overall it runs smoothly. I was even able to
<a href="https://github.com/mcguirepr89/BirdNET-Pi/pull/821">contribute a PR to the project</a> in April when I noticed a bug in the
platform after a hard reset of my Pi.</p>
<h2 id="birdnet-pi-notification-setup---mqtt">BirdNET-PI Notification Setup - MQTT<a hidden class="anchor" aria-hidden="true" href="#birdnet-pi-notification-setup---mqtt">#</a></h2>
<p>Once you have BirdNET-Pi up and running, you&rsquo;ll need to head over to the Settings and setup the correct MQTT payloads. Here
are the possible variables you can pass in an MQTT payload:</p>
<ul>
<li><code>$sciname</code>: Scientific Name</li>
<li><code>$comname</code>: Common Name</li>
<li><code>$confidence</code>: Confidence Score</li>
<li><code>$confidencepct</code>: Confidence Score as a percentage (eg. 0.91 =&gt; 91)</li>
<li><code>$listenurl</code>: A link to the detection</li>
<li><code>$date</code>: Date</li>
<li><code>$time</code>: Time</li>
<li><code>$week</code>: Week</li>
<li><code>$latitude</code>: Latitude</li>
<li><code>$longitude</code>: Longitude</li>
<li><code>$cutoff</code>: Minimum Confidence set in &ldquo;Advanced Settings&rdquo;</li>
<li><code>$sens</code>: Sigmoid Sensitivity set in &ldquo;Advanced Settings&rdquo;</li>
<li><code>$overlap</code>: Overlap set in &ldquo;Advanced Settings&rdquo;</li>
<li><code>$flickrimage</code>: A preview image of the detected species from Flickr. Set your API key below.</li>
</ul>
<p>For our purposes, we will only be using <code>$comname, $sciname, $date, $time, $week,</code> and <code>$confidence</code>. However, this entire
process is extremely customizable, which you&rsquo;ll learn more about in the AppDaemon section. Please expand on it and include
information that is pertinent to your own uses.</p>
<p>Here is how I&rsquo;ve setup my MQTT payload from BirdNET-Pi Settings:</p>
<p><img loading="lazy" src="../posts/img/birdnet_mqtt_settings.png," alt="Notification Settings" title="MQTT Settings in BirdNET-Pi" />
</p>
<p>Here it is in text form:</p>
<pre tabindex="0"><code class="language-none" data-lang="none">Notification Title: $comname,
Notification Body: $sciname, $date, $time, $week, $confidence
[ ] Notify each new infrequent species detection (&lt; 5 visits per week)
[ ] Notify each new species first detection of the day
[X] Notify each new detection
[X] Send weekly report
Minimum time between notifications of the same species (sec): 5
</code></pre><p>To test my MQTT notifications, I use the iOS client &ldquo;MQTTool&rdquo;. After signing up, head to &ldquo;Subscribe&rdquo; and type <code>birdnet</code> as
the topic and then click Subscribe. If everything is setup correctly and there are birds being recorded by the BirdNET-Pi&rsquo;s
microphone, you should start seeing those detections in the MQTTool app. If so, fantastic news! Let&rsquo;s move onto AppDaemon.</p>
<h2 id="appdaemon-script">AppDaemon Script<a hidden class="anchor" aria-hidden="true" href="#appdaemon-script">#</a></h2>
<p>Now that we have the Pi communicating via MQTT, it&rsquo;s time to get that information into HomeAssistant. I&rsquo;ve shared <a href="../posts/birdnet_homeassistant.html#birdnet-appdaemon-script">the full
script</a> at the bottom of this page, but let&rsquo;s jump into each
section. This is not a full tutorial of how to use AppDaemon, but it may help fill in any knowledge gaps with the system.</p>
<h3 id="imports">Imports<a hidden class="anchor" aria-hidden="true" href="#imports">#</a></h3>
<p>First, we&rsquo;re going to import <code>time</code> and <code>requests</code>. We&rsquo;re going to use time as a backup to the <code>$time</code> component in the
payload. This can be helpful to see if there delays, or if BirdNET-Pi stopped detecting. We&rsquo;re then going to use requests to
pull from Wikipedia&rsquo;s API and grab a description for our HomeAssistant Dashboard.</p>
<h3 id="class-definition">Class Definition<a hidden class="anchor" aria-hidden="true" href="#class-definition">#</a></h3>
<p>To start any AppDaemon app, you need to include a Class that is defined in the <code>apps.yaml</code> file. This is also where we
initialize and define the various items that will be used in the remainder of the script.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">birdnet</span>(adbase<span style="color:#f92672">.</span>ADBase):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">initialize</span>(self):
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>hassapi <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>get_plugin_api(<span style="color:#e6db74">&#34;HASS&#34;</span>)
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>adapi <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>get_ad_api()
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>mqttapi <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>get_plugin_api(<span style="color:#e6db74">&#34;MQTT&#34;</span>)
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>birdnet_mqtt <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;birdnet&#34;</span>
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>mqttapi<span style="color:#f92672">.</span>listen_event(
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>birdnet_message, <span style="color:#e6db74">&#34;MQTT_MESSAGE&#34;</span>, topic<span style="color:#f92672">=</span>self<span style="color:#f92672">.</span>birdnet_mqtt
</span></span><span style="display:flex;"><span> )
</span></span></code></pre></div><p>For this script, we need to use a lot of the AppDaemon APIs across more than just HomeAssistant, so we&rsquo;re going to be using
<code>ADBase</code>. By using that, we can initialize the various APIs, which we do in the next 3 lines. In these 3 lines we need to get
access to HomeAssistant&rsquo;s APIs, AppDaemon&rsquo;s APIs, and MQTT APIs - the first and third items are plugins of AppDaemon, and
AppDaemon is&hellip; well&hellip; AppDaemon! Here are a few reference docs:</p>
<ul>
<li><a href="https://appdaemon.readthedocs.io/en/latest/MQTT_API_REFERENCE.html">MQTT AppDaemon API</a></li>
<li><a href="https://appdaemon.readthedocs.io/en/latest/HASS_API_REFERENCE.html">HomeAssistant AppDaemon API</a></li>
<li><a href="https://appdaemon.readthedocs.io/en/latest/AD_API_REFERENCE.html">AppDaemon API</a></li>
</ul>
<p>These will indispensable to you as you leverage AppDaemon and expand this little script.</p>
<p>Once we have access to that, we need to setup the main topic for MQTT from BirdNET-Pi and finally, what event we are
listening for that will trigger the functions in the rest of the script. <code>self.birdnet_mqtt = &quot;birdnet&quot;</code> is the definition
for the MQTT topic. Let&rsquo;s breakdown the last line of the class.</p>
<p>Here&rsquo;s a breakdown of each of the items in that last line. You can find the official documentation <a href="https://appdaemon.readthedocs.io/en/latest/MQTT_API_REFERENCE.html#appdaemon.plugins.mqtt.mqttapi.Mqtt.listen_event">here</a>.</p>
<ul>
<li><code>self.mqttapi.listen_event</code> - this is what we use in AppDaemon to listen for an MQTT event in order to trigger a function.</li>
<li><code>self.birdnet_message</code> - the name of the function you&rsquo;d like to trigger</li>
<li><code>&quot;MQTT_MESSAGE&quot;</code> - The default event in AppDaemon&rsquo;s MQTT API plugin. This is used because MQTT doesn&rsquo;t keep a state in this
plugin.</li>
<li><code>topic=self.birdnet_mqtt</code> - The topic that will be received to trigger the function. Defined on the previous line.</li>
</ul>
<p>In other words, what we are telling AppDaemon is the following: &ldquo;When AppDaemon&rsquo;s MQTT API plugin receives a message with the
topic of &lsquo;birdnet&rsquo;, run the function <code>birdnet_message</code>.&rdquo;</p>
<h3 id="birdnet_message-function">birdnet_message Function<a hidden class="anchor" aria-hidden="true" href="#birdnet_message-function">#</a></h3>
<h4 id="part-1-variables-management">Part 1: Variables Management<a hidden class="anchor" aria-hidden="true" href="#part-1-variables-management">#</a></h4>
<p>Now we get into our first function of the script. The first portion of this script is splitting up the payload that we
defined from the BirdNET-Pi UI into individual variables that we can better manage later on. If you test this script out by
adding <code>print()</code> statements at various points, you&rsquo;ll notice that the payload is received with the following json formatting:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-json" data-lang="json"><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span> <span style="color:#f92672">&#34;payload&#34;</span>: {
</span></span><span style="display:flex;"><span> <span style="color:#f92672">&#34;data&#34;</span>: <span style="color:#e6db74">&#34;data&#34;</span>
</span></span><span style="display:flex;"><span> }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>As such, we need to look <em>inside</em> the payload to begin grabbing the data. The <code>pre_split</code> variable is now just looking at the
data inside the payload and the rest of the variables take all the date into the payload, split it by the comma, and then
grab the string by their index. If you remember what <a href="../posts/birdnet_homeassistant.html#birdnet-pi-notification-setup-mqtt">we did above</a> above, you&rsquo;ll see that we have the various BirdNET information at each of the indexes in the AppDaemon script - 0 through 5.</p>
<h4 id="part-2-re-publishing-mqtt-payloads">Part 2: Re-Publishing MQTT Payloads<a hidden class="anchor" aria-hidden="true" href="#part-2-re-publishing-mqtt-payloads">#</a></h4>
<p>This next section is shooting all the variables we just defined back via MQTT. The reason why we do it this way is because we
need HomeAssistant to grab each of these variables as individual sensors. BirdNET doesn&rsquo;t give us that capability - it&rsquo;s a
single message with all the information in one. [Here is the documentation from AppDaemon](## BirdNET-PI Notification Setup - MQTT
) on <code>mqtt_publish</code>. Later on, I&rsquo;ll show you how to ensure that HomeAssistant takes those topic payloads and adds them as
entities in your HA setup.</p>
<h4 id="part-3-wikipedia-sensor">Part 3: Wikipedia Sensor<a hidden class="anchor" aria-hidden="true" href="#part-3-wikipedia-sensor">#</a></h4>
<p>The next eight lines are a fairly straightforward <a href="https://en.wikipedia.org/api/rest_v1/">API call to Wikipedia</a>. We start
out by passing the <code>science_name</code> into the URL. The rest of the flags that we are passing into the URL comes from Wikipedia&rsquo;s
Docs.
<code>url = f&quot;https://en.wikipedia.org/w/api.php?format=json&amp;action=query&amp;prop=extracts&amp;exintro&amp;explaintext&amp;redirects=1&amp;titles={science_name}&quot;</code></p>
<p>Once that&rsquo;s done we call it with <code>response.get(url)</code> and format it with <code>response.json()</code>. Wikipedia returns the json payload
with the top level of <code>query</code> (which was our action in the url ;) ), and we&rsquo;re looking for the value within that query.</p>
<p>All that&rsquo;s left is to take that query value and push it to HomeAssistant! We can do that with the <code>self.hassapi.set_state</code>
function. Within the parenthesis we define the name of the sensor (<code>sensor.birdnet_wiki</code>), what it&rsquo;s state should be (<code>on</code>),
and any attributes associated with the entity. Since we can&rsquo;t assign a long description to the basic status of the entity,
we&rsquo;re adding an attribute with the key of <code>description</code> and the value will be the wikipedia description garnered from the API
call.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span> url <span style="color:#f92672">=</span> <span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;https://en.wikipedia.org/w/api.php?format=json&amp;action=query&amp;prop=extracts&amp;exintro&amp;explaintext&amp;redirects=1&amp;titles=</span><span style="color:#e6db74">{</span>science_name<span style="color:#e6db74">}</span><span style="color:#e6db74">&#34;</span>
</span></span><span style="display:flex;"><span> response <span style="color:#f92672">=</span> requests<span style="color:#f92672">.</span>get(url)
</span></span><span style="display:flex;"><span> response <span style="color:#f92672">=</span> response<span style="color:#f92672">.</span>json()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> value <span style="color:#f92672">in</span> response[<span style="color:#e6db74">&#39;query&#39;</span>][<span style="color:#e6db74">&#39;pages&#39;</span>]:
</span></span><span style="display:flex;"><span> wiki_desc <span style="color:#f92672">=</span> response[<span style="color:#e6db74">&#39;query&#39;</span>][<span style="color:#e6db74">&#39;pages&#39;</span>][value][<span style="color:#e6db74">&#39;extract&#39;</span>]
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>hassapi<span style="color:#f92672">.</span>set_state(<span style="color:#e6db74">&#34;sensor.birdnet_wiki&#34;</span>, state<span style="color:#f92672">=</span><span style="color:#e6db74">&#39;on&#39;</span>,
</span></span><span style="display:flex;"><span> attributes <span style="color:#f92672">=</span> {<span style="color:#e6db74">&#34;description&#34;</span>: wiki_desc})
</span></span></code></pre></div><h4 id="part-4-generate-picture-for-detection-optional">Part 4: Generate Picture for Detection (Optional)<a hidden class="anchor" aria-hidden="true" href="#part-4-generate-picture-for-detection-optional">#</a></h4>
<p>This part is optional but I noticed that BirdNET-Pi was already grabbing a Flickr Picture for it&rsquo;s front end, so I took the
code from the BirdNET code base and adjusted it a bit for my needs. This will work very similarly to the Wikipedia API call,
the main difference here being that you need an API key for Flickr. You can find more <a href="https://www.flickr.com/services/api/misc.api_keys.html">information here</a>.</p>
<p>Given Flickr&rsquo;s fairly robust API, by passing in the detected bird&rsquo;s common name, we get amazing results from the community of
various pictures of the same species of bird. Ever since I&rsquo;ve set this up, I&rsquo;ve not seen a mislabeled picture in my
dashboard!</p>
<p>The most confusion portion of this section is the <code>image_url</code> as you&rsquo;ll notice a bunch of <code>data[&quot;value&quot;]</code> strings at various
portions of the URL. The short answer to this is in the previous line with the <code>data</code> variable. A successful query has Flickr
returning a large payload of information. We&rsquo;re specifically using <a href="https://www.flickr.com/services/api/flickr.photos.search.html">this</a>
Flickr API endpoint. While you can pass a lot of variables for your needs, if you scroll down, you can see that the example
response contains multiple photos in a single response. We&rsquo;re passing <code>per_page=5</code> to limit some of those response items.
Left out of that response, though, is a one-stop-shop for a URL to that photo. Thankfully, Flickr can help us put together a
URL from the data in the response.</p>
<p><em>Note: Full Transparency that I only learned about this after reading through BirdNET-Pi&rsquo;s code base. Full credit goes to
<a href="https://github.com/mcguirepr89">mcguirepr89</a>. For additional reference, here is Flickr&rsquo;s <a href="https://www.flickr.com/services/api/misc.urls.html">official page on construction
photo image URLS</a></em></p>
<p>With this response, we now have the variables we need to construct the URL to actually render the image. Those variables are:
Farm ID, Server ID, ID and Secret. I haven&rsquo;t yet looked into why we need &ldquo;farm&rdquo; when the official documentation doesn&rsquo;t state
anything about it.</p>
<p>Almost there! We now do the same as we did with the Wikipedia API response. We create a sensor in HomeAssistant! We&rsquo;re
calling this sensor <code>sensor.birdpic</code>, ensuring the <code>state=on</code>, and giving it the attributes of the <code>image_url</code> as garnered
from Flickr.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span> headers <span style="color:#f92672">=</span> {<span style="color:#e6db74">&#39;User-Agent&#39;</span>: <span style="color:#e6db74">&#39;Python_Flickr/1.0&#39;</span>}
</span></span><span style="display:flex;"><span> flickr_api <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;enter_your_api_key&#34;</span>
</span></span><span style="display:flex;"><span> flickr_url <span style="color:#f92672">=</span> <span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;https://www.flickr.com/services/rest/?method=flickr.photos.search&amp;api_key=</span><span style="color:#e6db74">{</span>flickr_api<span style="color:#e6db74">}</span><span style="color:#e6db74">&amp;text=</span><span style="color:#e6db74">{</span>common_name<span style="color:#e6db74">}</span><span style="color:#e6db74"> bird&amp;sort=relevance&amp;per_page=5&amp;media=photos&amp;format=json&amp;nojsoncallback=1&#34;</span>
</span></span><span style="display:flex;"><span> flickr_resp <span style="color:#f92672">=</span> requests<span style="color:#f92672">.</span>get(url<span style="color:#f92672">=</span>flickr_url, headers<span style="color:#f92672">=</span>headers)
</span></span><span style="display:flex;"><span> data <span style="color:#f92672">=</span> flickr_resp<span style="color:#f92672">.</span>json()[<span style="color:#e6db74">&#34;photos&#34;</span>][<span style="color:#e6db74">&#34;photo&#34;</span>][<span style="color:#ae81ff">0</span>]
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> image_url <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;https://farm&#39;</span><span style="color:#f92672">+</span>str(data[<span style="color:#e6db74">&#34;farm&#34;</span>])<span style="color:#f92672">+</span><span style="color:#e6db74">&#39;.static.flickr.com/&#39;</span><span style="color:#f92672">+</span>str(data[<span style="color:#e6db74">&#34;server&#34;</span>])<span style="color:#f92672">+</span><span style="color:#e6db74">&#39;/&#39;</span><span style="color:#f92672">+</span>str(data[<span style="color:#e6db74">&#34;id&#34;</span>])<span style="color:#f92672">+</span><span style="color:#e6db74">&#39;_&#39;</span><span style="color:#f92672">+</span>str(data[<span style="color:#e6db74">&#34;secret&#34;</span>])<span style="color:#f92672">+</span><span style="color:#e6db74">&#39;_n.jpg&#39;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>hassapi<span style="color:#f92672">.</span>set_state(<span style="color:#e6db74">&#34;sensor.birdpic&#34;</span>, state<span style="color:#f92672">=</span><span style="color:#e6db74">&#39;on&#39;</span>,
</span></span><span style="display:flex;"><span> attributes<span style="color:#f92672">=</span>{<span style="color:#e6db74">&#34;image&#34;</span>: image_url})
</span></span></code></pre></div><p>In Part 2 of this article, we&rsquo;ll take a look at Home Assistant, see what these sensors look like, and create a rudimentary
dashboard.</p>
<h2 id="birdnet-appdaemon-script">Birdnet AppDaemon Script<a hidden class="anchor" aria-hidden="true" href="#birdnet-appdaemon-script">#</a></h2>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#f92672">import</span> time
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> requests
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">birdnet</span>(adbase<span style="color:#f92672">.</span>ADBase):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">initialize</span>(self):
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>hassapi <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>get_plugin_api(<span style="color:#e6db74">&#34;HASS&#34;</span>)
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>adapi <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>get_ad_api()
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>mqttapi <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>get_plugin_api(<span style="color:#e6db74">&#34;MQTT&#34;</span>)
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>birdnet_mqtt <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;birdnet&#34;</span>
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>mqttapi<span style="color:#f92672">.</span>listen_event(
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>birdnet_message, <span style="color:#e6db74">&#34;MQTT_MESSAGE&#34;</span>, topic<span style="color:#f92672">=</span>self<span style="color:#f92672">.</span>birdnet_mqtt
</span></span><span style="display:flex;"><span> )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">birdnet_message</span>(self, event_name, data, kwargs):
</span></span><span style="display:flex;"><span> pre_split <span style="color:#f92672">=</span> data[<span style="color:#e6db74">&#34;payload&#34;</span>]
</span></span><span style="display:flex;"><span> common_name <span style="color:#f92672">=</span> pre_split<span style="color:#f92672">.</span>split(<span style="color:#e6db74">&#39;,&#39;</span>)[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">.</span>strip()
</span></span><span style="display:flex;"><span> science_name <span style="color:#f92672">=</span> pre_split<span style="color:#f92672">.</span>split(<span style="color:#e6db74">&#39;,&#39;</span>)[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">.</span>strip()
</span></span><span style="display:flex;"><span> date_seen <span style="color:#f92672">=</span> pre_split<span style="color:#f92672">.</span>split(<span style="color:#e6db74">&#39;,&#39;</span>)[<span style="color:#ae81ff">2</span>]<span style="color:#f92672">.</span>strip()
</span></span><span style="display:flex;"><span> time_seen <span style="color:#f92672">=</span> pre_split<span style="color:#f92672">.</span>split(<span style="color:#e6db74">&#39;,&#39;</span>)[<span style="color:#ae81ff">3</span>]<span style="color:#f92672">.</span>strip()
</span></span><span style="display:flex;"><span> week_seen <span style="color:#f92672">=</span> pre_split<span style="color:#f92672">.</span>split(<span style="color:#e6db74">&#39;,&#39;</span>)[<span style="color:#ae81ff">4</span>]<span style="color:#f92672">.</span>strip()
</span></span><span style="display:flex;"><span> confidence <span style="color:#f92672">=</span> pre_split<span style="color:#f92672">.</span>split(<span style="color:#e6db74">&#39;,&#39;</span>)[<span style="color:#ae81ff">5</span>]<span style="color:#f92672">.</span>strip()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#75715e"># print(f&#34;A {common_name} was seen on {date_seen} at {time_seen}. Confidence is {confidence}.&#34;)</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>mqttapi<span style="color:#f92672">.</span>mqtt_publish(<span style="color:#e6db74">&#34;birdnet/sensors/common_name&#34;</span>, common_name)
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>mqttapi<span style="color:#f92672">.</span>mqtt_publish(<span style="color:#e6db74">&#34;birdnet/sensors/science_name&#34;</span>, science_name)
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>mqttapi<span style="color:#f92672">.</span>mqtt_publish(<span style="color:#e6db74">&#34;birdnet/sensors/time_seen&#34;</span>, time_seen)
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>mqttapi<span style="color:#f92672">.</span>mqtt_publish(<span style="color:#e6db74">&#34;birdnet/sensors/date_seen&#34;</span>, date_seen)
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>mqttapi<span style="color:#f92672">.</span>mqtt_publish(<span style="color:#e6db74">&#34;birdnet/sensors/confidence&#34;</span>, confidence)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> url <span style="color:#f92672">=</span> <span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;https://en.wikipedia.org/w/api.php?format=json&amp;action=query&amp;prop=extracts&amp;exintro&amp;explaintext&amp;redirects=1&amp;titles=</span><span style="color:#e6db74">{</span>science_name<span style="color:#e6db74">}</span><span style="color:#e6db74">&#34;</span>
</span></span><span style="display:flex;"><span> response <span style="color:#f92672">=</span> requests<span style="color:#f92672">.</span>get(url)
</span></span><span style="display:flex;"><span> response <span style="color:#f92672">=</span> response<span style="color:#f92672">.</span>json()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> value <span style="color:#f92672">in</span> response[<span style="color:#e6db74">&#39;query&#39;</span>][<span style="color:#e6db74">&#39;pages&#39;</span>]:
</span></span><span style="display:flex;"><span> wiki_desc <span style="color:#f92672">=</span> response[<span style="color:#e6db74">&#39;query&#39;</span>][<span style="color:#e6db74">&#39;pages&#39;</span>][value][<span style="color:#e6db74">&#39;extract&#39;</span>]
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>hassapi<span style="color:#f92672">.</span>set_state(<span style="color:#e6db74">&#34;sensor.birdnet_wiki&#34;</span>, state<span style="color:#f92672">=</span><span style="color:#e6db74">&#39;on&#39;</span>,
</span></span><span style="display:flex;"><span> attributes <span style="color:#f92672">=</span> {<span style="color:#e6db74">&#34;description&#34;</span>: wiki_desc})
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> headers <span style="color:#f92672">=</span> {<span style="color:#e6db74">&#39;User-Agent&#39;</span>: <span style="color:#e6db74">&#39;Python_Flickr/1.0&#39;</span>}
</span></span><span style="display:flex;"><span> flickr_api <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;enter_your_api_key&#34;</span>
</span></span><span style="display:flex;"><span> flickr_url <span style="color:#f92672">=</span> <span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;https://www.flickr.com/services/rest/?method=flickr.photos.search&amp;api_key=</span><span style="color:#e6db74">{</span>flickr_api<span style="color:#e6db74">}</span><span style="color:#e6db74">&amp;text=</span><span style="color:#e6db74">{</span>common_name<span style="color:#e6db74">}</span><span style="color:#e6db74"> bird&amp;sort=relevance&amp;per_page=5&amp;media=photos&amp;format=json&amp;nojsoncallback=1&#34;</span>
</span></span><span style="display:flex;"><span> flickr_resp <span style="color:#f92672">=</span> requests<span style="color:#f92672">.</span>get(url<span style="color:#f92672">=</span>flickr_url, headers<span style="color:#f92672">=</span>headers)
</span></span><span style="display:flex;"><span> data <span style="color:#f92672">=</span> flickr_resp<span style="color:#f92672">.</span>json()[<span style="color:#e6db74">&#34;photos&#34;</span>][<span style="color:#e6db74">&#34;photo&#34;</span>][<span style="color:#ae81ff">0</span>]
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> image_url <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;https://farm&#39;</span><span style="color:#f92672">+</span>str(data[<span style="color:#e6db74">&#34;farm&#34;</span>])<span style="color:#f92672">+</span><span style="color:#e6db74">&#39;.static.flickr.com/&#39;</span><span style="color:#f92672">+</span>str(data[<span style="color:#e6db74">&#34;server&#34;</span>])<span style="color:#f92672">+</span><span style="color:#e6db74">&#39;/&#39;</span><span style="color:#f92672">+</span>str(data[<span style="color:#e6db74">&#34;id&#34;</span>])<span style="color:#f92672">+</span><span style="color:#e6db74">&#39;_&#39;</span><span style="color:#f92672">+</span>str(data[<span style="color:#e6db74">&#34;secret&#34;</span>])<span style="color:#f92672">+</span><span style="color:#e6db74">&#39;_n.jpg&#39;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>hassapi<span style="color:#f92672">.</span>set_state(<span style="color:#e6db74">&#34;sensor.birdpic&#34;</span>, state<span style="color:#f92672">=</span><span style="color:#e6db74">&#39;on&#39;</span>,
</span></span><span style="display:flex;"><span> attributes<span style="color:#f92672">=</span>{<span style="color:#e6db74">&#34;image&#34;</span>: image_url})
</span></span></code></pre></div>
</div>
<footer class="post-footer">
<ul class="post-tags">
<li><a href="../tags/homeassistant.html">homeassistant</a></li>
<li><a href="../tags/python.html">python</a></li>
<li><a href="../tags/diy.html">diy</a></li>
</ul>
<nav class="paginav">
<a class="prev" href="../posts/new-favorite-website.html">
<span class="title">« Prev</span>
<br>
<span>New Favorite Website!</span>
</a>
<a class="next" href="../posts/multiple_git_remotes.html">
<span class="title">Next »</span>
<br>
<span>Pushing a Single Local Git Repo to Multiple Remote Repos</span>
</a>
</nav>
</footer>
</article>
</main>
<footer class="footer">
<span>&copy; 2023 <a href="../">Norm-working Packets 💾</a></span>
<span>
Powered by
<a href="https://gohugo.io/" rel="noopener noreferrer" target="_blank">Hugo</a> &
<a href="https://github.com/adityatelange/hugo-PaperMod/" rel="noopener" target="_blank">PaperMod</a>
</span>
</footer>
<a href="#top" aria-label="go to top" title="Go to Top (Alt + G)" class="top-link" id="top-link" accesskey="g">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 6" fill="currentColor">
<path d="M12 6H0l6-6z" />
</svg>
</a>
<script>
let menu = document.getElementById('menu')
if (menu) {
menu.scrollLeft = localStorage.getItem("menu-scroll-position");
menu.onscroll = function () {
localStorage.setItem("menu-scroll-position", menu.scrollLeft);
}
}
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener("click", function (e) {
e.preventDefault();
var id = this.getAttribute("href").substr(1);
if (!window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
document.querySelector(`[id='${decodeURIComponent(id)}']`).scrollIntoView({
behavior: "smooth"
});
} else {
document.querySelector(`[id='${decodeURIComponent(id)}']`).scrollIntoView();
}
if (id === "top") {
history.replaceState(null, null, " ");
} else {
history.pushState(null, null, `#${id}`);
}
});
});
</script>
<script>
var mybutton = document.getElementById("top-link");
window.onscroll = function () {
if (document.body.scrollTop > 800 || document.documentElement.scrollTop > 800) {
mybutton.style.visibility = "visible";
mybutton.style.opacity = "1";
} else {
mybutton.style.visibility = "hidden";
mybutton.style.opacity = "0";
}
};
</script>
<script>
document.getElementById("theme-toggle").addEventListener("click", () => {
if (document.body.className.includes("dark")) {
document.body.classList.remove('dark');
localStorage.setItem("pref-theme", 'light');
} else {
document.body.classList.add('dark');
localStorage.setItem("pref-theme", 'dark');
}
})
</script>
</body>
</html>