I have successfully installed opencv and can broadcast on localhost pc, but I failed to connect the opencv that I installed on the PC, with the home assistant server that I installed on the raspberry pi 4 via mqtt. I only want to broadcast face_id so as not to burden the performance of my raspberry pi4. Next in the home assistant I added the “Face Recognition ID”
mqtt:
sensor:
- name: "Face Recognition ID"
state_topic: "face_recognition/id"
value_template: "{{ value_json.face_id }}"
then in opencv I added the following code:
import paho.mqtt.client as mqtt
import json
# Konfigurasi MQTT
broker = "localhost" # Ganti dengan IP Raspberry Pi Anda jika perlu
port = 1883 # Port default untuk MQTT
topic = "face_recognition/id" # Topik untuk mengirim ID
# Fungsi callback saat terhubung ke broker
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Terhubung ke broker dengan hasil kode: " + str(rc))
else:
print("Gagal terhubung, hasil kode: " + str(rc))
# Membuat client MQTT
client = mqtt.Client(client_id="", clean_session=True, userdata=None, protocol=mqtt.MQTTv311)
client.on_connect = on_connect
# Mengatur username dan password untuk otentikasi
client.username_pw_set("jhondoe", "1234") # Ganti dengan username dan password yang sesuai
# Menghubungkan ke broker
client.connect(broker, port, 60)
# Fungsi untuk mengirim ID wajah
def send_face_id(face_id):
payload = {
"face_id": face_id
}
client.publish(topic, json.dumps(payload))
print(f"ID wajah {face_id} telah dikirim ke topik {topic}")
# Contoh penggunaan
if __name__ == "__main__":
client.loop_start() # Memulai loop untuk mendengarkan pesan
try:
while True:
face_id = input("1,2,3,4, (atau 'exit' untuk keluar): ")
if face_id.lower() == 'exit':
break
send_face_id(face_id)
except KeyboardInterrupt:
pass
finally:
client.loop_stop() # Menghentikan loop
client.disconnect() # Memutuskan koneksi
the second problem is the status of the “Face Recognition ID” sensor is always Unknown. thank you