Skip to content

Instantly share code, notes, and snippets.

Shelly Home Assistant Failover Script

A script for Shelly devices that automatically switches between "smart" and "dumb" modes based on Home Assistant connectivity. Perfect for setups where you want smart home functionality when Home Assistant is available, but need traditional switch functionality during outages.

Primary Use Case

Originally developed for controlling smart bulbs (like Philips Hue) where:

  • Shelly device controls power to smart bulbs
  • Physical switch input is used as a trigger for Home Assistant automations
  • Power to smart bulbs remains always on during normal operation
# change in tables_custom_flavor.py
class FlavorWrapper(object):
"""
Wrapper class that creates a predict function such that
predict(data: pd.DataFrame) -> model's output as pd.DataFrame (pandas DataFrame)
"""
# the intent is to allow state variables to be passed into the class here
def __init__(self, function, **kwargs):
self.function = function
for key, value in kwargs.items():
import os
import random
import _ucrdtw
import mlflow
import numpy as np
import pandas as pd
from mlflow.pyfunc import PythonModel
# Set our production capacity pattern to compare product sales to
def process_image(path):
img = Image.open(path)
img = img.resize((224, 224))
img = np.array(img)
return img
def process_data(X_data, y_data):
X_data = np.array(X_data, dtype = 'float32')
if rgb:
pass
X_data = np.array(X_data, dtype = 'float32')
X_data = np.stack((X_data,) * 3, axis=-1)
if smart_home:
if prediction == 'Palm':
try:
action = "Lights on, music on"
sonos.play()
# turn off smart home actions if devices are not responding
except ConnectionError:
smart_home = False
pass
# etc. etc.
sonos_ip = '192.168.0.104'
sonos = SoCo(sonos_ip)
# Play
sonos.play()
#Pause
sonos.pause()
# Philips Hue Settings
bridge_ip = '192.168.0.103'
b = Bridge(bridge_ip)
on_command = {'transitiontime' : 0, 'on' : True, 'bri' : 254}
off_command = {'transitiontime' : 0, 'on' : False, 'bri' : 254}
# Turn lights on
b.set_light(6, on_command)
#starts the webcam, uses it as video source
camera = cv2.VideoCapture(0) #uses webcam for video
while camera.isOpened():
#ret returns True if camera is running, frame grabs each frame of the video feed
ret, frame = camera.read()
k = cv2.waitKey(10)
if k == 32: # if spacebar pressed
frame = np.stack((frame,)*3, axis=-1)
from keras import load_model
model = load_model(path) # open saved model/weights from .h5 file
def predict_image(image):
image = np.array(image, dtype='float32')
image /= 255
pred_array = model.predict(image)
# model.predict() returns an array of probabilities -
# np.argmax grabs the index of the highest probability.