หน้าเว็บ

วันพฤหัสบดีที่ 8 ตุลาคม พ.ศ. 2563

Listening to intents over MQTT using Python

 ที่มา: https://snips.gitbook.io/tutorials/t/technical-guides/listening-to-intents-over-mqtt-using-python

Listening to intents over MQTT using Python

In this tutorial, you will learn how to create a standalone Python application that listens to various events coming from the Snips Platform, in the form of MQTT messages.

In this tutorial, you will learn how to create a standalone Python application that listens to various events coming from the Snips Platform, in the form of MQTT messages.

The Hermes protocol

The Snips Hermes Protocol is the set of messages and exchange of messages between the various components of the Snips Platform. The messages are MQTT messages. The figure below describes the flow of messages during a simple voice interaction session.

You will most likely be interested in the following messages:

  • hermes/hotword/<hotword_id>detected: when a wakeword is detected, this message will be sent, and Snips will listening to your voice command. You can for instance use this message to play a little tone, or start a led animation, indicating the start of a listening session

  • hermes/asr/textCaptured: when listening, Snips will transcribe your query into text, and after a small period of silence, it will stop listening, and send this message. You may use this to play another tone, or stop a led animation, indicating end of listening

  • hermes/intent/<intent_name>: after text has been captured, the NLU module will process the text and transform it into an intent, which is the final representation of your query that you can use as an actionable item. This is where you want to put your intent handler code

Listening to MQTT events

When launched, Snips starts an MQTT broker that it uses to broadcast the above MQTT messages. We can connect to this broker using the paho-mqtt library:

$ pip install paho-mqtt

The connection code looks as follows, replacing MQTT_BROKER_HOSTNAME with your broker hostname or IP:

import paho.mqtt.client as mqtt
HOST = 'raspi3-mika2.local'
PORT = 1883
def on_connect(client, userdata, flags, rc):
print("Connected to {0} with result code {1}".format(HOST, rc))
def on_message(client, userdata, msg):
print("Message received on topic {0}: {1}"\
.format(msg.topic, msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST, PORT, 60)
client.loop_forever()

Detecting a wakeword

When a wakeword is detected, a message is sent on the hermes/hotword/<hotword_id>/detected topic, where hotword_id is the ID of your wakeword. The default value is default, which we will use here. We extend the above example to detect a wakeword and trigger an action as follows:

def on_connect(client, userdata, flags, rc):
print("Connected to {0} with result code {1}".format(HOST, rc))
# Subscribe to the hotword detected topic
client.subscribe("hermes/hotword/default/detected")
def on_message(client, userdata, msg):
if msg.topic == 'hermes/hotword/default/detected':
print("Wakeword detected!")

Handling intents

We now extend our example to also trigger and action when an intent is detected by the NLU component. In this case, a message is sent on the hermes/intent/INTENT_NAMEtopic, where INTENT_NAME is the name of our intent.

def on_connect(client, userdata, flags, rc):
print("Connected to {0} with result code {1}".format(HOST, rc))
# Subscribe to the hotword detected topic
client.subscribe("hermes/hotword/default/detected")
# Subscribe to intent topic
client.subscribe('hermes/intent/INTENT_NAME')
def on_message(client, userdata, msg):
if msg.topic == 'hermes/hotword/default/detected':
print("Hotword detected!")
elif msg.topic == 'hermes/intent/INTENT_NAME':
print("Intent detected!")

Wildcard topics

We don’t have to manually subscribe to the topic for each intent. If we want to trigger an action when receiving any intent, we can simply subscribe to the wildcard topic hermes/intent/#:

def on_connect(client, userdata, flags, rc):
# Subscribe to any topic starting with 'hermes/intent/'
client.subscribe('hermes/intent/#')

Accessing intent parameters

In the following example, when receiving an intent, we parse the payload to extract the slots associated with our intent:

import json
def on_message(client, userdata, msg):
if msg.topic == 'hermes/intent/lightsTurnOnSet':
payload = json.loads(msg.payload)
name = payload["intent"]["intentName"]
slots = payload["slots"]
print("Intent {0} detected with slots {1}"\
.format(name, slots))

This completes the basic tutorial on how to write an MQTT client in Python that triggers actions upon receiving wakewords and intents from the Snips platform.

How To: Connect your Raspberry Pi to WiFi

 ที่มา: https://raspberrypihq.com/how-to-connect-your-raspberry-pi-to-wifi/

Getting your network information

For the purpose of this guide we will be connecting to a WiFi network with the following information:

  • SSID (Network Name): Test Wifi Network
  • PSK (Password): SecrectPassWord

Every time you see this network name and password in the guide you need to change them to the network name and password of your local network.

If you need to find the network name of your local network you can run the following command in the Raspberry terminal:

sudo iwlist wlan0 scan

This will list all the networks in your vicinity along with some useful information for each network. To find your network name look for something that look like: ESSID:”Test Wifi Network”.

Configuring your WiFi network

To tell the Raspberry Pi to automatically connect to your WiFi network you need to edit a file called: wpa_supplicant.conf.

To open the file in nano type the following command:

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

Scroll to the end of the file and add the following to the file to configure your network:

network={
   ssid="Test Wifi Network"
   psk="SecretPassWord"
}

Remember to replace this with your own network name and password.

Save and close the file by pressing Ctrl+X followed by Y. At this point the Raspberry Pi should automatically connect to your network.

You can check your network connection by running the following command:

ifconfig wlan0

If the output looks something like this (with an inet addr) you are connected:

wlan0   Link encap:Ethernet HWaddr 74:da:38:2b:1c:3d
        inet addr:192.168.1.216 Bcast:192.168.1.255 Mask:255.255.255.0
        inet6 addr: fe80::8727:5526:a190:b339/64 Scope:Link
        UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
        RX packets:6917 errors:0 dropped:229 overruns:0 frame:0
        TX packets:2931 errors:0 dropped:1 overruns:0 carrier:0
        collisions:0 txqueuelen:1000
        RX bytes:10001000 (9.5 MiB) TX bytes:295067 (288.1 KiB)

Sometimes the Raspberry Pi will not connect automatically and require a reboot to connect.

If it doesn’t connect after waiting 2-3 minutes try to reboot the pi using the following command:

sudo reboot

วันอาทิตย์ที่ 4 ตุลาคม พ.ศ. 2563

Time Zone

 ubuntu 14.04 ขึ้นไปจะมีคำสั่งใหม่คือ timedatectl สำหรับจัดการ timezone ของระบบ สำหรับการตั้งค่า timezone เป็น Asia/Bangkok ให้ใช้คำสั่งดังนี้

  1. sudo timedatectl set-timezone Asia/Bangkok

วันพฤหัสบดีที่ 1 ตุลาคม พ.ศ. 2563

MQTT Connect

import paho.mqtt.client as mqtt


mqtt_username = "USER"

mqtt_password = "PASSWORD"

mqtt_topic = "TOPIC"

mqtt_broker_ip = "MQTT SERVER"


client = mqtt.Client()

client.username_pw_set(mqtt_username, mqtt_password)


def on_connect(client, userdata, flags, rc):

    print ("Connected!", str(rc))

    client.subscribe(mqtt_topic)


def on_message(client, userdata, msg):

    print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))


client.on_connect = on_connect

client.on_message = on_message

client.connect(mqtt_broker_ip, 1883)

client.publish(mqtt_topic, payload="test", retain=True)


# Once we have told the client to connect, let the client object run itself

client.loop_forever()

client.disconnect() 

SHT10 Sensor

ที่มา : https://community.mydevices.com/t/sht10-sensor/2450 

Wiring the SHT10 Sensor:

Red Wire - to 3.3V
Green Wire - to GND
Blue Wire(Data) to PIN23
Yellow Wire(Clock) to PIN24

Important: Use 10K pullUp resistor from VCC(Red Wire) to DATA(Blue Wire).

Install Library:

I use this library:

pip3 install pi-sht1x

if there is error, you have to uprade the pip3 with the following command:
sudo easy_install3 -U pip

Also before start writing your python code, you have to install paho-mqtt for python3

sudo pip3 install paho-mqtt

Go to Cayenne Dashboard -> Add New -> Devices & Widgets and press the big blue button Add Your Own Thing

Then copy your MQTT Username, MQTT Password and Cliend ID to the following places in the code:

import paho.mqtt.client as mqtt
import time
import sys
from time import sleep
from pi_sht1x import SHT1x
import RPi.GPIO as GPIO
import datetime

#time.sleep(60) #Sleep to allow wireless to connect before starting MQTT

mqttc = mqtt.Client(client_id="YOUR CLIENT ID")
mqttc.username_pw_set("YOUR USERNAME", password="YOUR PASSWORD")
mqttc.connect("mqtt.mydevices.com", port=1883, keepalive=60)
topic_sht10_temp = "v1/YOUR USERNAME/things/CLIENT ID/data/1"
topic_sht10_humidity = "v1/YOUR USERNAME/things/CLIENT ID/data/2"
while True:
        try:
                with SHT1x(23, 24, gpio_mode=GPIO.BCM) as sensor:
                    temp11 = sensor.read_temperature()
                    humidity11 = sensor.read_humidity(temp11)
                if temp11 is not None:
                        temp11 = "temp,c=" + str(temp11)
                        mqttc.publish(topic_sht10_temp, payload=temp11, retain=True)
                if humidity11 is not None:
                        humidity11 = "rel_hum,p=" + str(humidity11)
                        mqttc.publish(topic_sht10_humidity, payload=humidity11, retain=True)
                        sleep(5)
                time.sleep(5)
        except (EOFError, SystemExit, KeyboardInterrupt):
                mqttc.disconnect()
                sys.exit()

Save and run the file using:

sudo python3 yourfilename.py