Try to link iTunes and Hue collection case with MQTT

This article is the 16th day article of Home Hack Advent Calendar 2015.

I've accumulated a lot of things, and I was a little late for the Advent Calendar ... so it's the 16th day. There aren't many days this year ... Looking back, there were various changes this year, and I moved to a larger room, and it was a year when I was playing around with "The environment for my house hack is ready!".

Until now, like Aggregate status confirmation and operation of IRKit and Philips Hue with MQTT, manually control devices such as IRKit and Hue I was playing around, but when I became able to do it manually, the next thing I wanted to do was human beings.

That's why I'm playing around with things like syncing my device with applications, especially iTunes, so make a note of it.

Hue as a collection case ... but how do you control it?

I bought a collection case when I moved, and bought Chogokin Soul Brave King Gaogaigar to decorate it. I wanted to add something to the toys that were very big and well-made, rather than just decorating them.

So, although it is easy, I tried to attach the surplus Hue appropriately.

image

Just playing with the colors and brightness from the Hue app will change the atmosphere and raise the tension, but if this light is automatically activated by some change in the house, the tension will rise even more.

Link iTunes and Hue?

On the other hand, our home audio is unified to iTunes, and it is configured to be enjoyed with speakers connected to Apple TV from Mac with AirPlay.

Of course, I also enjoy hot songs such as "The King of Braves!" In this environment, but ** Isn't the tension rising when the lighting of the collection case changes in synchronization with iTunes? **have become.

Link iTunes and MQTT?

I already made it possible to monitor and control Hue via MQTT in the previous article, ** The song information being played on iTunes is transmitted to MQTT, and the song is played on iTunes by the message thrown to MQTT * I thought that the shape of * would be good, so I started to consider it.

When I thought about linking iTunes with other apps, I immediately came up with the idea of using DAAP to remotely monitor and control the playback status of iTunes. I used to feel that the stray DAAP library was also connected to iTunes, but after a little trial, I encountered a case that did not work with the latest version and gave up.

That's how I searched for and arrived at AppleScript. It's dark under the lighthouse. By using AppleScript, you can easily write scripts that work with other Mac applications ...

I wanted to make the communication with MQTT with Python, but since there is py-applescript for cooperation with Python, install this one If you do, you can also execute AppleScript from Python. It looks like the following.

import applescript

...

script = applescript.AppleScript('''
on current_state()
    tell application "iTunes"
        try
            set c to container of current track
        on error
            return {}
        end try
        set cinfo to {playlist_name:name of c}
        set tinfo to {track_name:name of current track, track_artist:artist of current track, track_album:album of current track}
        return cinfo & tinfo
    end tell
end current_state
''')

...

state = script.call('current_state')

Now you can get the iTunes current track information from Python. Nice.

Write a guy that connects iTunes and MQTT

I wrote that.

When you install it, the command ** mqtt-itunes ** will be installed. With this command executed, you can get information about the song being played on iTunes by subscribing to the topic named specified by the option / iTunes distinguished name / current specified by the option on the MQTT server. I can do it.

The data on this topic looks like this.

{"state": "playing", "track_name": "Birth of the Hero King!", "playlist_name": "Music",
 "track_album": "The King of Braves Gaogaigar-Original Soundtrack 1",
 "track_artist": "Masaaki Endoh"}

Conversely, by publishing JSON in the same format for this topic, you can also play, pause, and stop the song.

ITunes and Hue integration via MQTT

Now, in addition to the existing Hue-MQTT integration, iTunes-MQTT integration is also possible. All you have to do now is write and run code that has the following features:

--Subscribe to iTunes topics to get information about the song currently playing --Throw to Hue topic according to the information of the song being played

Now this is the code.

GGG.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt
import json

TOPIC_BASE = 'xxxx'
MQTT_HOST = 'xxxx'
MQTT_PORT = xxxx
MQTT_USERNAME = 'xxxx'
MQTT_PASSWORD = 'xxxx'
HUE_BRIDGE_ID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
HUE_LIGHT_ID = x

def on_connect(client, userdata, flags, rc):
    client.subscribe('{}/itunes/+/current'.format(TOPIC_BASE))

def on_message(client, userdata, msg):
    song = json.loads(msg.payload)
    print('Changed(iTunes): {}'.format(msg.payload.decode('unicode_escape').encode('utf8')))
    color = get_hue_color_for_itunes(song)
    print('Change(Hue): {}'.format(color))
    client.publish('{base}/hue/{bridge}/light/{light}/status'.format(base=TOPIC_BASE, bridge=HUE_BRIDGE_ID, light=HUE_LIGHT_ID), payload=json.dumps(color))

def get_hue_color_for_itunes(song):
    if song['state'] == 'playing':
        if 'track_album' in song and u'The King of Braves' in song['track_album']:
            return {"on": True, "saturation": 253, "brightness": 218, "hue": 47125}
        if 'track_name' in song and u'The King of Braves' in song['track_name']:
            return {"on": True, "saturation": 253, "brightness": 218, "hue": 47125}
        if 'track_artist' in song and u'Endo' in song['track_artist'] and u'Masaaki' in song['track_artist']:
           return {"on": True, "saturation": 253, "brightness": 218, "hue": 47125}
    return {"on": False, "saturation": 253, "brightness": 95, "hue": 47125}



mqtt_client = mqtt.Client()
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
mqtt_client.connect(MQTT_HOST, MQTT_PORT)

mqtt_client.loop_forever()

If the song is playing, Hue will be lit if the album name or track name contains "The King of Braves" or the artist name contains "Endo" or "Masaaki". Other than that, it is off.

An output example when this is moved.

Changed(iTunes): {"state": "playing", "track_name": "Birth of the Hero King!", "playlist_name": "Music", "track_album": "The King of Braves Gaogaigar-Original Soundtrack 1", "track_artist": "Masaaki Endoh"}
Change(Hue): {'on': True, 'saturation': 253, 'hue': 47125, 'brightness': 218}
Changed(iTunes): {"state": "playing", "track_name": "Kakushin-like ☆ Metamarufo-Ze!", "playlist_name": "Music", "track_album": "Kakushin-like ☆ Metamarufo-Ze! - EP", "track_artist": "Umaru Doma(CV:Aimi Tanaka)"}
Change(Hue): {'on': False, 'saturation': 253, 'hue': 47125, 'brightness': 95}

The King of Braves is born! Hue is turned on only when is started playing. Off when playback is started by someone other than the King of Braves, or when playback itself is stopped.

With this kind of feeling, ** I feel like the device is automatically controlled just by subscribing to MQTT messages and issuing messages ** without worrying about the details of each protocol. I'm trying to develop it. So that's it.

Recommended Posts

Try to link iTunes and Hue collection case with MQTT
Try to operate DB with Python and visualize with d3
Try to factorial with recursion
[pyqtgraph] Add region to the graph and link it with the graph region
Try to bring up a subwindow with PyQt5 and Python
Try to display google map and geospatial information authority map with python
[Python] Try to recognize characters from images with OpenCV and pyocr
Link to get started with python
Try to profile with ONNX Runtime
Try to output audio with M5STACK
Put Cabocha 0.68 on Windows and try to analyze the dependency with Python
Try converting latitude / longitude and world coordinates to each other with python
Try to make foldl and foldr with Python: lambda. Also time measurement
Try to separate the background and moving object of the video with OpenCV
Try to reproduce color film with Python
Try logging in to qiita with Python
Fractal to make and play with Python
Let's try gRPC with Go and Docker
Try to predict cherry blossoms with xgboost
Try converting to tidy data with pandas
Quickly try to visualize datasets with pandas
[AWS] Link Lambda and S3 with boto3
First YDK to try with Cisco IOS-XE
Try to generate an image with aliasing
Try to make BOT by linking spreadsheet and Slack with python 2/2 (python + gspread + slackbot)
Try to make BOT by linking spreadsheet and Slack with python 1/2 (python + gspread + slackbot)
WEB scraping with python and try to make a word cloud from reviews