Skip to content

Instantly share code, notes, and snippets.

@ov1d1u
Last active November 28, 2023 18:40
Show Gist options
  • Save ov1d1u/8e6ec1f0a087d1f410c65f16217273ba to your computer and use it in GitHub Desktop.
Save ov1d1u/8e6ec1f0a087d1f410c65f16217273ba to your computer and use it in GitHub Desktop.
Get MacOS mic status
import time
import requests
import atomacos
sysui = atomacos.getAppRefByBundleId('com.apple.controlcenter')
hass_api_url = "https://hassio.ov1d1u.net/api/webhook/<webhook_id>"
state = { "incall": False }
while True:
elems = [elem for elem in sysui.findAllR() if 'AXDescription' in elem.getAttributes()]
descs = [elem for elem in elems if 'Microphone' in elem.AXDescription.split() and 'use' in elem.AXDescription.split()]
is_mic_on = bool(descs)
new_state = { "incall": is_mic_on }
if new_state != state:
try:
r = requests.post(hass_api_url, json=new_state)
print("response:", r.text)
except:
pass
state = new_state
time.sleep(0.16)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>net.ov1d1u.pyhton.micstatus</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/python3/python3</string>
<string>/Users/ovidiu/Projects/micstatus.py</string>
</array>
<key>StandardErrorPath</key>
<string>/tmp/python_script.error</string>
<key>KeepAlive</key>
<true/>
<key>WorkingDirectory</key>
<string>/tmp</string>
</dict>
</plist>
- trigger:
- platform: webhook
webhook_id: <webhook_id>
binary_sensor:
- name: "In Call"
unique_id: fccb4eb1-5dd2-4d83-a15b-0abff69612c6
state: "{{ trigger.json.incall }}"
@johntdyer
Copy link

is this working for you in OSX 13.5.2?

@ov1d1u
Copy link
Author

ov1d1u commented Sep 19, 2023

Seems that it still working. If it doesn't work for you, add this at line 12 (after the line with elems = ....):

[print(elem.AXDescription) for elem in elems]

Then run the script in Terminal and see what the accessibility description you get when the microphone is in use.

@jrprinty
Copy link

jrprinty commented Sep 26, 2023

Sorry, but I am new to running python3 as a daemon, and when running the script with launchctl, it isn't loading the modules. How do I correct that? It works great when run by the user.

I installed both modules using

python3 -m pip install

UPDATE:
I forgot to use the Homebrew path for python3. All is working fine now.

Thank you so much for posting this!

@parautenbach
Copy link

This is very useful, thank you for this gist.

Has anybody seen a memory leak by running this for long periods (as intended)?

macOS 13.5.2 (22G91) on an Apple M1 iMac.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment