Python 3 – die besten Beiträge

Wo ist der Fehler in meinem Python Code (MQTT)?

Ich habe ein Python Script erstellt, damit später bei Nachrichten bestimmte befehle ausgeführt werden. Beim ersten Script(Openhab_Mqtt.py) habe ich beim Testen 3 Terminals aufgemacht und beim 2.(Openhab_Mqttv2.py) auch genau gleiche Sorgehensweise.

Im 1. Terminal habe ich das Python Script gestartet mit:

python Openhab_Mqttv2.py

Output:
Script 1: Connected to MQTT broker
Script 2: Connected to MQTT broker
Connected to MQTT broker

Im 2. Terminal habe ich die Nachricht ausgegeben bei Nachrichten mit:

mosquitto_sub -t "main/messager" -v -u xxx -P xxx

Output(Nach T3):
Script 1: main/messager test
Script 2: main/messager test

Und im 3. Terminal habe ich eine Nachricht gesendet mit:

mosquitto_pub -t "main/messager" -m "test" -u xxx-P xxx  

Output:
Script 1: Payload: test und BLA...
Script 2:

Ich kann einfach nicht den Fehler finden, warum es bei Openhab_Mqtt.py funktioniert und bei Openhab_Mqttv2.py nicht funktioniert.

Openhab_Mqtt.py DATA:

import paho.mqtt.client as mqtt
import os
import time
import bme280_temp
import smbus2
import bme280
import threading

def on_subscribe(client, userdata, mid, granted_qos):
 print("Subscribed to topic : " + str(mid) +" with QoS" + str(granted_qos))


def on_connect(client, userdata, flags, rc):
 print("Connected to MQTT broker")


def on_message(client, userdata, msg): 
 print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
 print("Payload: " + msg.payload.decode())
 if msg.payload.decode() == "send_signal":
  print("Calling script to send signal...")
  IR_Signal()
 if msg.payload.decode() == "temp_bme280_start":
  print("Calling script to for temperature start...")
  userdata["counter"] += 1
  print(str(userdata["counter"]))
  client.publish("frame/monitor", "START", qos=0, retain=True)
  Temp_sensor() 
 if msg.payload.decode() == "temp_bme280_stop":
  print("Calling script to for temperature stop...")
  userdata["counter"] -= 1
  print(str(userdata["counter"]))
  client.publish("frame/monitor", "STOP", qos=0, retain=True)
 if msg.payload.decode() == "test":
  print("BLA...")  
  print(str(["counter"])) 
  os.system("vcgencmd measure_temp") 
 else:
  pass    



#Bme280_basic Temperature
address = 0x76
bus = smbus2.SMBus(1)
calibration_params = bme280.load_calibration_params(bus, address)

def Temp_sensor():
 data = bme280.sample(bus, address, calibration_params)
 temperature_celsius = data.temperature      
 print("Temperature: {:.2f} °C".format(temperature_celsius))
 time.sleep(2)
    
 
def IR_Signal():
 os.system("irsend SEND_ONCE pioneer_vsx-301 KEY_POWER")
 print ("Signal Send!")


client = mqtt.Client()
client.on_message = on_message 
client.on_connect = on_connect
client.user_data_set({"counter": 0})
client.username_pw_set( "xx" , "xx" )
client.connect( "192.x.x.x", 1883, 60)
client.subscribe( "main/messager" , qos=0)


client.loop_forever() 

Openhab_Mqttv2.py

import paho.mqtt.client as mqtt
import time
import smbus2
import bme280
import threading


# Getting information
def on_subscribe(client, userdata, mid, granted_qos):
 print("Subscribed to topic : " + str(mid) +" with QoS" + str(granted_qos))
                                                                 
def on_connect(client, userdata, flags, rc):
 print("Connected to MQTT broker")


# Damit loops nicht am anfang durchstarten 
TempLoop_running = False


# Checking for messages to execute code
def on_message(client, userdata, msg):
 print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
 print("Payload: " + msg.payload.decode())
 if msg.payload.decode() == "Temp_Start":
  start_TempLoop()
 if msg.payload.decode() == "Temp_Stop":
  stop_TempLoop()
 if msg.payload.decode() == "test":
  print("TESTING...")
  client.publish("main/messager", "START", qos=0, retain=True)
 else:
  pass



# Execute things here ->


# Getting Temperature
address = 0x76
bus = smbus2.SMBus(1)
# Load calibration parameters
calibration_params = bme280.load_calibration_params(bus, address)
def Temperature_loop():
 global TempLoop_running
 while TempLoop_running:
  data = bme280.sample(bus, address, calibration_params)
  #Extract temperature, pressure, and humidity
  temperature_celsius = data.temperature      
  #Print the readings
  print("Temperature: {:.2f} °C".format(temperature_celsius))
  # Nachricht an das entsprechende Topic senden
  client.publish("Temp/Loop", "Temperature: {:.2f} °C".format(temperature_celsius))
  # Wartezeit, um die Ausgabe zu verlangsamen
  time.sleep(2)
# Funktion zum Starten der Temperatur Schleife
def start_TempLoop():
 global TempLoop_running
 TempLoop_running = True
 threading.Thread(target=Temperature_loop).start()
# Funktion zum Stoppen der Temperatur Schleife
def stop_TempLoop():
 global TempLoop_running
 TempLoop_running = False



# Set general data
client = mqtt.Client()
client.on_message = on_message 
client.on_connect = on_connect
client.connect( "192.x.x.x", 1883, 60)
client.username_pw_set( "xx", "xx" )
client.subscribe( "main/messager", qos=0)


# Loop forever
client.loop_forever()
Code, Python, Terminal, Message, Python 3, Raspberry Pi, mqtt

Warum funktioniert mein Code auf dem Raspberry Pi nicht?

Hallo,

Ich programmiere gerade einen Sprachassistenten und auf meinem Windows PC hat alles super funktioniert, aber als ich das Programm auf den Pi geladen und das Programm gestartet habe, kam diese Fehlermeldung:

Traceback (most recent call last):

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/main.py", line 1164, in <module>

  execute()

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/main.py", line 658, in execute

  if detect_wake_word(): # Falls das Wake-Word erkannt wurde

    ^^^^^^^^^^^^^^^^^^

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/main.py", line 139, in detect_wake_word

  recognizer.adjust_for_ambient_noise(source) # Hintergrundgeräusche anpassen

  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/.venv/lib/python3.11/site-packages/speech_recognition/__init__.py", line 389, in adjust_for_ambient_noise

  assert source.stream is not None, "Audio source must be entered before adjusting, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"

      ^^^^^^^^^^^^^^^^^^^^^^^^^

AssertionError: Audio source must be entered before adjusting, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?

Ich habe ein gutes Mikrofon am Pi, welches auch funktioniert, und ich habe schon viel am Code geändert, aber es geht nicht weg. Woran kann das sonst liegen?

Wenn ich Teile meines Codes zeigen soll, könnt ihr das sagen.

Freundliche Grüsse

cmd, Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Raspberry Pi, Pycharm, ChatGPT

Python variable ändern (erhöhen oder verringern)?

Ich bin ein absoluter Anfänger was programmieren angeht, lerne aber immer mehr und mehr dazu. Ich möchte für etwas ein Python Script erstellen, was auf meinem Pi die ganze Zeit läuft und die MQTT Nachrichten mitliest, um diese auszuführen und/oder eine Nachricht zurück zu senden.

Ich habe versucht eine Nachricht zu senden der den wert der Variable um 1 erhöhen soll und damit auch die While schleife aktivieren soll. Jedoch funktioniert es nicht, da die variable nicht in "def on_message" verfügbar ist und es die Erhöhung quasi nicht nach außen austrägt.

Was gibt es für Möglichkeiten die variable zu erhöhen, sodass sich die while schleife aktiviert? Und gibt es auch andere Ansätze wie man eine diese Schleife machen kann?

Script:

import paho.mqtt.client as mqtt
import os
import subprocess
import time
import smbus2
import bme280

#Bme280_basic Temperature
# BME280 sensor address (default address)
address = 0x76
# Initialize I2C bus
bus = smbus2.SMBus(1)
# Load calibration parameters
calibration_params = bme280.load_calibration_params(bus, address)
# to activate loop
y = int(1)
#Temperature loop
while y == 2:
      data = bme280.sample(bus, address, calibration_params)

      # Extract temperature, pressure, and humidity
      temperature_celsius = data.temperature      
      # Print the readings
      print("Temperature: {:.2f} °C".format(temperature_celsius))
      # Wait for a few seconds before the next reading
      time.sleep(2)
      #print(y)
else:
      print("stopped") 
    
#Connection successfull
def on_connect(client, userdata, flags, rc):
  print("Connected to MQTT broker")


#Checking for messages to execute code
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
    if msg.payload.decode() == "temp_bme280_start":
        print("Calling script to for temperature start...")
        # activate loop by adding 1
        y += 1   
        print(y)
    if msg.payload.decode() == "temp_bme280_stop":
        print("Calling script to for temperature stop...")
        # deactivate loop by remove 1
        y -= 1  
        print(y)  

def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribed to topic : " + str(mid) +" with QoS" + str(granted_qos))

client = mqtt.Client()

client.username_pw_set( "userxxx" , "passwortxxx" )

client.connect( "192.16x.xxx.xxx", 1883, 60)

client.subscribe( "frame/monitor" , qos=1)

client.on_connect = on_connect

client.on_message = on_message

client.loop_forever()

Würde Chat GPT sowas lösen können?

Code, Programmiersprache, Python, Script, Python 3, Raspberry Pi, while-Schleife, ChatGPT

Wie kann ich die Porcupine Wake-Word detection verwenden?

Hallo,

ich programmiere gerade einen Sprachassistenten und wollte nun die Wake-Word Funktion hinzufügen. Das ist mein Code:

def wait_for_wake_word(recognizer, source):
    keyword_path = r"C:\Users\User\PycharmProjects\voiceAssistant\hey-Luna_de_windows_v3_0_0 (2)\hey-Luna_de_windows_v3_0_0.ppn"
    sensitivity = 0.5
    access_key = "..."

    handle = pvporcupine.create(keywords=[keyword_path], sensitivities=[sensitivity], access_key=access_key)

    if handle is None:
        print("Fehler beim Erstellen des Porcupine-Objekts. Überprüfe den Dateipfad und den Zugriffsschlüssel.")
        return

    audio = pyaudio.PyAudio()

    try:
        print("Warte auf das Wake-Word...")

        stream = audio.open(
            rate=handle.sample_rate,
            channels=1,
            format=pyaudio.paInt16,
            input=True,
            frames_per_buffer=handle.frame_length)

        while True:
            pcm = stream.read(handle.frame_length)
            pcm = pcm[0: handle.frame_length]

            keyword_index = handle.process(pcm)
            if keyword_index >= 0:
                print("Wake-Word 'Luna' erkannt!")
                break
    finally:
        if handle is not None:
            handle.delete()
        if stream is not None:
            stream.close()
        if audio is not None:
            audio.terminate()

Wenn ich es nun aber ausführe, kommt diese Fehlermeldung:

Traceback (most recent call last):

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 1162, in <module>

  execute()

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 671, in execute

  wait_for_wake_word(recognizer, source)

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 121, in wait_for_wake_word

  handle = pvporcupine.create(keywords=[keyword_path], sensitivities=[sensitivity], access_key=access_key)

       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "C:\Users\User\PycharmProjects\voiceAssistant\venv\interpreter\Lib\site-packages\pvporcupine\_factory.py", line 59, in create

  raise ValueError(

ValueError: One or more keywords are not available by default. Available default keywords are:\ngrapefruit, picovoice, terminator, americano, computer, hey siri, bumblebee, hey barista, ok google, alexa, hey google, blueberry, grasshopper, jarvis, porcupine, pico clock

Es liegt aber nicht an einem Rechtschreibfehler im Dateipfad oder im API Key. Woran kann es sonst liegen?

Freundliche Grüsse

cmd, Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Pycharm

Wie kann ich machen, dass OpenAI mich duzt?

Hallo,

wie kann ich bei diesem Code machen, dass mich OpenAI bei allen Fragen, die es mir beantwortet, duzt und nicht siezt?

import pyttsx3
import re
import pyjokes
import speech_recognition as sr
import geocoder
import datetime
import pytz
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
import openai

openai.api_key = 'sk-...'
model_id = "gpt-4"

engine = pyttsx3.init()


def recognize_speech(recognizer, source):
    print("Sage etwas...")
    audio = recognizer.listen(source, timeout=10)
    try:
        text = recognizer.recognize_google(audio, language="de-DE")
        print("Text: " + text)
        return text
    except sr.UnknownValueError:
        return "not_understood"
    except sr.RequestError as e:
        print(f"Fehler bei der Anfrage an die Google Web Speech API: {e}")
        return ""


def openai_request(prompt):
    response = openai.ChatCompletion.create(
        model=model_id,
        messages=[{"role": "user", "content": prompt}],
        max_tokens=150
    )

    api_usage = response['usage']
    print('Total Token consumed: {0}'.format(api_usage['total_tokens']))
    response_text = response.choices[0].message['content']
    prompt += response_text
    return prompt


def speak(text=None):
    if text:
        engine.say(text)
        engine.runAndWait()


def hey_luna_in_q(q):
    return "luna" in q.lower()


def wait_for_wake_word(recognizer, source):
    while True:
        print("Warte auf Wake-Word...")
        audio = recognizer.listen(source)
        try:
            text = recognizer.recognize_google(audio, language="de-DE")
            if hey_luna_in_q(text):
                print("Wake-Word erkannt!")
                return
        except sr.UnknownValueError:
            pass
        except sr.RequestError as e:
            print(f"Fehler bei der Anfrage an die Google Web Speech API: {e}")


def get_local_time(location_name):
    try:
        if location_name.lower() == "current location":
            current_location = geocoder.ip('me')
            latitude, longitude = current_location.latlng
        else:
            geolocator = Nominatim(user_agent="voiceAssistant")
            location = geolocator.geocode(location_name)

            if not location:
                return "Ort nicht gefunden"

            latitude = location.latitude
            longitude = location.longitude

        tf = TimezoneFinder()
        timezone = tf.timezone_at(lng=longitude, lat=latitude)

        if timezone:
            local_time = datetime.datetime.now(pytz.timezone(timezone))
            return local_time.strftime("%H:%M")
        else:
            return "Unbekannte Zeitzone"
    except Exception as e:
        print("Fehler beim Abrufen der lokalen Zeit:", e)
        return "Fehler"


def execute():
    recognizer = sr.Recognizer()

    witz_erzählt = False  # Variable, um den Zustand des Witzes zu verfolgen

    with sr.Microphone() as source:
        while True:
            wait_for_wake_word(recognizer, source)
            print("Warte auf Wake-Word...")

            q = recognize_speech(recognizer, source)
            print("Erkannter Text:", q)

            if q == "not_understood":
                speak("Entschuldigung! Das habe ich nicht verstanden.")
                continue

            if "hallo" in q.lower():
                speak("Hallo! Womit kann ich dir behilflich sein?")
                continue

            if "wie geht es dir" in q.lower():
                speak("Mir geht es gut, danke! Wie geht es dir?")
                continue

            if "spät ist es in" in q.lower() or "wieviel uhr ist es in" in q.lower() or "wieviel uhr in" in q.lower() or "zeit in" in q.lower() or "uhrzeit in" in q.lower():
                location_name = q.split("in")[-1].strip()
                print("Extrahierter Ortname:", location_name)
                local_time = get_local_time(location_name)
                print("Lokale Zeit für", location_name, ":", local_time)
                if local_time:
                    speak(f"In {location_name} ist es {local_time}.")
                else:
                    speak(f"Entschuldigung, ich konnte die Zeit für {location_name} nicht finden.")
                continue

            if "spät ist es" in q.lower() or "wieviel uhr" in q.lower() or "zeit in" in q.lower() or "uhrzeit in" in q.lower():
                current_location = geocoder.ip('me')
                latitude, longitude = current_location.latlng
                local_time = get_local_time("current location")
                speak(f"Es ist {local_time}.")
                continue

            if "erzähle mir einen witz" in q.lower() or "erzähl mir einen witz" in q.lower() or "ich möchte einen witz hören" in q.lower():
                joke = pyjokes.get_joke(language='de')
                speak(joke)
                witz_erzählt = True
                continue

            if "ich bin traurig" in q.lower() or "mir geht es nicht gut" in q.lower() or "es geht mir nicht gut" in q.lower() or "mir geht es schlecht" in q.lower():
                if not witz_erzählt:
                    speak("Das tut mir leid zu hören. Ich bin hier für dich, wenn du reden möchtest oder jemanden zum Zuhören brauchst. Soll ich dir zum Aufmuntern einen Witz erzählen?")
                    response = recognize_speech(recognizer, source)
                    if "ja" in response.lower():
                        joke = pyjokes.get_joke(language='de')
                        speak(joke)
                        continue
                    elif "nein" in response.lower():
                        speak("Ok, womit kann ich dir sonst behilflich sein?")
                        continue
                    else:
                        speak("Entschuldigung. Ich habe dich nicht verstanden.")
                        continue

            prompt = q
            response = openai_request(prompt)

            if response.lower().startswith(q.lower()):
                response = response[len(q):].strip()

            speak(response)


if __name__ == '__main__':
    execute()

Freundliche Grüsse

Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Pycharm, ChatGPT

Meistgelesene Beiträge zum Thema Python 3