How to use sango - Python

I will explain how to use sango from Python.

To use sango in Ruby, follow the procedure below.

  1. Install libraries with pip
  2. Client implementation

Confirmed environment

  • Python 2.7.8
  • Paho-mqtt 1.0

1. Install libraries with pip

In python paho-mqtt use. It should be noted that, mosquitto but there is also the library, so we already have development finished, please note.

pip install paho-mqtt

2. Client implementation

mqtt.Client() in to create an instance of the MQTT client, and connect if run connect. Since the default is to be connected at 3.1 MQTT, protocol giving the argument that will be connected in the 3.1.1.

After connect the get or perform Subscribe in, publish or you can go to Publish in.

Connect

The Connect part is common to both Pub / Sub.

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

import paho.mqtt.client as mqtt

MQTTHOST = "free.mqtt.shiguredo.jp"
USERNAME = "example@github"
PASSWORD = "password"

# 3.1.1用のClientを作成します
client = mqtt.Client(protocol=mqtt.MQTTv311)
# ユーザー名とパスワードを設定します
client.username_pw_set(USERNAME, PASSWORD)

# 接続します
client.connect(MQTTHOST)

Subscribe

TOPIC = "shirou@github/a/b"
# Subscribeします
client.subscribe(TOPIC)

# メッセージを待ち受けるループに入ります
client.loop_forever()

Publish

TOPIC = "shirou@github/a/b"
# Publishします
client.publish(TOPIC, "message from python")

# そのままだとすぐにプロセスが終了してしまいますので、Publishし終わるまで待ちます
import time
time.sleep(0.05)