예제 #1
0
 def test_init_device(self, mocked_device_info):
     device = libsoundtouch.soundtouch_device("192.168.1.1")
     self.assertEqual(mocked_device_info.call_count, 1)
     self.assertEqual(device.host, "192.168.1.1")
     self.assertEqual(device.port, 8090)
     self.assertEqual(device.ws_port, 8080)
     self.assertEqual(device.dlna_port, 8091)
     self.assertEqual(device.config.device_id, "00112233445566")
     self.assertEqual(device.config.device_ip, "192.168.1.1")
     self.assertEqual(device.config.mac_address, "66554433221100")
     self.assertEqual(device.config.name, "Home")
     self.assertEqual(device.config.type, "SoundTouch 20")
     self.assertEqual(device.config.account_uuid, "AccountUUIDValue")
     self.assertEqual(device.config.module_type, "sm2")
     self.assertEqual(device.config.variant, "spotty")
     self.assertEqual(device.config.variant_mode, "normal")
     self.assertEqual(device.config.country_code, "GB")
     self.assertEqual(device.config.region_code, "GB")
     self.assertEqual(len(device.config.networks), 2)
     self.assertEqual(len(device.config.components), 2)
     self.assertListEqual(
         [component.category for component in device.config.components],
         ['SCM', 'PackagedProduct'])
     self.assertListEqual([
         component.serial_number for component in device.config.components
     ], ['XXXXX', 'YYYYY'])
     self.assertListEqual([
         component.software_version
         for component in device.config.components
     ], ['13.0.9.29919.1889959 epdbuild.trunk.cepeswbldXXX', None])
예제 #2
0
def playSong1(track):
	device = soundtouch_device('192.168.1.168')

	#device.power_on()
	trackToPlay = 'spotify:track:'+track
	print(device.config.name)
	resp = device.play_media(Source.SPOTIFY, trackToPlay, '5yz9rfw854rb39vkepel9jh3f')
	print(resp)
예제 #3
0
 def __init__(self, name, config):
     """Create Soundtouch Entity."""
     from libsoundtouch import soundtouch_device
     self._name = name
     self._device = soundtouch_device(config['host'], config['port'])
     self._status = self._device.status()
     self._volume = self._device.volume()
     self._config = config
예제 #4
0
    def _initSoundTouch(self):
        if (self.configuration['name']) is not None:
            logger.debug("Searching device with name : " +
                         self.configuration['name'])
            device = self._findByName()
        elif (self.configuration['port']) is not None:
            device = soundtouch_device(self.configuration['host'],
                                       self.configuration['port'])
        else:
            device = soundtouch_device(self.configuration['host'])

        if device is None:
            logger.error('Device not found')
            raise RuntimeError("Device not found")
        else:
            logger.debug("Got device :" + device.config.name)
            self.device = device
예제 #5
0
 def __init__(self, name, config):
     """Create Soundtouch Entity."""
     from libsoundtouch import soundtouch_device
     self._name = name
     self._device = soundtouch_device(config['host'], config['port'])
     self._status = self._device.status()
     self._volume = self._device.volume()
     self._config = config
def main():

    # Getting the emotions from the IBM Watson Cloud Visual Recognition
#     cmd = '''curl -u "apikey:9t_w3I8yzOheBd9syHpyPFEeCN21DSw0NX8tnYJCvdBe" "https://gateway.watsonplatform.net/visual-recognition/api/v3/classify?url=https://us.123rf.com/450wm/bowie15/bowie151401/bowie15140100080/39843138-sad-man.jpg?ver=6&version=2018-03-19&classifier_ids=DefaultCustomModel_1963778161"
#     '''
	  
    # args = shlex.split(cmd)
#     process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#     stdout, stderr = process.communicate()
#     stdout1 = stdout.decode("utf-8")
    url ='https://gateway.watsonplatform.net/visual-recognition/api/v3/classify?version=2016-04-19&classifier_ids=DefaultCustomModel_2222222' 
    files = {'images_file': open("./XTYZZ.jpg",'rb')} 
    stdout = requests.post(url, auth=('apikey','XXXXXXXXXXXXXXXX'), files=files)
    stdout1 = str(stdout.content)
    # Splitting the string returned to get the emotion "Sad" "Happy" "Angry" "Depressed"
    emotion = stdout1.split('"class":')[1].split('",')[0].replace(' "','')
    
    print(emotion)
    id = ""

    if emotion == "Happy":
        id = "spotify:playlist:XDXDXDXDXD"
        cmd = '''curl -d \\ "<play_info><app_key>XXXXXDXDXDXD</app_key><url>http://www.fromtexttospeech.com/output/111111/222222.mp3</url><service>service text</service><reason>reason text</reason><message>message text</message><volume>25</volume></play_info>" http://192.170.100.160:9090/speaker'''
    elif emotion == "Sad":
        id = "spotify:playlist:DDDDDDDDDDD"
        cmd = '''curl -d \\ "<play_info><app_key>DDDDDDDDDDDD</app_key><url>http://www.fromtexttospeech.com/output/222222/333333.mp3</url><service>service text</service><reason>reason text</reason><message>message text</message><volume>25</volume></play_info>" http://192.170.100.160:9090/speaker'''
    elif emotion == "Angry":
        id = "spotify:playlist:XXXXXXXXXX"
        cmd = '''curl -d \\ "<play_info><app_key>XXXXXXXXXX</app_key><url>http://www.fromtexttospeech.com/output/333333/444444.mp3</url><service>service text</service><reason>reason text</reason><message>message text</message><volume>25</volume></play_info>" http://192.170.100.160:9090/speaker'''


    args = shlex.split(cmd)
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    st, sd = process.communicate()
    st1 = st.decode("utf-8")
    time.sleep(10)

    # Switching on the device
    device = soundtouch_device('193.170.100.120')
    device.power_on()
    # Config object
    print(device.config.name)

    # Status object
    # device.status() will do an HTTP request. Try to cache this value if needed.
    #device.play_media(Source.INTERNET_RADIO, '4712')
    #device.play()
    #device.pause()

    #Spotify Username
    spot_user_id = 'mnuk68asijvbj6nzapegd4p94' # Should be filled in with your Spotify userID
    # This userID can be found by playing Spotify on the
    # connected SoundTouch speaker, and calling
    #print(device.status().content_item.source_account)
    # time.sleep(10)
    device.play_media(Source.SPOTIFY,id,spot_user_id)
    return ""
예제 #7
0
def getCurrentSongDuration():
	URL = "http://192.168.1.168:8090/now_playing"
	device = soundtouch_device('192.168.1.168')
	print(device.status().content_item.source_account)
	# device.power_on()
	print(device.config.name)
	resp = (device.status())

	return resp.duration
예제 #8
0
def findMaster():
    for device in devices:
        device = soundtouch_device(device)
        status = device.status()
        zone_status = device.zone_status()
        if zone_status:
            if zone_status.is_master:
                master = device.config.name
                print (str(master) + " is Master")
예제 #9
0
    def __init__(self, name, config):
        """Create Soundtouch Entity."""

        self._device = soundtouch_device(config["host"], config["port"])
        if name is None:
            self._name = self._device.config.name
        else:
            self._name = name
        self._status = self._device.status()
        self._volume = self._device.volume()
        self._config = config
예제 #10
0
 def test_init_device_with_none_values(self, mocked_device_info):
     device = libsoundtouch.soundtouch_device("192.168.1.1")
     self.assertEqual(mocked_device_info.call_count, 1)
     self.assertIsNone(device.config.device_id)
     self.assertIsNone(device.config.name)
     self.assertIsNone(device.config.type)
     self.assertIsNone(device.config.account_uuid)
     self.assertIsNone(device.config.module_type)
     self.assertIsNone(device.config.variant)
     self.assertIsNone(device.config.variant_mode)
     self.assertIsNone(device.config.country_code)
     self.assertIsNone(device.config.region_code)
예제 #11
0
def sonBose1():

    entrepot = soundtouch_device('192.168.1.11')
    entrepot.power_on()

    #entrepot.snapshot()
    volumeactuel = entrepot.volume()

    entrepot.set_volume(25)
    entrepot.play_url('http://192.168.1.39/Sons/Sonnette.wav')
    time.sleep(2)
    entrepot.play_url('http://192.168.1.39/Sons/Sonnette.wav')
    time.sleep(2)

    #entrepot.restore()
    entrepot.set_volume(volumeactuel)
예제 #12
0
    def __init__(self, sh, *args, **kwargs):
        """
        Initalizes the plugin. The parameters describe for this method are pulled from the entry in plugin.conf.

        :param sh:  **Deprecated**: The instance of the smarthome object. For SmartHomeNG versions 1.4 and up: **Don't use it**!
        :param *args: **Deprecated**: Old way of passing parameter values. For SmartHomeNG versions 1.4 and up: **Don't use it**!
        :param **kwargs:**Deprecated**: Old way of passing parameter values. For SmartHomeNG versions 1.4 and up: **Don't use it**!

        If you need the sh object at all, use the method self.get_sh() to get it. There should be almost no need for
        a reference to the sh object any more.

        The parameters *args and **kwargs are the old way of passing parameters. They are deprecated. They are imlemented
        to support oder plugins. Plugins for SmartHomeNG v1.4 and beyond should use the new way of getting parameter values:
        use the SmartPlugin method get_parameter_value(parameter_name) instead. Anywhere within the Plugin you can get
        the configured (and checked) value for a parameter by calling self.get_parameter_value(parameter_name). It
        returns the value in the datatype that is defined in the metadata.
        """
        from bin.smarthome import VERSION
        if '.'.join(VERSION.split('.', 2)[:2]) <= '1.5':
            self.logger = logging.getLogger(__name__)

        # If an package import with try/except is done, handle an import error like this:

        # Exit if the required package(s) could not be imported
        # if not REQUIRED_PACKAGE_IMPORTED:
        #     self.logger.error("Unable to import Python package '<exotic package>'")
        #     self._init_complete = False
        #     return

        # get the parameters for the plugin (as defined in metadata plugin.yaml):
        self.PLUGIN_PARAMETER_IP = self.get_parameter_value('ip')
        self.PLUGIN_PARAMETER_PORT = self.get_parameter_value('port')

        # cycle time in seconds, only needed, if hardware/interface needs to be
        # polled for value changes by adding a scheduler entry in the run method of this plugin
        # (maybe you want to make it a plugin parameter?)
        self._cycle = self.get_parameter_value('cycle_time')

        #######################################################################
        # BOSE SOUNDTOUCH INITIALIZATION
        #######################################################################
        # Connect to device
        self.device = soundtouch_device(self.PLUGIN_PARAMETER_IP,
                                        self.PLUGIN_PARAMETER_PORT)
        self.logger.info("Initialized connection to Bose Soundtouch device '" +
                         self.getSoundtouchDevice().config.name + "' at " +
                         self.getSoundtouchDevice().config.device_ip)
        #######################################################################

        # On initialization error use:
        #   self._init_complete = False
        #   return

        # The following part of the __init__ method is only needed, if a webinterface is being implemented:

        # if plugin should start even without web interface
        # self.init_webinterface()

        # if plugin should not start without web interface
        # if not self.init_webinterface():
        #     self._init_complete = False

        return
예제 #13
0
# -*- coding: utf-8 -*-
#
from libsoundtouch import soundtouch_device
from libsoundtouch.utils import Source, Type

device = soundtouch_device('192.168.1.1')  # Manual configuration
device.power_on()

# Config object
print(device.config.name)

# Status object
# device.status() will do an HTTP request.
# Try to cache this value if needed.
status = device.status()
print(status.source)
print(status.artist + " - " + status.track)
device.pause()
device.next_track()
device.play()

# Media Playback
# device.play_media(source, location, account, media_type)
# account and media_type are optionals

# Radio
device.play_media(Source.INTERNET_RADIO, '4712')  # Studio Brussel

# Spotify
spot_user_id = ''  # Should be filled in with your Spotify userID
# This userID can be found by playing Spotify on the
# Getting the emotions from the IBM Watson Cloud Visual Recognition
cmd = '''curl -u "apikey:XXXX" "https://gateway.watsonplatform.net/visual-recognition/api/v3/classify?url=https://us.123rf.com/450wm/bowie15/bowie151401/bowie15140100080/39843138-sad-man.jpg?ver=6&version=2018-03-19&classifier_ids=DefaultCustomModel_196000000"'''
args = shlex.split(cmd)
process = subprocess.Popen(args,
                           shell=False,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout1 = stdout.decode("utf-8")

# Splitting the string returned to get the emotion "Sad" "Happy" "Angry" "Depressed"
emotion = stdout1.split('"class":')[1].split('",')[0].replace(' "', '')
print(emotion)

# Switching on the device
device = soundtouch_device('194.168.109.111')
device.power_on()

# Config object
print(device.config.name)

# Status object
# device.status() will do an HTTP request. Try to cache this value if needed.
#device.play_media(Source.INTERNET_RADIO, '4712')
#device.play()
#device.pause()

#Spotify Username
spot_user_id = 'XXXXXXXXXXX'  # Should be filled in with your Spotify userID
# This userID can be found by playing Spotify on the
# connected SoundTouch speaker, and calling
예제 #15
0
    parser = argparse.ArgumentParser()
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='Be verbose')
    parser.add_argument(
        'host',
        help='IP address or hostname of Bose SoundTouch device',
        default='192.168.111.106')
    args = parser.parse_args()

    if args.verbose:
        _LOGGER.setLevel(logging.DEBUG)
    else:
        _LOGGER.setLevel(logging.INFO)

    host = args.host
    try:
        device = soundtouch_device(host)
    except ConnectionError as e:
        print('Could not connect to device(' + host + '):\n' + e.__str__() +
              '\n',
              file=sys.stderr)
        exit(-1)

    # Config object
    print('Connected to \'' + device.config.name + '(@ ' + host + ')\'')
    prompt = SoundtouchPrompt(device)
    prompt.prompt = '> '
    prompt.cmdloop('Starting prompt...')
예제 #16
0
            STdevice.play_media(Source.SPOTIFY,
                                'spotify:track:3Q8HNCQq4NU8dd7qBv6m13',
                                os.environ['SPOTIFY_API_KEY'])
        elif (emotion == SURPRISED):
            STdevice.play_media(Source.SPOTIFY,
                                'spotify:track:4uLU6hMCjMI75M1A2tKUQC',
                                os.environ['SPOTIFY_API_KEY'])
        elif (emotion == PLAY):
            STdevice.play()
        elif (emotion == PAUSE):
            STdevice.pause()
        else:
            return json.dumps({
                "status": "404",
                "message": "Desired action could not be found"
            })
    except:
        return "Error occured during operation"


if __name__ == '__main__':
    # Status object
    # device.status() will do an HTTP request. Try to cache this value if needed.

    STdevice = soundtouch_device(os.environ['BOSE_IP'])
    # STdevice.power_on()
    status = STdevice.status()

    # app.run(debug=True)
    app.run()
예제 #17
0
from flask import Flask, request
from libsoundtouch import soundtouch_device
from auth import requires_auth
from config import config

soundtouch = soundtouch_device(config['soundtouch']['ip'])
app = Flask(__name__)

BASE_SOUNDTOUCH_URL = '/soundtouch'
SUCCESS_RESPONSE_JSON = '{"result": "success"}'

@app.route(BASE_SOUNDTOUCH_URL)
def index():
    return 'Welcome to the Soundtouch Control System'
    
@app.route(BASE_SOUNDTOUCH_URL+'/volume', methods=['POST'])
@requires_auth
def set_volume():
    req_data = request.get_json()
    volume = req_data['volume']
    soundtouch.set_volume(volume)
    return SUCCESS_RESPONSE_JSON
    
@app.route(BASE_SOUNDTOUCH_URL+'/source', methods=['POST'])
@requires_auth
def set_source():
    req_data = request.get_json()
    source = req_data['source']
    if source == 'tv':
        soundtouch.select_source_tv()
    elif source == 'bluetooth':
예제 #18
0
import matplotlib.pyplot as plt
from libsoundtouch import soundtouch_device, discover_devices
from libsoundtouch.utils import Source, Type
from random import *
import numpy as np
import time

device = soundtouch_device('192.168.1.105')
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(100)
y = np.random.randn(100)
li, = ax.plot(x, y)
ax.relim()
ax.autoscale_view(True, True, True)
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
fig.canvas.draw()
plt.show(block=False)
while True:
    volume = device.volume()

    y[:-1] = y[1:]
    y[-1:] = float(volume.actual)
    li.set_ydata(y)
    fig.canvas.draw()
    time.sleep(0.01)
예제 #19
0
# -*- coding: utf-8 -*-
#
#
from libsoundtouch import soundtouch_device

master = soundtouch_device('192.168.18.1')
slave1 = soundtouch_device('192.168.18.2')
slave2 = soundtouch_device('192.168.18.3')

# Create a new zone
master.create_zone([slave1, slave2])

# Remove a slave
master.remove_zone_slave([slave2])

# Add a slave
master.add_zone_slave([slave2])
예제 #20
0
           'DEVICE_IP', # Device 3
           'DEVICE_IP'] # Device 4

def discoverDevices():
    x = PrettyTable()
    x.field_names = ["DEVICE NAME", "DEVICE ID", "DEVICE IP", "DEVICE MAC", "DEVICE STATUS", "ZONE STATUS", "DEVICE TYPE"]
    x.align["DEVICE NAME"] = "l"
    x.align["DEVICE ID"] = "l"
    x.align["DEVICE IP"] = "l"
    x.align["DEVICE MAC"] = "l"
    x.align["DEVICE STATUS"] = "l"
    x.align["ZONE STATUS"] = "l"
    x.align["DEVICE TYPE"] = "l"

for device in devices:
        device = soundtouch_device(device)
        status = device.status()
        zone_status = device.zone_status()
        mac = re.sub(r'(.{2})(?!$)', r'\1:', device.config.mac_address)
        
        if zone_status:
            if zone_status.is_master:
                zone_status = 'Master'
            else:
                zone_status = 'Slave'

        x.add_row([device.config.name, device.config.device_id, device.config.device_ip, mac , status.source, zone_status, device.config.type])
        
    print(x)

def findMaster():
예제 #21
0
 def __init__(self, ip=''):
     self.ip = ip
     self.device = soundtouch_device(self.ip)