WyzeSense and MQTT

Posted on
Fri Aug 30, 2019 6:55 pm
FlyingDiver offline
User avatar
Posts: 7189
Joined: Jun 07, 2014
Location: Southwest Florida, USA

WyzeSense and MQTT

Continuation of discussion from: viewtopic.php?f=132&t=22822

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Posted on
Fri Aug 30, 2019 7:14 pm
FlyingDiver offline
User avatar
Posts: 7189
Joined: Jun 07, 2014
Location: Southwest Florida, USA

Re: WyzeSense and MQTT

First, download this project to your rPi: https://github.com/HclX/WyzeSensePy

You only need the wyzesense folder and sample.py. Put those in a handy directory. Then copy this code and put it in a file called wyze-mqtt.py (or anything you want, really) in the same directory.
Code: Select all
#!/usr/bin/env python

"""Example of using WyzeSense USB bridge.

**Usage:** ::
  sample.py [options]

**Options:**

    -d, --debug         output debug log messages to stderr
    -v, --verbose       print and log more information
    --device PATH       USB device path [default: /dev/hidraw0]
    --broker Address    IP address or hostname of MQTT Broker

**Examples:** ::

  sample.py --device /dev/hidraw0   # Using WyzeSense USB bridge /dev/hidraw0

"""
#from __future__ import print_function
#from builtins import input
#import os
import re
import sys
import logging
import errno
import binascii
import time
import json

import wyzesense

import paho.mqtt.client as mqtt

mqtt_client = None

def on_event(ws, e):
    global mqtt_client

    if e.Type == 'state':
        print("StateEvent: sensor_type=%s, state=%s, battery=%d, signal=%d" % e.Data)
        topic = "wyzesense/{}/update".format(e.MAC)
       
        payload = {
            "sensor_type" : e.Data[0],
            "state" : e.Data[1],
            "battery" : e.Data[2],
            "signal" : e.Data[3]
        }
        mqtt_client.publish(topic, json.dumps(payload), 0, False)

 
def main(args):
    global mqtt_client
   
    if args['--debug']:
        loglevel = logging.DEBUG - (1 if args['--verbose'] else 0)
        logging.getLogger("wyzesense").setLevel(loglevel)
        logging.getLogger().setLevel(loglevel)

    device = args['--device']
    print("Opening wyzesense gateway [{}]".format(device))
    try:
        ws = wyzesense.Open(device, on_event)
        if not ws:
            print("Open wyzesense gateway failed")
            return 1
        print("Gateway info:")
        print("\tMAC:%s" % ws.MAC)
        print("\tVER:%s" % ws.Version)
        print("\tENR:%s" % binascii.hexlify(ws.ENR))
    except IOError:
        print("No device found on path %r" % device)
        return 2
   
    broker_addr = args['--broker']
    mqtt_client = mqtt.Client(client_id="wyze-mqtt-{}".format(ws.MAC), clean_session=True, userdata=None, protocol=4, transport="tcp")

    try:
        mqtt_client.connect(broker_addr, 1883, 60)
    except:
        print("Unable to connect to mqtt broker @ {}:1883".format(broker_addr))
        return 2

    try:
        while True:
            time.sleep(.1)
    finally:
        ws.Stop()

    return 0


if __name__ == '__main__':
    logging.basicConfig(format='%(levelname)s %(asctime)s %(message)s')

    try:
        from docopt import docopt
    except ImportError:
        sys.exit("the 'docopt' module is needed to execute this program")

    # remove restructured text formatting before input to docopt
    usage = re.sub(r'(?<=\n)\*\*(\w+:)\*\*.*\n', r'\1', __doc__)
    sys.exit(main(docopt(usage)))

Code: Select all
pi@raspberrypi:~/WyzeSensePy $ ls -la
total 20
drwxr-xr-x  3 pi pi 4096 Aug 30 21:15 .
drwxr-xr-x 17 pi pi 4096 Aug 30 16:37 ..
-rwxr-xr-x  1 pi pi 3796 Aug 24 20:16 sample.py
-rwxr--r--  1 pi pi 3338 Aug 30 18:04 wyze-mqtt.py
drwxr-xr-x  3 pi pi 4096 Aug 24 20:27 wyzesense

Also, you need Python3 installed on the rPi. I think I did it with "apt install Python3". Once you have that installed, do "pip3 install paho-mqtt".

Then install the Wyze dongle on the rPi. Look to see if the device is created:

Code: Select all
pi@raspberrypi:~/WyzeSensePy $ ls -l /dev/hidraw*
crw-rw-r-- 1 root pi 245, 0 Aug 30 13:17 /dev/hidraw0


Then, run the sample.py file, you should get something like:
Code: Select all
pi@raspberrypi:~/WyzeSensePy $ python3 sample.py
Openning wyzesense gateway ['/dev/hidraw0']
Gateway info:
   MAC:7781E59E
   VER:0.0.0.30 V1.4 Dongle UD3U
   ENR:b'1546866884c76deae03f2fc3bf2c3976'
L to list
P to pair
U to unpair
X to exit
Action:


If there's more than one hidraw device, you can try specifying them like:
Code: Select all
pi@raspberrypi:~/WyzeSensePy $ python3 sample.py --device /dev/hidraw1


If that all works, enter "L" to list the sensors paired to the dongle. If they're not paired, enter "P", then use a pin to press the button in the little tiny hole on the side of the sensor until the red light flashes. Wait and you'll get something like:

Code: Select all
Sensor found: mac=778D7280, type=1, version=16
L to list
P to pair
U to unpair
X to exit


Make a note of that mac number, it's the identifier for that specific sensor. Repeat as needed. If you have the three sensors that came in the starter kit, eventually pressing L will get you a list of the three:

Code: Select all
Action:l
3 sensor paired:
   Sensor: 778D7038
   Sensor: 7781A40B
   Sensor: 778D7280
L to list
P to pair
U to unpair
X to exit


Now X to exit that program.

Now start up the bridge program with:

Code: Select all
python3 wyze-mqtt.py --broker <<IP address of your MQTT Broker>>


You can add "--device /dev/xxxx" if needed.

You'll get the same Gateway info that sample.py gave you. If you trigger one of the sensors, you'll see something like:

Code: Select all
pi@raspberrypi:~/WyzeSensePy $ python3 wyze-mqtt.py --broker 192.168.111.20
Opening wyzesense gateway [/dev/hidraw0]
Gateway info:
   MAC:7781E59E
   VER:0.0.0.30 V1.4 Dongle UD3U
   ENR:b'1546866884c76deae03f2fc3bf2c3976'
StateEvent: sensor_type=switch, state=open, battery=96, signal=80
StateEvent: sensor_type=switch, state=close, battery=96, signal=82


Which means it's working. Now you need to look at your MQTT Broker. You'll see messages like:

Code: Select all
Topic = wyze/778D7038/update
Payload = {"sensor_type": "switch", "state": "close", "battery": 96, "signal": 86}


Subscribe to that with MQTT Connector and set up a Shim device to monitor the "state" value.

Done.

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Posted on
Sat Aug 31, 2019 4:17 am
ChopOMatic offline
Posts: 110
Joined: Sep 12, 2014

Re: WyzeSense and MQTT

Thx, Joe. Can't wait to set it up and play with it. Will advise.


Sent from my iPad using Tapatalk

Posted on
Mon Dec 21, 2020 10:15 pm
diefledermaus offline
Posts: 17
Joined: Feb 07, 2015

Re: WyzeSense and MQTT

jI just found this recently I do not know if it changes anything

https://github.com/libusb/hidapi

Posted on
Tue Dec 22, 2020 6:42 am
FlyingDiver offline
User avatar
Posts: 7189
Joined: Jun 07, 2014
Location: Southwest Florida, USA

Re: WyzeSense and MQTT

I'm not actually using the Wyze gear anymore. I switched to Z-wave because of the variety of sensors.

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 1 guest