Repository navigation
Expand file tree
/
Copy pathmpdcontrol.py
More file actions
executable file
·279 lines (255 loc) · 6.67 KB
/
Copy pathmpdcontrol.py
File metadata and controls
executable file
·279 lines (255 loc) · 6.67 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/python
# -*- coding: utf-8 -*-
from serial import Serial
import os
from subprocess import Popen, PIPE
import time
import threading
import string
from daemon import runner
import commands
import logging
ips = commands.getoutput("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | grep -v '127.0.0.1' | " +
"awk {'print $2'} | sed -ne 's/addr\:/ /p'")
print ips
# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
connected = False
poweroff = False
t1=0
serial_port = Serial('/dev/ttyAMA0', 115200, timeout=0)
#!!!! DO NOT ENABLE LOG IN PRODUCTION! This ruins sdxc memory card!!!!
log = False
#log = True
def handle_data(x):
global poweroff
global log
if log==True: #and x and x.strip()!='RPC_S_SONG':
logger.info("handle.data "+x.strip())
# print(x.strip())
cmd2=''
for case in switch(x.strip()):
if case('RPC_PLAY'):
cmd='play'
break
if case('RPC_STOP'):
cmd='pause'
break
if case('RPC_PAUSE'):
cmd='toggle'
break
if case('RPC_NEXT'):
cmd='next'
break
if case('RPC_PREV'):
cmd='previous'
break
if case('RPC_POWEROFF'):
cmd='RPC_POWEROFF'
break
if case('RPC_POWERON'):
cmd=''
break
if case('RPC_VOLUP'):
cmd='volume'
cmd2='+1'
break
if case('RPC_VOLDOWN'):
cmd='volume'
cmd2='-1'
break
if case('RPC_FF'):
cmd='seek'
# cmd2='+00:00:10'
cmd2='plus'
break
if case('RPC_RW'):
cmd='seek'
# cmd2='-00:00:10'
cmd2='minius'
break
if case('RPC_STATUS'):
cmd='STATUS'
break
if case('RPC_S_SONG'):
# cmd='S_STATUS'
cmd=''
break
if case(): # default
cmd=''
cmd2=''
break
if cmd:
if log==True:
logger.info("exec cmd=" + cmd)
if cmd=="RPC_POWEROFF":
print("Going to power off...")
cmd=""
poweroff=True; # set flag to power off PC
else:
if cmd!="STATUS":
print("NO power off!")
poweroff=False;
for case in switch(cmd):
if case('STATUS'):
ips = commands.getoutput("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | grep -v '127.0.0.1' | awk {'print $2'} | sed -ne 's/addr\:/ /p'")
# serial_port.write("OK\n")
serial_port.write("OK" + ips)
serial_port.write("\n")
time.sleep(0.1)
break
if case('S_STATUS'):
# if log==True:
# logger.info("song status cmd=" + cmd)
process = Popen(["volumio","status"], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
print(output)
serstat=0
if log==True:
logger.info("mpc exit_code=" + exit_code)
logger.info("mpc output=" + output)
logger.info("mpc err=" + err)
line = string.split(output, '\n')
if line[0].startswith('volume:'):
serial_port.write("P0\n")
else:
serial_port.write("P1"+line[0]+"\n")
serial_port.write("P2"+line[1]+"\n")
break
if case():
#mpc commands
if log==True:
logger.info("mpc cmd=" + cmd + " cmd2=" + cmd2)
if cmd2=='':
process = Popen(["volumio", cmd], stdout=PIPE)
# if log==True:
# logger.info("mpc process 1=" + process)
else:
process = Popen(["volumio", cmd, cmd2], stdout=PIPE)
# if log==True:
# logger.info("mpc process 2=" + process)
(output, err) = process.communicate()
exit_code = process.wait()
# print ("Exit code")
# print (exit_code)
if log==True:
# logger.info("mpc exit_code=" + exit_code)
logger.info("mpc output=" + output)
# logger.info("mpc err=" + err)
# print ("Output")
# print(output)
serstat=0
for line in string.split(output, '\n'):
if line.startswith('volume:'):
if line.find("%"):
vol=line[line.find(" ")+1:line.find("%")]
if vol:
serial_port.write("v"+vol+"\n")
print("v"+vol+"\n")
serstat=1
# print ("line = " + line)
# cmd=''
break
cmd=''
cmd=''
def read_from_port(ser):
global connected
while not connected:
#serin = ser.read()
connected = True
while True:
# print("test")
reading = ser.readline().decode()
handle_data(reading)
# if threaded
#thread = threading.Thread(target=read_from_port, args=(serial_port,))
#thread.start()
def mainloop():
#t1=time()
while True:
# x=ser.readline()
#ser.write('1')
#if not threaded
# logger.debug("Debug message")
x=serial_port.readline()
if log==True:
logger.info("before=" + x)
handle_data(x)
if log==True:
logger.info("after=" + x)
x=''
serial_port.flushInput()
if poweroff:
if (time.time()-t2>1):
print(".")
t2=time.time()
if t1>0:
if (time.time()-t1>10): # 30 seconds timeout without commands
print ("Bye bye!")
serial_port.write("PWROFF")
os.system("mpc stop && poweroff");
else:
t1=time.time() # start counting
else:
t1=0
t2=0
# t2=time()
# if t2-t1>10:
# print(t2-t1)
# t1=t2
# process = Popen(["mpc"], stdout=PIPE)
# (output, err) = process.communicate()
# exit_code = process.wait()
# print ("Exit code")
# print (exit_code)
# print ("Output")
# print(output)
time.sleep(0.1)
class MPDControl():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/null'
# self.stderr_path = '/dev/null'
# self.stdin_path = '/tmp/stdin'
# self.stdout_path = '/tmp/stdout'
self.stderr_path = '/tmp/stderr'
self.pidfile_path = '/tmp/mpdcontrol.pid'
self.pidfile_timeout = 5
def run(self):
serial_port = Serial('/dev/ttyAMA0', 115200, timeout=0)
# logger.debug("Debug message")
logger.info("mpdcontrol started!")
# logger.warn("Warning message")
# logger.error("Error message")
mainloop()
app = MPDControl()
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("/tmp/mpdcontrol.log")
handler.setFormatter(formatter)
logger.addHandler(handler)
daemon_runner = runner.DaemonRunner(app)
daemon_runner.daemon_context.files_preserve=[handler.stream]
daemon_runner.do_action()