Infineon Team
Published © MIT

Low latency voice control with PSOC™ Edge & Home Assistant

Are you also tired of waiting seconds for your cloud-based voice assistant to react? Change the latency to milliseconds with PSOC™ Edge!

IntermediateFull instructions provided3 hours362
Low latency voice control with PSOC™ Edge & Home Assistant

Things used in this project

Hardware components

PSOC™ Edge E84 AI Evaluation Kit
Infineon PSOC™ Edge E84 AI Evaluation Kit
×1
Smart Plug
×1
Desk Light
×1

Software apps and online services

Home Assistant
Home Assistant
Python

Story

Read more

Code

ha_config.py

Python
# Home Assistant Configuration
# Update these values with your Home Assistant details

HA_URL = "http://192.168.178.26:8123/"  # Your Home Assistant URL
HA_TOKEN = ""  # Long-lived access token from HA

edge-to-ha.py

Python
import serial
import re
import requests
from ha_config import HA_URL, HA_TOKEN

# Serial port configuration
SERIAL_PORT = 'COM34'
BAUD_RATE = 115200

# Home Assistant entity
LIGHT_ENTITY = "light.light_buro"

# Home Assistant API client
class HomeAssistantAPI:
    def __init__(self, url, token):
        self.url = url.rstrip('/')
        self.headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }
    
    def call_service(self, domain, service, entity_id):
        """Call a Home Assistant service"""
        endpoint = f"{self.url}/api/services/{domain}/{service}"
        data = {"entity_id": entity_id}
        
        try:
            response = requests.post(endpoint, headers=self.headers, json=data, timeout=5)
            response.raise_for_status()
            print(f"Success: {domain}.{service} called on {entity_id}")
            return True
        except requests.exceptions.RequestException as e:
            print(f"Error calling HA service: {e}")
            return False
    
    def turn_on_light(self, entity_id):
        """Turn on a light"""
        return self.call_service("light", "turn_on", entity_id)
    
    def turn_off_light(self, entity_id):
        """Turn off a light"""
        return self.call_service("light", "turn_off", entity_id)

# Initialize Home Assistant API clientg
ha_api = None

# Intent handler functions
def TurnOnLight():
    """Handler for TurnOnLight intent"""
    print("Executing TurnOnLight...")
    if ha_api:
        ha_api.turn_on_light(LIGHT_ENTITY)

def TurnOffLight():
    """Handler for TurnOffLight intent"""
    print("Executing TurnOffLight...")
    if ha_api:
        ha_api.turn_off_light(LIGHT_ENTITY)

# Intent mapping
INTENT_HANDLERS = {
    'TurnOnLight': TurnOnLight,
    'TurnOffLight': TurnOffLight,
}

def parse_intent(line):
    """Parse intent name from serial output"""
    # Look for lines like "Intent name: TurnOnLight"
    match = re.search(r'Intent name:\s*(\w+)', line)
    if match:
        return match.group(1)
    return None

def main():
    """Main function to read from serial and execute intent handlers"""
    global ha_api
    
    # Initialize Home Assistant API
    print("Initializing Home Assistant API...")
    ha_api = HomeAssistantAPI(HA_URL, HA_TOKEN)
    print(f"Home Assistant URL: {HA_URL}")
    
    print(f"\nConnecting to {SERIAL_PORT} at {BAUD_RATE} baud...")
    
    try:
        # Open serial connection
        with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as ser:
            print("Connected! Listening for intents...")
            
            while True:
                # Read line from serial port
                if ser.in_waiting > 0:
                    line = ser.readline().decode('utf-8', errors='ignore').strip()
                    
                    if line:
                        print(f"Received: {line}")
                        
                        # Parse intent from line
                        intent_name = parse_intent(line)
                        
                        if intent_name:
                            # Execute corresponding handler if it exists
                            handler = INTENT_HANDLERS.get(intent_name)
                            if handler:
                                print(f"Intent detected: {intent_name}")
                                handler()
                            else:
                                print(f"Unknown intent: {intent_name}")
                    
    except serial.SerialException as e:
        print(f"Serial port error: {e}")
    except KeyboardInterrupt:
        print("\nStopped by user")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()

Credits

Infineon Team
143 projects • 429 followers
Hands-on projects, tutorials, and code for sensors, MCUs, connectivity, security, power, and IoT. Follow for new builds and ideas.

Comments