-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathamp_power.py
118 lines (101 loc) · 2.94 KB
/
amp_power.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
from enum import Enum
import time
import subprocess
import re
import logging
import sys
STEAM_PROC = '/proc/asound/card2/stream0'
KASA_DEVICE = 'Amplifier'
KASA_AMP_CMD = ['kasa', '--type', 'plug', '--alias', KASA_DEVICE]
class State(Enum):
UNKNOWN = 'unkown'
OFF = 'off'
ON = 'on'
#
# Here we look for the playback status
#
# $ cat /proc/asound/card2/stream0
# MOTU M4 at usb-0000:01:00.0-1.3, high speed : USB Audio
# Playback:
# Status: Running
# ...
#
def getSoundState() :
state = State.UNKNOWN
file = open(STEAM_PROC)
data = file.read()
file.close()
result = re.search("Playback:\s+Status:\s+(Running|Stop)", data)
if result is not None:
match result.group(1):
case 'Running':
state = State.ON
case 'Stop':
state = State.OFF
#log.info("Sound is " + str(state))
return state
#
# Get the state of the plug
#
# $ kasa --type plug --alias "Amplifier" state
# Alias is given, using discovery to find host Amplifier
# Found hostname is 192.168.86.29
# == Amplifier - HS103(US) ==
# Host: 192.168.86.29
# Device state: ON
# ...
#
def getAmpState() :
state = State.UNKNOWN
cmd = KASA_AMP_CMD.copy()
cmd.append('state')
data = subprocess.check_output(cmd)
result = re.search("Device state: (ON|OFF)", str(data))
if result is not None:
match result.group(1):
case 'ON':
state = State.ON
case 'OFF':
state = State.OFF
log.info("Amp is " + str(state))
return state
#
# Set the state of the plug
#
# $ kasa --type plug --alias "Amplifier" on
# Alias is given, using discovery to find host Amplifier
# Found hostname is 192.168.86.29
# ...
#
def setAmpState(state) :
if (state == State.UNKNOWN):
return
log.info("Setting Amp to " + str(state))
cmd = KASA_AMP_CMD.copy()
cmd.append(str(state.value))
subprocess.check_output(cmd)
#
# Main loop
#
if __name__ == '__main__':
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
log = logging.getLogger("amp_power")
log.info("Starting")
sound_prev_state = State.UNKNOWN
while (True) :
sound_new_state = getSoundState()
if sound_new_state == State.UNKNOWN:
log.error("Unable to get sound state")
sys.exit()
elif sound_prev_state != sound_new_state:
log.info("Sound changed from " + str(sound_prev_state) + " to " + str(sound_new_state))
amp_state = getAmpState()
if amp_state == State.UNKNOWN:
log.error("Unable to get amp state")
sys.exit()
elif amp_state != sound_new_state:
setAmpState(sound_new_state)
else:
log.info("Amp is already " + str(sound_new_state))
sound_prev_state = sound_new_state
time.sleep(1)