『瀚思彼岸』» 智能家居技术论坛

 找回密码
 立即注册
查看: 8452|回复: 4

[经验分享] 使用蓝牙扫描通过MQTT发布设备跟踪

[复制链接]

4

主题

20

帖子

136

积分

注册会员

Rank: 2

积分
136
金钱
116
HASS币
10
发表于 2021-1-13 10:53:20 | 显示全部楼层 |阅读模式
该方法是GitHub上大神写的Python脚本,这里只是搬运。
相信网上有很多这类的教程,这里的分享只是多一种参考。
使用场景上可以在家中放置多个不同区域的蓝牙扫描设备,防止单个设备扫描区域有限,误报为离开。
我使用的是树莓派3b的设备,不知为何无法识别树莓派自带的蓝牙设备。所以使用了USB接口的蓝牙。通过蓝牙扫描,将蓝牙的MAC地址判断是否找到,找到则使用MQTT在某一个主题上发布一条消息
使用方法:
二、树莓派上操作
apt install bluetooth python-bluez libbluetooth-dev python3-pip
python3 -m pip install pybluez paho-mqtt


创建脚本与自启动服务

创建扫描脚本
/root/script/bt_tracker.py
#!/usr/bin/python3
#
#   Bluetooth Device Tracking MQTT Client for Raspberry Pi (or others)
#
#   Version:    0.1
#   Status:     Development
#   Github:     https://github.com/robmarkoski/bt-mqtt-tracker
# 

import os
import time
import logging

import bluetooth
import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt

# Add the name and Mac address of the each device. The name will be used as part of the state topic.
devices = [
#修改相应的蓝牙地址,使用其它方法找到,已经你想要的设备名
    {"name": "xxx", "mac": "aa:bb:cc:dd:00:11", "state": "not home"},
    {"name": "yyy", "mac": "aa:bb:cc:dd:00:11", "state": "not home"}
    ]

# Provide name of the location where device is (this will form part of the state topic)
LOCATION = "Home"  #此处可以作为不同的区域,这里将改变mqtt主题的发布

# The final state topic will therefore be: HomeAssistant/Presence/LOCATION/DEVICE_NAME

# Update the follow MQTT Settings for your system.
MQTT_USER = "username"              # MQTT Username    #MQTT服务器的用户名
MQTT_PASS = "password"     # MQTT Password      #MQTT服务器的密码
MQTT_CLIENT_ID = "bttracker"    # MQTT Client Id
MQTT_HOST_IP = "127.0.0.1"      # MQTT HOST
MQTT_PORT = 1883                # MQTT PORT (DEFAULT 1883)


SCAN_TIME = 30  # Interval Between Scans    #扫描间隔
BLU_TIMEOUT = 4 # How long during scan before there is a timeout.

# Set up logging.
LOG_NAME = "bt_tracker.log"      # Name of log file
LOG_LEVEL = logging.NOTSET       # Change to DEBUG for debugging. INFO For basic Logging or NOTSET to turn off


# SHOULDNT NEED TO CHANGE BELOW
MQTT_AUTH = {
    'username': MQTT_USER,  
    'password': MQTT_PASS  
}
LOG_FORMAT = "%(asctime)-15s %(message)s"
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) + "/"
LOG_FILE = SCRIPT_DIR + LOG_NAME
logging.basicConfig(filename=LOG_FILE,
                    level=LOG_LEVEL,
                    format=LOG_FORMAT,
                    datefmt='%Y-%m-%d %H:%M:%S')

try:
    logging.info("Starting BLE Tracker Server")
    while True:
        for device in devices:
            mac = device['mac']
            logging.debug("Checking for {}".format(mac))
            result = bluetooth.lookup_name(mac, timeout=BLU_TIMEOUT)
            if result:
                device['state'] = "home"
                logging.debug("Device Found!")
            else:
                device['state'] = "not home"
                logging.debug("Device Not Found!")
            try:
                publish.single("HomeAssistant/bluetooth/" + LOCATION + "/" + device['name'], #发布的主题,无需修改,由变量组成
                    payload=device['state'],
                    hostname=MQTT_HOST_IP,
                    client_id=MQTT_CLIENT_ID,
                    auth=MQTT_AUTH,
                    port=MQTT_PORT,
                    protocol=mqtt.MQTTv311)
            except:
                logging.exception("MQTT Publish Error")
        time.sleep(SCAN_TIME)
except KeyboardInterrupt:
    logging.info("KEY INTERRUPT - STOPPING SERVER")
except:
    logging.exception("BLUETOOTH SERVER ERROR")
为该脚本添加执行权限
chmod +x /root/script/bt_tracker.py
编写开机自启动,作为服务

/etc/systemd/system/bttracker.service
[Unit]
Description=Raspberry Pi Device Tracker MQTT Service
After=network.target

[Service]
Type=idle
User=root
ExecStart=/usr/bin/python3 /root/script/bt_tracker.py
Restart=always

[Install]
WantedBy=multi-user.target
启动服务
systemctl enable bluetooth
systemctl start bluetooth
systemctl daemon-reload
systemctl enable bttracker.service
systemctl start bttracker.service



三、HomeAssistant上添加配置
device_tracker:
  - platform: mqtt
    devices:
      iPhoneXR: "HomeAssistant/bluetooth/Home/xxx" #设备名:主题
      oppor11: "HomeAssistant/bluetooth/Home/yyy"
    qos: 1
    payload_home: 'home'
    payload_not_home: 'not home'
    source_type: bluetooth
重启HomeAssistant服务

评分

参与人数 1金钱 +20 HASS币 +10 收起 理由
+ 20 + 10 感谢楼主分享!

查看全部评分

回复

使用道具 举报

77

主题

1391

帖子

2万

积分

元老级技术达人

积分
24349
金钱
22918
HASS币
290
发表于 2021-1-13 17:53:38 | 显示全部楼层
没有树莓派,esp32移植版会现出江湖吗?
回复

使用道具 举报

0

主题

22

帖子

351

积分

中级会员

Rank: 3Rank: 3

积分
351
金钱
329
HASS币
0
发表于 2021-1-13 20:16:17 | 显示全部楼层
斐讯N1能用吗
回复

使用道具 举报

4

主题

20

帖子

136

积分

注册会员

Rank: 2

积分
136
金钱
116
HASS币
10
 楼主| 发表于 2021-1-13 21:54:45 | 显示全部楼层

N1能装linux系统,以及有蓝牙设备。是可以的。主要是Python环境软件包要安装。
回复

使用道具 举报

4

主题

20

帖子

136

积分

注册会员

Rank: 2

积分
136
金钱
116
HASS币
10
 楼主| 发表于 2021-1-13 21:56:09 | 显示全部楼层
dscao 发表于 2021-1-13 17:53
没有树莓派,esp32移植版会现出江湖吗?

可能会,等我学会了共享出来。应该不难
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Hassbian

GMT+8, 2024-11-26 18:35 , Processed in 0.246337 second(s), 28 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表