Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

MQTT-Group3

#导入库 pip install paho-mqtt import paho.mqtt.client as mqtt import json import time import threading from datetime import datetime

MQTT 配置

MQTT_BROKER = "your_mqtt_broker" MQTT_PORT = 1883 MQTT_TOPIC_CONTROL = "home/lights/control" MQTT_TOPIC_STATUS = "home/lights/status"

PyAudio配置

FORMAT = pyaudio.paInt16 # 16位深度 CHANNELS = 1 # 单通道 RATE = 44100 # 采样率 CHUNK = 1024 # 缓冲区大小

def get_current_db(stream): """读取音频流并计算当前的分贝值""" data = np.frombuffer(stream.read(CHUNK), dtype=np.int16) rms = np.sqrt(np.mean(np.square(data))) db = 20 * np.log10(rms) return db

def set_brightness(client, brightness): """通过MQTT发布设置亮度的消息""" client.publish(MQTT_TOPIC_SET_BRIGHTNESS, brightness) print(f"Set brightness to {brightness}")

def on_message(client, userdata, msg): """处理收到的MQTT消息,设置智能灯带亮度""" try: brightness = int(msg.payload.decode()) set_brightness(client, brightness) except ValueError: print("Invalid brightness value received")

def main(): # 初始化MQTT客户端 client = mqtt.Client()

# 设置回调函数
client.on_message = on_message

# 连接到MQTT代理
client.connect(MQTT_BROKER, MQTT_PORT, 60)

# 订阅主题
client.subscribe(MQTT_TOPIC_SET_BRIGHTNESS)

# 启动MQTT客户端
client.loop_start()

# 初始化PyAudio
audio = pyaudio.PyAudio()

# 打开流
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)

try:
    while True:
        # 计算当前分贝值
        db = get_current_db(stream)
        
        # 将分贝值转换为亮度值
        brightness = int(min(max((db + 50) * 2, 0), 100))
        
        # 发布亮度值
        client.publish(MQTT_TOPIC_DB_BRIGHTNESS, brightness)
        print(f"Current dB: {db:.2f}, Adjusted brightness: {brightness}")

except KeyboardInterrupt:
    # 关闭流和MQTT客户端
    stream.stop_stream()
    stream.close()
    audio.terminate()
    client.loop_stop()
    client.disconnect()
    print("Exiting...")

if name == "main": main()