【求助】用python写了一个软件关机程序,可以用,但,homeAssistant提示没有unique ID 。求助!!!貌似没有unique ID ,每次重启就会改变身份,有点恼火
try:
import paho.mqtt.client as mqtt
except ImportError:
print("请运行 “pip install paho-mqtt” 安装MQTT模块")
exit(1)
import os
import socket
import platform
# pip install paho-mqtt
# MQTT连接参数
mqtt_broker = "192.168.10.1"
mqtt_port = 1883
# MQTT回调函数,接收远程控制指令
def on_message(client, userdata, msg):
message = msg.payload.decode().lower()
# print("收到message:%s" % message)
if message == "shutdown" or message == "off":
print("收到关闭指令,系统即将关闭...")
if platform.system() == "Windows":
os.system("shutdown -s -t 0")
else:
os.system("shutdown -h now")
# MQTT连接成功回调函数
def on_connect(client, userdata, flags, rc):
# 订阅该设备的唯一主题
myip = get_unique_id()
raw_topic = "homeassistant/switch/" + myip
publish = raw_topic + "/config"
subscribe = raw_topic + "/set"
print("成功连接到MQTT代理\n 订阅主题 - %s" % subscribe)
c = '{"name": "pcshutdownScript_%s", "command_topic": "%s", "state_topic": "%s/state"}' % (myip, subscribe, raw_topic)
client.publish(publish, c) # 发布连接成功消息
client.subscribe(subscribe) # 订阅主题
# 获取设备的唯一标识符
def get_unique_id():
# 这里使用设备的IP地址作为唯一标识符,
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 必须随便链接到一个真实存在的ip来获取自己的ip否则可能是一个172的ip地址
s.connect((mqtt_broker, mqtt_port))
client_address = s.getsockname()[0]
s.close()
return client_address.replace(".", "_") # mqtt服务器不支持.的信息发布,所以需要替换掉
if __name__ == "__main__":
# 创建MQTT客户端
client = mqtt.Client()
# client.username_pw_set("admin", "admin") # 设置MQTT用户名和密码
# 设置MQTT回调函数
client.on_connect = on_connect
client.on_message = on_message
# 连接到MQTT代理
client.connect(mqtt_broker, mqtt_port, 60)
# 循环监听MQTT消息
client.loop_forever()
|