Python Program integration to HA

Hi to everyone,

I was already building a “smart home” using arduino sensors for data reading and other stuff which i found a lot of information by searching. Also i use python and a couple of PC’s and laptops .
Then i discovered the HA, so everything is much easier and good looking especially with the lovelace UI.

But what i can’t get, is how (and if is possible) to make my custom made python program that is running and sends the commands or reads the state of the other PC/laptops, “talk” with HA.

As an example, with the python program i send commands (using sockets | server-client build) to a laptop connected to my TV so i can change channels, open Netflix etc.
What i would like is to integrate HA to this setup. Create a button and then send this command to my main python program so the laptop acts according to the command (showing it as info is the easy part i assume).

Is the possibility there? I know i can use some python scripts in HA but from all the search i ve made my question is still unclear.

As you have imagined i am fairly new to all this and i haven’t been able to successfully find anything to point me in either direction.

Sorry for the dumb question, and i know it might be trivial for some of you but your insight will be in a great value as i will have to re-draw my plan without wasting time for no reason.

Thank you in advance,
Jim

Hi Jim,
You can build custom components or add ons.

Hope this helps!

1 Like

Check the command_line integration.

1 Like

I was in the same situation when i started with HA.
Meanwhile i mostly connect python scripts over mqtt and use mqtt components.
Take a look at the paho mqtt python module.

Simple python example:

import paho.mqtt.client as mqtt
import sys

topic = "home/some/topic"

def on_connect(client, userdata, flags, rc):
    #print("Connected with result code " + str(rc))
    client.subscribe(topic + "/#")

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 1883, 60)
client.loop_forever()

also with shell scripts:

#!/bin/bash
MQTT='localhost'

## Uptime
TOPIC="home/sensors/$(hostname)/uptime"
PAYLOAD=$(cat /proc/uptime | awk '{printf "%0.f", $1}')
/usr/bin/mosquitto_pub -t "$TOPIC" -m "$PAYLOAD" -h "$MQTT"

## Disk
TOPIC="home/sensors/$(hostname)/diskpercent"
PAYLOAD=$(df -h | grep mmc | tr -s ' ' | cut -d' ' -f5 | sed 's/%$//')
/usr/bin/mosquitto_pub -t "$TOPIC" -m "$PAYLOAD" -h "$MQTT"
1 Like

Thanks everyone for the awsome suggestions. I have started experimenting with the different approaches that were proposed and just for the sake of someone having the same question in the future i ll upload my solution and the code that made it possible.
Thank you once more.

1 Like

Dont forget to checkout appdaemon (HA addon). Its the perfect fit for using python to interact with HA.

1 Like