Skip to content

Deploying FHEM

Introduction

FHEM (Freundliche Hausautomation und Energie-Messung, meaning “Friendly Home Automation and Energy Monitoring”) is a powerful, open-source Perl-based server for smart home automation. Originally developed in Germany, FHEM has grown into one of the most versatile home automation platforms available, supporting hundreds of different devices, protocols, and integrations.

FHEM stands out for its:

  • Protocol Flexibility: Native support for Z-Wave, Zigbee, EnOcean, MQTT, KNX, Homematic, and 200+ other protocols
  • Device Compatibility: Works with thousands of smart home devices from various manufacturers
  • Perl-Based Extensibility: Highly customizable through Perl modules and user-defined functions
  • Web Interface: Full-featured web UI for device management, visualization, and automation
  • Event System: Powerful event-driven automation with complex condition logic
  • Data Logging: Comprehensive data collection with integrated plotting and analysis tools
  • No Cloud Dependency: Fully local operation with complete privacy and control
  • Active Community: Large, established user base with extensive documentation and modules

This comprehensive guide walks you through deploying FHEM on Klutch.sh using Docker, including detailed installation steps, device configuration, persistent storage setup, sample configurations, and production-ready best practices.

Why Deploy FHEM on Klutch.sh?

Deploying FHEM on Klutch.sh offers several advantages:

  • Automated Docker Deployment: Klutch.sh automatically detects your Dockerfile and builds your FHEM container with all required Perl modules and dependencies
  • Persistent Storage: Built-in persistent volumes ensure your device configurations, automation rules, and historical data are never lost
  • Always Accessible: Access your smart home from anywhere with HTTPS-enabled URLs
  • Zero Infrastructure Management: No need to maintain a home server, configure port forwarding, or manage dynamic DNS
  • Reliable Uptime: Keep your home automation running even during local power outages or internet disruptions
  • Easy Updates: Deploy new FHEM versions with a simple git push
  • Scalable Resources: Adjust compute resources as your smart home grows

Prerequisites

Before you begin, ensure you have the following:

  • A Klutch.sh account
  • A GitHub account with a repository for your FHEM project
  • Docker installed locally for testing (optional but recommended)
  • Smart home devices or protocols you want to integrate (Z-Wave, Zigbee, MQTT, etc.)
  • Basic understanding of Docker and smart home automation concepts

Installation and Setup

Step 1: Create Your Project Directory

First, create a new directory for your FHEM deployment project:

Terminal window
mkdir fhem-klutch
cd fhem-klutch
git init

Step 2: Create the Dockerfile

Create a Dockerfile in your project root directory. This will define your FHEM container configuration:

FROM debian:bookworm-slim
# Install required packages
RUN apt-get update && apt-get install -y --no-install-recommends \
perl \
perl-base \
libdevice-serialport-perl \
libio-socket-ssl-perl \
libwww-perl \
libxml-simple-perl \
libjson-perl \
sqlite3 \
libdbd-sqlite3-perl \
libtext-diff-perl \
libtimedate-perl \
libmail-imapclient-perl \
libgd-graph-perl \
libtext-csv-perl \
wget \
gnupg \
apt-transport-https \
ca-certificates \
netcat-traditional \
&& rm -rf /var/lib/apt/lists/*
# Install FHEM
WORKDIR /opt
RUN wget -qO- https://fhem.de/fhem-6.3.tar.gz | tar xz && \
mv fhem-6.3 fhem && \
cd fhem && \
chmod +x fhem.pl
# Create necessary directories
RUN mkdir -p /opt/fhem/log && \
mkdir -p /opt/fhem/data && \
chmod 755 /opt/fhem
# Set working directory
WORKDIR /opt/fhem
# Expose FHEM web interface port
EXPOSE 8083
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD nc -z localhost 8083 || exit 1
# Start FHEM
CMD ["perl", "fhem.pl", "fhem.cfg"]

Dockerfile Notes:

  • Uses Debian Bookworm for stability and compatibility
  • Installs essential Perl modules for device communication and data processing
  • Downloads and extracts FHEM 6.3 (the stable release)
  • Exposes port 8083 (FHEM’s default web interface port)
  • Creates directories for logs and persistent data
  • Includes a health check to monitor FHEM’s web server

Step 3: Create Initial FHEM Configuration

Create a basic fhem.cfg configuration file that will be used as the initial configuration:

# FHEM Configuration File
# Automatically generated for Klutch.sh deployment
# Global settings
attr global logfile /opt/fhem/log/fhem-%Y-%m-%d.log
attr global modpath /opt/fhem
attr global statefile /opt/fhem/data/fhem.save
attr global verbose 3
attr global autoload_undefined_devices 1
attr global uniqueID 98d6b001f9a2a1234567890abcdef012
# Define telnet interface (local only for security)
define telnetPort telnet 7072 localhost
# Define web interface
define WEB FHEMWEB 8083 global
attr WEB plotmode SVG
attr WEB plotfork 1
attr WEB csrfToken random123456789
attr WEB stylesheetPrefix f18
# Define allowed devices
define allowed allowed
# Example: Define an MQTT client (configure after deployment)
# define mqttClient MQTT 127.0.0.1:1883
# Example: Define a dummy device for testing
define TestDevice dummy
attr TestDevice room System
attr TestDevice alias Test Device
# Enable autocreate for new devices
define autocreate autocreate
attr autocreate filelog /opt/fhem/log/autocreate-%Y-%m-%d.log
# Save configuration on shutdown
define ShutdownSave at *shutdown save
# Initialize done

Configuration Notes:

  • Sets up logging to /opt/fhem/log/ for persistent logs
  • Configures state file at /opt/fhem/data/fhem.save to preserve device states
  • Enables telnet interface on localhost only for security
  • Creates web interface on port 8083
  • Includes a test dummy device to verify the installation
  • Enables autocreate to automatically discover new devices

Step 4: Create Advanced Dockerfile with Custom Modules

For a more production-ready setup with additional Perl modules and device support:

FROM debian:bookworm-slim
# Install system dependencies and Perl modules
RUN apt-get update && apt-get install -y --no-install-recommends \
# Core system packages
perl perl-base perl-modules wget gnupg ca-certificates \
# Serial communication
libdevice-serialport-perl \
# SSL/TLS support
libio-socket-ssl-perl libnet-ssleay-perl \
# Web and HTTP
libwww-perl libhttp-daemon-perl \
# Data formats
libxml-simple-perl libjson-perl libjson-xs-perl \
libtext-csv-perl libtext-csv-xs-perl \
# Database support
sqlite3 libdbd-sqlite3-perl libdbi-perl \
# Date/Time handling
libtimedate-perl libdatetime-perl \
# Email support
libmail-imapclient-perl libmail-sendmail-perl \
# Image processing for plots
libgd-graph-perl libgd-text-perl libgd-perl \
# Utility modules
libtext-diff-perl libdigest-sha-perl \
libterm-readkey-perl libterm-readline-perl-perl \
# MQTT support
libnet-mqtt-simple-perl libnet-mqtt-perl \
# Bluetooth/Zigbee support
bluetooth bluez libbluetooth-dev \
# Network utilities
netcat-traditional telnet net-tools \
# Build tools (for CPAN modules if needed)
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Install additional CPAN modules
RUN cpan -T \
Device::USB \
Protocol::WebSocket \
LWP::Protocol::https \
&& rm -rf /root/.cpan
# Install FHEM
WORKDIR /opt
RUN wget -qO- https://fhem.de/fhem-6.3.tar.gz | tar xz && \
mv fhem-6.3 fhem
# Set proper permissions
RUN cd fhem && \
chmod 755 fhem.pl && \
chmod 755 /opt/fhem && \
mkdir -p /opt/fhem/log /opt/fhem/data /opt/fhem/www/tablet && \
chmod 755 /opt/fhem/log /opt/fhem/data
# Copy custom configuration if exists
COPY fhem.cfg /opt/fhem/fhem.cfg
# Set working directory
WORKDIR /opt/fhem
# Expose ports
# 8083: FHEMWEB interface
# 7072: Telnet interface (optional, localhost only)
EXPOSE 8083 7072
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=90s --retries=3 \
CMD nc -z localhost 8083 || exit 1
# Environment variables
ENV TZ=UTC
ENV FHEM_DIR=/opt/fhem
ENV FHEM_UID=6061
ENV FHEM_GID=6061
# Start FHEM
CMD ["perl", "fhem.pl", "fhem.cfg"]

Advanced Features:

  • Comprehensive Perl module installation for device support
  • MQTT, Bluetooth, and Zigbee protocol support
  • Image processing for FHEM’s built-in plotting
  • Additional CPAN modules for advanced integrations
  • Proper directory structure with permissions
  • Multiple exposed ports for different interfaces

Step 5: Create Device Configuration Examples

Create a devices.cfg.example file with sample device configurations:

# FHEM Device Configuration Examples
# Copy and customize for your smart home setup
# ============================================
# MQTT Devices
# ============================================
# MQTT Broker Connection
define mqttBroker MQTT 192.168.1.100:1883
attr mqttBroker clientId fhem-klutch
attr mqttBroker username mqtt_user
attr mqttBroker password mqtt_password
# MQTT Temperature Sensor
define livingroom_temp MQTT_DEVICE
attr livingroom_temp IODev mqttBroker
attr livingroom_temp subscribeReading_temperature home/livingroom/temperature
attr livingroom_temp room Living Room
attr livingroom_temp alias Living Room Temperature
# ============================================
# Z-Wave Devices
# ============================================
# Z-Wave USB Controller
define ZWave ZWave /dev/ttyUSB0@115200
attr ZWave room System
# Z-Wave Light Switch
define kitchen_light ZWave_SWITCH_BINARY 3
attr kitchen_light IODev ZWave
attr kitchen_light room Kitchen
attr kitchen_light alias Kitchen Light
# ============================================
# Zigbee Devices
# ============================================
# Zigbee2MQTT Bridge
define zigbee2mqtt MQTT2_DEVICE
attr zigbee2mqtt IODev mqttBroker
attr zigbee2mqtt room System
attr zigbee2mqtt devStateIcon online:10px-kreis-gruen offline:10px-kreis-rot
# Philips Hue Bulb via Zigbee2MQTT
define bedroom_light MQTT2_DEVICE
attr bedroom_light IODev mqttBroker
attr bedroom_light subscribeReading_state zigbee2mqtt/bedroom_light/state
attr bedroom_light setList on:noArg off:noArg toggle:noArg brightness:slider,0,1,254
attr bedroom_light room Bedroom
attr bedroom_light alias Bedroom Light
# ============================================
# Homematic Devices
# ============================================
# Homematic CCU Connection
define HM_CCU2 HMCCU 192.168.1.50
attr HM_CCU2 ccuflags experts
attr HM_CCU2 room System
# Homematic Thermostat
define heating_thermostat HMCCUDEV ABC1234567
attr heating_thermostat IODev HM_CCU2
attr heating_thermostat room Heating
attr heating_thermostat alias Living Room Thermostat
# ============================================
# Network Devices
# ============================================
# Network Presence Detection
define phone_john PRESENCE lan-ping 192.168.1.101
attr phone_john room Presence
attr phone_john alias John's Phone
attr phone_john timeout 180
# ============================================
# Virtual Devices and Automation
# ============================================
# Virtual switch for scene
define evening_scene dummy
attr evening_scene room Scenes
attr evening_scene alias Evening Scene
attr evening_scene setList on off
# ============================================
# Data Logging
# ============================================
# Temperature Log
define FileLog_temp FileLog /opt/fhem/log/temp-%Y-%m-%d.log livingroom_temp:temperature.*
attr FileLog_temp room Logs
attr FileLog_temp logtype text
# Plot for temperature
define SVG_temp SVG FileLog_temp:SVG_temp:CURRENT
attr SVG_temp room Plots
attr SVG_temp label "Living Room Temperature"

Step 6: Create Automation Examples

Create an automation.cfg.example file with sample automation rules:

# FHEM Automation Examples
# Event-driven automation for smart home
# ============================================
# Time-Based Automation
# ============================================
# Turn on evening lights at sunset
define evening_lights at *{sunset()} set livingroom_light on
attr evening_lights room Automation
# Turn off all lights at midnight
define midnight_off at 00:00:00 set light_.*,TYPE=MQTT_DEVICE off
attr midnight_off room Automation
# ============================================
# Presence-Based Automation
# ============================================
# Turn on lights when phone detected (arriving home)
define arrive_home notify phone_john:present.* {\
fhem("set livingroom_light on");;\
fhem("set kitchen_light on");;\
}
attr arrive_home room Automation
attr arrive_home alias Arrival Automation
# Turn off lights when leaving
define leave_home notify phone_john:absent.* {\
fhem("set livingroom_light off");;\
fhem("set kitchen_light off");;\
}
attr leave_home room Automation
attr leave_home alias Departure Automation
# ============================================
# Sensor-Based Automation
# ============================================
# Turn on heating when temperature drops below 18°C
define temp_heating notify livingroom_temp:temperature:.* {\
my $temp = ReadingsVal("livingroom_temp","temperature",20);;\
if($temp < 18) {\
fhem("set heating_thermostat desired-temp 21");;\
}\
}
attr temp_heating room Automation
# ============================================
# Scene Automation
# ============================================
# Evening scene: Dim lights, close blinds
define evening_scene_trigger notify evening_scene:on {\
fhem("set livingroom_light brightness 128");;\
fhem("set bedroom_light brightness 64");;\
fhem("set blinds_living closed");;\
}
attr evening_scene_trigger room Automation
# ============================================
# Security Automation
# ============================================
# Send notification on motion when away
define motion_alert notify motion_sensor:motion.* {\
if(ReadingsVal("phone_john","presence","absent") eq "absent") {\
fhem("set Pushover msg='Motion detected while away!'");;\
}\
}
attr motion_alert room Security
# ============================================
# Energy Management
# ============================================
# Log power consumption hourly
define power_log at +*01:00:00 {\
my $power = ReadingsVal("power_meter","power",0);;\
fhem("setreading power_daily consumption $power");;\
}
attr power_log room Energy

Step 7: Create Environment Configuration

Create a .env.example file to document optional environment variables:

Terminal window
# FHEM Environment Configuration
# Copy to .env and customize as needed
# Timezone for FHEM
TZ=UTC
# FHEM directories (these are defaults in Dockerfile)
FHEM_DIR=/opt/fhem
FHEM_LOG_DIR=/opt/fhem/log
FHEM_DATA_DIR=/opt/fhem/data
# Security settings
# Set to 1 to enable HTTPS for FHEMWEB
FHEM_ENABLE_HTTPS=0
# Web interface password (configure via FHEM web interface after deployment)
# FHEM_WEB_PASSWORD=your-secure-password
# Optional: MQTT broker configuration
# MQTT_BROKER_HOST=mqtt.example.com
# MQTT_BROKER_PORT=1883
# MQTT_USERNAME=fhem
# MQTT_PASSWORD=secure-password
# Optional: Database configuration (for advanced logging)
# DB_TYPE=postgresql
# DB_HOST=postgres-app.klutch.sh
# DB_PORT=8000
# DB_NAME=fhem
# DB_USER=fhem
# DB_PASSWORD=secure-password

Step 8: Create README Documentation

Create a README.md file with deployment instructions:

# FHEM Smart Home Automation on Klutch.sh
This repository contains the Docker configuration for deploying FHEM on Klutch.sh.
## Quick Start
1. Push this repository to GitHub
2. Create a new app on Klutch.sh
3. Connect your GitHub repository
4. Deploy with HTTP traffic on port 8083
5. Attach persistent volumes (see below)
6. Access FHEM at your assigned URL
## Required Persistent Volumes
FHEM requires persistent storage for configurations and data:
- **Mount Path**: `/opt/fhem/data` - Device states and configurations
- **Mount Path**: `/opt/fhem/log` - System logs and device logs
## Initial Configuration
After deployment:
1. Access the web interface at `https://example-app.klutch.sh`
2. Set a password: Go to FHEM web UI → Set password
3. Configure your devices (see `devices.cfg.example`)
4. Set up automation rules (see `automation.cfg.example`)
5. Configure device discovery for your protocols
## Supported Protocols
- MQTT
- Z-Wave
- Zigbee (via Zigbee2MQTT)
- Homematic
- KNX
- EnOcean
- 200+ other protocols
## Documentation
- <a href="https://fhem.de/fhem.html" target="_blank" rel="noopener noreferrer">FHEM Official Documentation</a>
- <a href="https://wiki.fhem.de/" target="_blank" rel="noopener noreferrer">FHEM Wiki</a>
- <a href="https://docs.klutch.sh?utm_source=docs" target="_blank">Klutch.sh Docs</a>

Step 9: Test Locally with Docker (Optional)

For local testing, you can run FHEM with Docker:

Terminal window
# Build the Docker image
docker build -t fhem-klutch .
# Run FHEM locally
docker run -d \
--name fhem-test \
-p 8083:8083 \
-v "$(pwd)/fhem-data:/opt/fhem/data" \
-v "$(pwd)/fhem-log:/opt/fhem/log" \
-e TZ=America/New_York \
fhem-klutch
# View logs
docker logs -f fhem-test
# Access FHEM at http://localhost:8083
# Stop and remove when done
docker stop fhem-test
docker rm fhem-test

For a complete local test environment with MQTT, create a docker-compose.yml:

version: "3.8"
services:
mosquitto:
image: eclipse-mosquitto:2
ports:
- "1883:1883"
- "9001:9001"
volumes:
- mosquitto-data:/mosquitto/data
- mosquitto-log:/mosquitto/log
restart: unless-stopped
fhem:
build: .
ports:
- "8083:8083"
- "7072:7072"
environment:
TZ: America/New_York
volumes:
- fhem-data:/opt/fhem/data
- fhem-log:/opt/fhem/log
depends_on:
- mosquitto
restart: unless-stopped
volumes:
mosquitto-data:
mosquitto-log:
fhem-data:
fhem-log:

Run the complete environment:

Terminal window
docker-compose up -d
docker-compose logs -f fhem

Note: Docker Compose is only for local development and testing. Klutch.sh does not support Docker Compose for deployments.

Step 10: Push to GitHub

Commit your configuration files to your GitHub repository:

Terminal window
git add Dockerfile fhem.cfg devices.cfg.example automation.cfg.example .env.example README.md
git commit -m "Add FHEM Docker configuration for Klutch.sh"
git remote add origin https://github.com/yourusername/fhem-klutch.git
git push -u origin main

Deploying to Klutch.sh

Now that your FHEM project is ready and pushed to GitHub, follow these steps to deploy it on Klutch.sh with persistent storage.

    1. Log in to Klutch.sh

      Navigate to klutch.sh/app and sign in to your account.

    2. Create a New Project

      Go to Create Project and give your project a meaningful name (e.g., “FHEM Smart Home”).

    3. Create a New App

      Navigate to Create App and configure the following settings.

    4. Select Your Repository

      • Choose GitHub as your Git source
      • Select the repository containing your FHEM Dockerfile
      • Choose the branch you want to deploy (usually main or master)
    5. Configure Traffic Type

      • Traffic Type: Select HTTP (FHEM serves a web interface via HTTP)
      • Internal Port: Set to 8083 (the default port that FHEM’s web interface listens on)
    6. Set Environment Variables (Optional)

      Add environment variables to customize your FHEM deployment:

      • TZ: Your timezone (e.g., America/New_York, Europe/Berlin, Asia/Tokyo) for accurate time-based automation

      Security Note: After deployment, immediately set a password for the FHEM web interface to prevent unauthorized access.

    7. Attach Persistent Volumes

      FHEM requires persistent storage for device configurations, automation rules, state data, and logs. Add two volumes:

      Data Volume:

      • Click “Add Volume” in the Volumes section
      • Mount Path: Enter /opt/fhem/data
      • Size: Choose 5-10GB (stores device states, configurations, and automation rules)

      Log Volume:

      • Click “Add Volume” again
      • Mount Path: Enter /opt/fhem/log
      • Size: Choose 2-5GB (stores system logs, device logs, and historical data)

      Critical: These persistent volumes ensure your smart home configurations, device states, automation rules, and historical data persist across deployments, updates, and restarts. Without them, you’ll lose all your settings every time the container restarts.

    8. Configure Additional Settings

      • Region: Select the region closest to your physical location for optimal device communication latency
      • Compute Resources: Choose CPU and memory based on your device count:
        • Small (< 25 devices): 256MB RAM, 0.25 CPU
        • Medium (25-100 devices): 512MB RAM, 0.5 CPU
        • Large (100+ devices): 1GB+ RAM, 1+ CPU
      • Instances: Start with 1 instance (FHEM doesn’t support horizontal scaling due to device state management)
    9. Deploy Your Application

      Click “Create” to start the deployment. Klutch.sh will:

      • Automatically detect your Dockerfile in the repository root
      • Build the Docker image with FHEM and all Perl dependencies
      • Attach the persistent volumes for data and logs
      • Configure environment variables
      • Start your FHEM container
      • Assign a URL for external access
    10. Access Your FHEM Interface

      Once deployment is complete, you’ll receive a URL like example-app.klutch.sh. Navigate to this URL in your browser to access your FHEM web interface:

      https://example-app.klutch.sh

      You should see the FHEM web interface with the default configuration including a test dummy device.


Post-Deployment Configuration

After your FHEM instance is deployed, complete the initial setup and secure your installation.

Secure Your FHEM Installation

  1. Set Web Interface Password

    In the FHEM web interface command input at the top, enter:

    set WEB password your-secure-password

    Then reload the page. You’ll be prompted to enter your password.

  2. Restrict Telnet Access

    The telnet interface should only be accessible from localhost (already configured in fhem.cfg). To verify:

    list telnetPort

    Ensure it shows 127.0.0.1:7072 or localhost:7072.

  3. Enable HTTPS (Optional)

    Klutch.sh automatically provides HTTPS for your app URL, so your FHEM web interface is already secured with TLS.

Configure Device Discovery

FHEM can automatically discover devices on your network. Enable autocreate to automatically add new devices:

  1. Verify Autocreate is Enabled

    The example fhem.cfg already includes autocreate. Check by entering in the command input:

    list autocreate
  2. Configure Protocol-Specific Discovery

    Depending on your devices, configure the appropriate discovery modules:

    For MQTT devices:

    define mqttBroker MQTT mqtt.example.com:1883
    attr mqttBroker clientId fhem-klutch
    attr mqttBroker username your-mqtt-username
    attr mqttBroker password your-mqtt-password

    For Zigbee2MQTT:

    define zigbee2mqtt MQTT2_DEVICE
    attr zigbee2mqtt IODev mqttBroker
    attr zigbee2mqtt subscribeReading_bridge_state zigbee2mqtt/bridge/state

Add Your First Device

Let’s add a simple MQTT temperature sensor as an example:

  1. Define the Device

    In the FHEM command input, enter:

    define living_room_temp MQTT_DEVICE
    attr living_room_temp IODev mqttBroker
    attr living_room_temp subscribeReading_temperature home/livingroom/temperature
    attr living_room_temp room Living Room
    attr living_room_temp alias Living Room Temperature
  2. Save Configuration

    save
  3. View the Device

    Click on “Living Room” in the room list to see your new device.

Create Your First Automation

Create a simple time-based automation to test the system:

  1. Create an Automation Rule

    define morning_greeting notify global:INITIALIZED {\
    Log 1, "FHEM started successfully!";;\
    }
    attr morning_greeting room System
  2. Create a Scheduled Task

    define evening_lights at *{sunset()} {\
    Log 1, "Evening lights automation triggered";;\
    }
    attr evening_lights room Automation
  3. Save Configuration

    save

Device Integration

FHEM supports hundreds of device types and protocols. Here are detailed guides for the most common integrations.

MQTT Devices

MQTT is one of the most popular protocols for smart home devices. Here’s how to integrate MQTT devices with FHEM:

  1. Configure MQTT Broker Connection

    If you have an external MQTT broker or want to deploy one on Klutch.sh:

    define mqttBroker MQTT mqtt-broker.example.com:1883
    attr mqttBroker clientId fhem-smart-home
    attr mqttBroker username mqtt_user
    attr mqttBroker password secure_password
    attr mqttBroker room System
  2. Add MQTT Device

    # Temperature and humidity sensor
    define bedroom_sensor MQTT_DEVICE
    attr bedroom_sensor IODev mqttBroker
    attr bedroom_sensor subscribeReading_temperature home/bedroom/temperature
    attr bedroom_sensor subscribeReading_humidity home/bedroom/humidity
    attr bedroom_sensor room Bedroom
    attr bedroom_sensor alias Bedroom Climate Sensor
  3. Add Controllable MQTT Device

    # Smart light bulb
    define bedroom_light MQTT_DEVICE
    attr bedroom_light IODev mqttBroker
    attr bedroom_light subscribeReading_state home/bedroom/light/state
    attr bedroom_light publishReading_on home/bedroom/light/set ON
    attr bedroom_light publishReading_off home/bedroom/light/set OFF
    attr bedroom_light setList on off
    attr bedroom_light room Bedroom
    attr bedroom_light alias Bedroom Light

Zigbee Devices (via Zigbee2MQTT)

Zigbee2MQTT is a popular bridge for Zigbee devices. To integrate with FHEM:

  1. Deploy Zigbee2MQTT

    If you haven’t already, deploy Zigbee2MQTT with MQTT broker support.

  2. Configure Zigbee2MQTT Bridge in FHEM

    define zigbee2mqtt MQTT2_DEVICE
    attr zigbee2mqtt IODev mqttBroker
    attr zigbee2mqtt room System
    attr zigbee2mqtt subscribeReading_state zigbee2mqtt/bridge/state
    attr zigbee2mqtt subscribeReading_devices zigbee2mqtt/bridge/devices
  3. Add Zigbee Devices

    # Philips Hue bulb
    define hue_living MQTT2_DEVICE
    attr hue_living IODev mqttBroker
    attr hue_living subscribeReading_state zigbee2mqtt/hue_living/state
    attr hue_living subscribeReading_brightness zigbee2mqtt/hue_living/brightness
    attr hue_living setList on:noArg off:noArg brightness:slider,0,1,254
    attr hue_living room Living Room
    attr hue_living alias Hue Living Room
    # Xiaomi temperature sensor
    define xiaomi_temp MQTT2_DEVICE
    attr xiaomi_temp IODev mqttBroker
    attr xiaomi_temp subscribeReading_temperature zigbee2mqtt/xiaomi_temp/temperature
    attr xiaomi_temp subscribeReading_humidity zigbee2mqtt/xiaomi_temp/humidity
    attr xiaomi_temp subscribeReading_battery zigbee2mqtt/xiaomi_temp/battery
    attr xiaomi_temp room Living Room
    attr xiaomi_temp alias Xiaomi Temperature Sensor

Z-Wave Devices

For Z-Wave devices, you need a Z-Wave USB controller connected to your FHEM server. Since Klutch.sh is cloud-based, Z-Wave integration requires a local FHEM instance or a network-connected Z-Wave gateway.

Alternative Approach: Use a Z-Wave to MQTT bridge running locally, then connect FHEM on Klutch.sh to the MQTT broker.

Homematic Devices

If you have a Homematic CCU (Central Control Unit):

  1. Configure CCU Connection

    define HM_CCU HMCCU 192.168.1.50
    attr HM_CCU ccuflags experts
    attr HM_CCU room System
  2. Add Homematic Devices

    # Radiator thermostat
    define living_thermostat HMCCUDEV ABC1234567
    attr living_thermostat IODev HM_CCU
    attr living_thermostat room Living Room
    attr living_thermostat alias Living Room Thermostat

Network-Based Presence Detection

Detect presence based on device network connectivity:

# Phone presence detection via ping
define phone_alice PRESENCE lan-ping 192.168.1.101
attr phone_alice room Presence
attr phone_alice alias Alice's Phone
attr phone_alice timeout 180
# Trigger automation based on presence
define welcome_home notify phone_alice:present.* {\
fhem("set living_light on");;\
Log 1, "Alice arrived home";;\
}
attr welcome_home room Automation

Data Logging and Visualization

FHEM includes powerful built-in tools for logging device data and creating visualizations.

Configure File Logging

  1. Create a Log File for Temperature Data

    define FileLog_temperature FileLog /opt/fhem/log/temperature-%Y-%m-%d.log living_room_temp:temperature.*
    attr FileLog_temperature room Logs
    attr FileLog_temperature logtype text
  2. Create a Plot

    define SVG_temperature SVG FileLog_temperature:SVG_temperature:CURRENT
    attr SVG_temperature room Plots
    attr SVG_temperature label "Living Room Temperature History"
  3. View the Plot

    Navigate to the “Plots” room in the FHEM web interface to see your temperature graph.

Database Logging (Advanced)

For long-term data storage and advanced analytics, configure database logging:

  1. Deploy PostgreSQL on Klutch.sh

    Follow the PostgreSQL deployment guide to create a database instance.

  2. Configure DbLog Module

    define myDbLog DbLog postgresql:database=fhem;host=postgres-app.klutch.sh;port=8000 fhem fhem_password
    attr myDbLog room Logs
    attr myDbLog DbLogType Current
    attr myDbLog DbLogSelectionMode Include
  3. Configure What to Log

    attr myDbLog DbLogInclude living_room_temp:temperature.*,bedroom_sensor:.*

Create a Dashboard

FHEM’s FHEMWEB interface supports customizable dashboards:

  1. Create a Dashboard Room

    define Dashboard dashboard
    attr Dashboard room Dashboard
  2. Add Widgets to Dashboard

    Use the web interface to drag and drop devices onto your dashboard, or configure programmatically:

    attr WEB dashboard_row1col1 living_room_temp
    attr WEB dashboard_row1col2 bedroom_sensor
    attr WEB dashboard_row2col1 living_light

Automation and Scenes

FHEM’s event-driven architecture makes it powerful for automation. Here are practical examples.

Time-Based Automation

# Morning wake-up automation
define morning_routine at 07:00:00 {\
fhem("set bedroom_light brightness 128");;\
fhem("set thermostat desired-temp 21");;\
Log 1, "Morning routine executed";;\
}
attr morning_routine room Automation
# Evening automation at sunset
define evening_routine at *{sunset()} {\
fhem("set outdoor_lights on");;\
fhem("set living_light brightness 180");;\
fhem("set security_camera recording on");;\
}
attr evening_routine room Automation
# Night mode at bedtime
define night_mode at 23:00:00 {\
fhem("set all_lights off");;\
fhem("set thermostat desired-temp 18");;\
fhem("set security_system armed");;\
}
attr night_mode room Automation

Sensor-Triggered Automation

# Motion-activated lighting
define motion_light notify motion_sensor:motion {\
my $state = ReadingsVal("living_light","state","off");;\
if($state eq "off") {\
fhem("set living_light on");;\
fhem("define motion_timer at +00:05:00 set living_light off");;\
}\
}
attr motion_light room Automation
# Temperature-based heating control
define smart_heating notify living_room_temp:temperature:.* {\
my $temp = ReadingsVal("living_room_temp","temperature",20);;\
my $target = 21;;\
if($temp < ($target - 1)) {\
fhem("set thermostat desired-temp $target");;\
} elsif($temp > ($target + 1)) {\
fhem("set thermostat desired-temp " . ($target - 2));;\
}\
}
attr smart_heating room Automation
# Window open detection (turn off heating)
define window_heating_protect notify window_sensor:open {\
fhem("set thermostat desired-temp 12");;\
Log 1, "Window opened, heating reduced";;\
}
attr window_heating_protect room Automation

Presence-Based Automation

# Arriving home
define arrive_home notify phone_alice:present.* {\
fhem("set living_light on");;\
fhem("set thermostat desired-temp 21");;\
fhem("set welcome_speaker msg='Welcome home, Alice!'");;\
Log 1, "Alice arrived home";;\
}
attr arrive_home room Automation
# Leaving home
define leave_home notify phone_alice:absent.* {\
my $bob_present = ReadingsVal("phone_bob","presence","absent");;\
if($bob_present eq "absent") {\
fhem("set all_lights off");;\
fhem("set thermostat desired-temp 16");;\
fhem("set security_system armed");;\
Log 1, "Everyone left, house secured";;\
}\
}
attr leave_home room Automation

Complex Scenes

# Movie scene
define movie_scene dummy
attr movie_scene room Scenes
attr movie_scene alias Movie Scene
attr movie_scene setList on off
define movie_scene_on notify movie_scene:on {\
fhem("set living_light brightness 32");;\
fhem("set tv on");;\
fhem("set av_receiver input HDMI1");;\
fhem("set blinds closed");;\
Log 1, "Movie scene activated";;\
}
attr movie_scene_on room Automation
define movie_scene_off notify movie_scene:off {\
fhem("set living_light brightness 200");;\
fhem("set blinds open");;\
}
attr movie_scene_off room Automation
# Vacation mode
define vacation_mode dummy
attr vacation_mode room Scenes
attr vacation_mode alias Vacation Mode
attr vacation_mode setList on off
define vacation_mode_on notify vacation_mode:on {\
fhem("set random_lights at +*04:00:00 set living_light toggle");;\
fhem("set security_camera recording continuous");;\
fhem("set mail_forward enabled");;\
Log 1, "Vacation mode activated";;\
}
attr vacation_mode_on room Automation

Production Best Practices

Security Hardening

  1. Use Strong Passwords

    Set a strong password for the FHEM web interface:

    set WEB password $(openssl rand -base64 32)
  2. Disable Telnet from Internet

    Telnet should only listen on localhost (already configured in example fhem.cfg):

    attr telnetPort globalattr 127.0.0.1:7072
  3. Use HTTPS

    Klutch.sh automatically provides HTTPS for your app URL, ensuring encrypted communication.

  4. Restrict Web Access by IP (Optional)

    attr WEB allowedHttpHosts example-app.klutch.sh
    attr WEB HTTPS 1
  5. Regular Updates

    Keep FHEM updated by modifying your Dockerfile to use the latest version:

    RUN wget -qO- https://fhem.de/fhem-6.3.tar.gz | tar xz

Backup Strategy

Implement a comprehensive backup strategy for your smart home configuration:

  1. Manual Configuration Backup

    FHEM stores all configuration in fhem.cfg and the /opt/fhem/data/ directory. These are automatically persisted to your Klutch.sh volumes.

  2. Automated Backups

    Create a daily backup automation:

    define daily_backup at 03:00:00 {\
    fhem("save");;\
    system("cp /opt/fhem/fhem.cfg /opt/fhem/data/backups/fhem-backup-$(date +\%Y\%m\%d).cfg");;\
    }
    attr daily_backup room System
  3. Export Configuration

    Regularly export your configuration to version control:

    Terminal window
    # From the FHEM web interface command line
    save

    Then download /opt/fhem/fhem.cfg and commit to Git.

  4. Volume Snapshots

    Klutch.sh’s persistent volumes ensure data durability. Consider additional off-site backups for critical configurations.

Performance Optimization

  1. Optimize Database Logging

    If using DbLog, set appropriate retention policies:

    attr myDbLog DbLogKeepDays 365
  2. Reduce Log Verbosity

    For production, reduce log verbosity:

    attr global verbose 2
  3. Disable Unused Modules

    Comment out or delete unused device definitions to reduce memory usage.

  4. Use Efficient Polling Intervals

    Avoid polling devices too frequently:

    # Good: Poll every 60 seconds
    attr temperature_sensor interval 60
    # Bad: Poll every second (unnecessary load)
    # attr temperature_sensor interval 1

Monitoring and Alerting

  1. Monitor FHEM Process

    The Dockerfile includes a health check that monitors port 8083. Klutch.sh will automatically restart the container if the health check fails.

  2. Create System Health Notifications

    define fhem_restart notify global:REREADCFG {\
    Log 1, "FHEM restarted at " . TimeNow();;\
    }
    attr fhem_restart room System
  3. Monitor Critical Devices

    define device_offline notify security_camera:state:offline {\
    fhem("set pushover_notification msg='Security camera offline!'");;\
    Log 1, "Critical device offline: security_camera";;\
    }
    attr device_offline room Monitoring
  4. Resource Usage Monitoring

    Monitor FHEM’s memory and CPU usage through Klutch.sh’s dashboard metrics.

High Availability Considerations

FHEM maintains device state internally, so horizontal scaling (multiple instances) is not recommended. For high availability:

  1. Use Persistent Volumes (already configured)
  2. Implement regular backups (see Backup Strategy above)
  3. Monitor health checks (included in Dockerfile)
  4. Quick disaster recovery: Keep your Git repository up to date so you can quickly redeploy if needed

Troubleshooting

Cannot Access FHEM Web Interface

Symptoms: Unable to reach FHEM web interface at the provided URL

Solutions:

  • Verify your app is running in the Klutch.sh dashboard
  • Check that the internal port is set to 8083
  • Ensure HTTP traffic type is selected
  • Review application logs for startup errors
  • Verify the health check is passing
  • Check that FHEM started successfully: Look for “Server started” in logs

FHEM Won’t Start

Symptoms: Container starts but FHEM process doesn’t run

Solutions:

  • Check the logs in Klutch.sh dashboard for Perl errors
  • Verify fhem.cfg syntax is correct (no Perl syntax errors)
  • Ensure all required Perl modules are installed in Dockerfile
  • Check file permissions for /opt/fhem/data and /opt/fhem/log
  • Verify persistent volumes are properly mounted

Devices Not Responding

Symptoms: Devices defined but not responding to commands

Solutions:

  • Verify device connection settings (IP address, port, credentials)
  • Check network connectivity between FHEM and devices
  • For MQTT: Verify broker connection with list mqttBroker
  • Check device logs: list device_name
  • Test device manually with direct commands
  • Verify IODev attribute points to correct connection device

MQTT Connection Issues

Symptoms: Cannot connect to MQTT broker

Solutions:

  • Verify broker hostname and port are correct
  • Check broker credentials (username/password)
  • Ensure broker is accessible from FHEM (test with: telnet mqtt-broker 1883)
  • Check broker logs for connection attempts
  • Verify firewall rules allow connection
  • Test with: get mqttBroker version

Automation Not Triggering

Symptoms: Defined notify/at commands don’t execute

Solutions:

  • Verify automation syntax is correct (check for Perl errors)
  • Check that the event pattern matches actual device events
  • Use list automation_name to see if it’s properly defined
  • Enable verbose logging: attr automation_name verbose 5
  • Test event matching with: trigger device_name event_name
  • Check the FHEM log for automation execution messages

Configuration Not Persisting

Symptoms: Changes lost after container restart

Solutions:

  • Verify persistent volumes are attached at /opt/fhem/data and /opt/fhem/log
  • Check volume mount paths in Klutch.sh dashboard
  • Ensure you’re running save command after making changes
  • Verify file permissions allow writes to volume directories
  • Check available disk space on volumes
  • Review Klutch.sh volume status in dashboard

High CPU Usage

Symptoms: FHEM consuming excessive CPU resources

Solutions:

  • Check for devices with very short polling intervals
  • Review automation rules for infinite loops
  • Disable verbose logging (set attr global verbose 2)
  • Check for misbehaving modules or plugins
  • Review log files for repetitive errors
  • Reduce number of concurrent operations
  • Optimize database logging intervals

Memory Leaks

Symptoms: Memory usage grows over time

Solutions:

  • Update to latest FHEM version (known memory leaks are fixed)
  • Restart FHEM periodically: define daily_restart at 03:00:00 shutdown restart
  • Limit log file sizes and rotation
  • Reduce DbLog retention period
  • Disable unused modules
  • Monitor memory usage through Klutch.sh dashboard

Advanced Configuration

Custom Perl Modules

FHEM’s Perl-based architecture allows extensive customization. To add custom Perl modules:

  1. Modify Dockerfile to Install CPAN Modules

    RUN cpan -T \
    Your::Custom::Module \
    Another::Module
  2. Create Custom FHEM Modules

    Create a file 99_mymodule.pm in your repository:

    package main;
    use strict;
    use warnings;
    sub mymodule_Initialize {
    my $hash = shift;
    # Module initialization code
    }
    1;
  3. Load Custom Module

    Place the file in /opt/fhem/FHEM/ and reload:

    reload 99_mymodule

Integrate with External APIs

FHEM can call external APIs for integrations:

# Weather API integration
define weather_api dummy
attr weather_api setList update:noArg
define weather_api_update notify weather_api:update {\
my $url = "https://api.openweathermap.org/data/2.5/weather?q=Berlin&appid=YOUR_API_KEY";;\
my $data = `curl -s "$url"`;;\
my $json = decode_json($data);;\
my $temp = $json->{main}{temp} - 273.15;;\
fhem("setreading weather_api temperature $temp");;\
}
attr weather_api_update room Weather

Multi-Language Support

FHEM supports multiple languages. To change the interface language:

attr WEB language DE
# Options: EN, DE, NL, FR, PL

Mobile App Integration

FHEM can integrate with mobile apps:

  1. FHEM Native App

    Available for iOS and Android. Configure connection in app:

    • URL: https://example-app.klutch.sh
    • Username: (if set)
    • Password: (your FHEM web password)
  2. Home Assistant Integration

    FHEM can export devices to Home Assistant via MQTT autodiscovery.

  3. Custom API Endpoints

    Create custom JSON endpoints for mobile apps:

    define api_endpoint weblink htmlCode {\
    return '{"temperature": ' . ReadingsVal("living_room_temp","temperature",0) . '}';;\
    }

Migrating from Existing FHEM Installation

If you’re migrating from an existing FHEM installation:

  1. Backup Current Configuration

    On your existing FHEM instance:

    Terminal window
    cd /opt/fhem
    ./fhem.pl fhem.cfg save
    tar czf fhem-backup.tar.gz fhem.cfg data/ log/
  2. Export Configuration File

    Copy your fhem.cfg to your new repository:

    Terminal window
    cp /opt/fhem/fhem.cfg /path/to/your/repo/fhem.cfg
  3. Update Configuration for Klutch.sh

    Edit fhem.cfg and update paths:

    # Change from:
    attr global logfile /var/log/fhem/fhem-%Y-%m-%d.log
    # To:
    attr global logfile /opt/fhem/log/fhem-%Y-%m-%d.log
  4. Deploy to Klutch.sh

    Follow the deployment steps in this guide.

  5. Restore Data Files

    If you have historical data to migrate, you can upload files to the persistent volume after deployment.


Integration Examples

Home Assistant Integration via MQTT

FHEM can publish device states to MQTT for Home Assistant consumption:

define mqtt2ha_temp notify living_room_temp:temperature:.* {\
my $temp = ReadingsVal("living_room_temp","temperature",0);;\
fhem("set mqttBroker publish homeassistant/sensor/fhem_temp/state $temp");;\
}
attr mqtt2ha_temp room Integration

Telegram Bot Integration

Control FHEM via Telegram:

# Define Telegram bot
define myBot TelegramBot YOUR_BOT_TOKEN
attr myBot defaultPeer @YOUR_TELEGRAM_ID
# Define command handler
define telegram_handler notify myBot:message:.* {\
my $msg = ReadingsVal("myBot","message","");;\
if($msg =~ /\/lights on/) {\
fhem("set all_lights on");;\
fhem("set myBot message 'Lights turned on'");;\
} elsif($msg =~ /\/temp/) {\
my $temp = ReadingsVal("living_room_temp","temperature",0);;\
fhem("set myBot message 'Temperature: $temp°C'");;\
}\
}
attr telegram_handler room Integration

Grafana Dashboard Integration

Visualize FHEM data in Grafana:

  1. Configure DbLog to PostgreSQL (see Data Logging section)
  2. Add PostgreSQL data source in Grafana
  3. Create queries to visualize FHEM device data

Voice Assistant Integration

Integrate with Google Home or Alexa via MQTT and Home Assistant bridge, or use FHEM’s built-in Alexa module:

# Alexa integration
define myAlexa alexa
attr myAlexa room Voice

Additional Resources


Conclusion

Deploying FHEM to Klutch.sh provides a robust, cloud-hosted smart home automation platform with extensive device support, powerful automation capabilities, and complete privacy control. With persistent storage for configurations and logs, a comprehensive web interface, and support for hundreds of protocols and devices, your FHEM instance on Klutch.sh is ready to power your entire smart home automation system. The Perl-based architecture allows virtually unlimited customization, while the active community ensures continuous improvements and new device support.