Advertisement
Guest User

Python MQTT Alsa volume controller

a guest
Dec 23rd, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. #    This program is free software: you can redistribute it and/or modify
  2. #    it under the terms of the GNU General Public License as published by
  3. #    the Free Software Foundation, either version 3 of the License, or
  4. #    (at your option) any later version.
  5. #
  6. #    This program is distributed in the hope that it will be useful,
  7. #    but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  9. #    GNU General Public License for more details.
  10. #
  11. #    You should have received a copy of the GNU General Public License
  12. #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  13. #
  14. #
  15. # Python/MQTT volume controller (ALSA).
  16. #
  17. # Every 2 second it checks the current system volume. If it has
  18. # changed, it is reported via MQTT. If a setvolume command is
  19. # received through MQTT, the system volume is set to the incoming
  20. # value.
  21. #
  22. # This script can run as a service, for a user that has the necessary
  23. # rights to control the alsa volume (f.ex. logged in user). No
  24. # guarantees for security holes/bugs if run as root.
  25.  
  26. import paho.mqtt.client as mqtt
  27. import alsaaudio
  28. import time
  29. import socket
  30.  
  31. mqtt_broker = 'raaserv'
  32. mqtt_port = 1883
  33.  
  34. sleeptime = 2 # seconds
  35. topic = socket.gethostname() + "/volume"
  36.  
  37. currentvolume = 0
  38.  
  39. def on_connect(client, userdata, flags, rc):
  40.     print "Connected to MQTT"
  41.     client.subscribe(socket.gethostname() + '/setvolume')
  42.  
  43.  
  44. def on_message(client, userdata, msg):
  45.     print "Got message " + str(msg.payload)
  46.     alsaaudio.Mixer().setvolume(int(msg.payload))
  47.  
  48. client = mqtt.Client()
  49. client.on_connect = on_connect
  50. client.connect(mqtt_broker, mqtt_port)
  51. client.on_message = on_message
  52.  
  53. time.sleep(1)
  54.  
  55. while True:
  56.     newvolume = int(alsaaudio.Mixer().getvolume()[0])
  57.     print newvolume
  58.     if newvolume != currentvolume:
  59.         client.publish(topic, str(newvolume))
  60.         currentvolume = newvolume
  61.         print "changed: " + str(newvolume)
  62.     client.loop(sleeptime)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement