From a61eadd77ca5f12f8a4aeee286b949da3ae4c68d Mon Sep 17 00:00:00 2001
From: jess <jess@jward.io>
Date: Fri, 31 Aug 2018 23:46:19 +0000
Subject: [PATCH] Final changes: Added async loop to fix issue where it hung
 after muting Final clean-up and comments

---
 darkmute.py | 26 ++++++++++++++------------
 1 file changed, 14 insertions(+), 12 deletions(-)

diff --git a/darkmute.py b/darkmute.py
index dfaf343..b1bfb1e 100644
--- a/darkmute.py
+++ b/darkmute.py
@@ -1,31 +1,33 @@
-import RPi.GPIO as GPIO
+import asyncio
 import time
-import snapcast.control
-from snapcast import get_snapcast_client
-from snapcast import add_server
+import RPi.GPIO as GPIO
+from snap import get_snapcast_client
+
 
 SENSOR_PIN = 7
 MUTE_BRIGHTNESS = 0.1
 
 
 def dark_mute():
-    '''Runs measure_brightness and prints output'''
-    server = snapcast.control.Snapserver(add_server(),
-                                         snapcast.control.CONTROL_PORT)
-    client = get_snapcast_client(server)
+    '''Uses brighness level to mute or unmute device'''
+    # Snapcast library only supports asynchronous so need to wrap in async loop
+    loop = asyncio.new_event_loop()
+    client = get_snapcast_client(loop)
     GPIO.setmode(GPIO.BOARD)
     try:
         while True:
-            #  TODO: track current state, don't send constant updates
             brightness = measure_brightness(SENSOR_PIN)
             if brightness < MUTE_BRIGHTNESS:
-                client.muted = True
+                # client.muted did not work so need client.set_muted
+                # loop used here and also passed into snap.py to get server
+                loop.run_until_complete(client.set_muted(True))
             else:
-                client.muted = False
+                loop.run_until_complete(client.set_muted(False))
     except KeyboardInterrupt:
         pass
     finally:
-            GPIO.cleanup()
+        GPIO.cleanup()
+        loop.close()
 
 
 def measure_brightness(pin_to_circuit):
-- 
GitLab