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:
mkdir fhem-klutchcd fhem-klutchgit initStep 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 packagesRUN 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 FHEMWORKDIR /optRUN 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 directoriesRUN mkdir -p /opt/fhem/log && \ mkdir -p /opt/fhem/data && \ chmod 755 /opt/fhem
# Set working directoryWORKDIR /opt/fhem
# Expose FHEM web interface portEXPOSE 8083
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ CMD nc -z localhost 8083 || exit 1
# Start FHEMCMD ["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 settingsattr global logfile /opt/fhem/log/fhem-%Y-%m-%d.logattr global modpath /opt/fhemattr global statefile /opt/fhem/data/fhem.saveattr global verbose 3attr global autoload_undefined_devices 1attr global uniqueID 98d6b001f9a2a1234567890abcdef012
# Define telnet interface (local only for security)define telnetPort telnet 7072 localhost
# Define web interfacedefine WEB FHEMWEB 8083 globalattr WEB plotmode SVGattr WEB plotfork 1attr WEB csrfToken random123456789attr WEB stylesheetPrefix f18
# Define allowed devicesdefine allowed allowed
# Example: Define an MQTT client (configure after deployment)# define mqttClient MQTT 127.0.0.1:1883
# Example: Define a dummy device for testingdefine TestDevice dummyattr TestDevice room Systemattr TestDevice alias Test Device
# Enable autocreate for new devicesdefine autocreate autocreateattr autocreate filelog /opt/fhem/log/autocreate-%Y-%m-%d.log
# Save configuration on shutdowndefine ShutdownSave at *shutdown save
# Initialize doneConfiguration Notes:
- Sets up logging to
/opt/fhem/log/for persistent logs - Configures state file at
/opt/fhem/data/fhem.saveto 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 modulesRUN 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 modulesRUN cpan -T \ Device::USB \ Protocol::WebSocket \ LWP::Protocol::https \ && rm -rf /root/.cpan
# Install FHEMWORKDIR /optRUN wget -qO- https://fhem.de/fhem-6.3.tar.gz | tar xz && \ mv fhem-6.3 fhem
# Set proper permissionsRUN 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 existsCOPY fhem.cfg /opt/fhem/fhem.cfg
# Set working directoryWORKDIR /opt/fhem
# Expose ports# 8083: FHEMWEB interface# 7072: Telnet interface (optional, localhost only)EXPOSE 8083 7072
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=90s --retries=3 \ CMD nc -z localhost 8083 || exit 1
# Environment variablesENV TZ=UTCENV FHEM_DIR=/opt/fhemENV FHEM_UID=6061ENV FHEM_GID=6061
# Start FHEMCMD ["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 Connectiondefine mqttBroker MQTT 192.168.1.100:1883attr mqttBroker clientId fhem-klutchattr mqttBroker username mqtt_userattr mqttBroker password mqtt_password
# MQTT Temperature Sensordefine livingroom_temp MQTT_DEVICEattr livingroom_temp IODev mqttBrokerattr livingroom_temp subscribeReading_temperature home/livingroom/temperatureattr livingroom_temp room Living Roomattr livingroom_temp alias Living Room Temperature
# ============================================# Z-Wave Devices# ============================================
# Z-Wave USB Controllerdefine ZWave ZWave /dev/ttyUSB0@115200attr ZWave room System
# Z-Wave Light Switchdefine kitchen_light ZWave_SWITCH_BINARY 3attr kitchen_light IODev ZWaveattr kitchen_light room Kitchenattr kitchen_light alias Kitchen Light
# ============================================# Zigbee Devices# ============================================
# Zigbee2MQTT Bridgedefine zigbee2mqtt MQTT2_DEVICEattr zigbee2mqtt IODev mqttBrokerattr zigbee2mqtt room Systemattr zigbee2mqtt devStateIcon online:10px-kreis-gruen offline:10px-kreis-rot
# Philips Hue Bulb via Zigbee2MQTTdefine bedroom_light MQTT2_DEVICEattr bedroom_light IODev mqttBrokerattr bedroom_light subscribeReading_state zigbee2mqtt/bedroom_light/stateattr bedroom_light setList on:noArg off:noArg toggle:noArg brightness:slider,0,1,254attr bedroom_light room Bedroomattr bedroom_light alias Bedroom Light
# ============================================# Homematic Devices# ============================================
# Homematic CCU Connectiondefine HM_CCU2 HMCCU 192.168.1.50attr HM_CCU2 ccuflags expertsattr HM_CCU2 room System
# Homematic Thermostatdefine heating_thermostat HMCCUDEV ABC1234567attr heating_thermostat IODev HM_CCU2attr heating_thermostat room Heatingattr heating_thermostat alias Living Room Thermostat
# ============================================# Network Devices# ============================================
# Network Presence Detectiondefine phone_john PRESENCE lan-ping 192.168.1.101attr phone_john room Presenceattr phone_john alias John's Phoneattr phone_john timeout 180
# ============================================# Virtual Devices and Automation# ============================================
# Virtual switch for scenedefine evening_scene dummyattr evening_scene room Scenesattr evening_scene alias Evening Sceneattr evening_scene setList on off
# ============================================# Data Logging# ============================================
# Temperature Logdefine FileLog_temp FileLog /opt/fhem/log/temp-%Y-%m-%d.log livingroom_temp:temperature.*attr FileLog_temp room Logsattr FileLog_temp logtype text
# Plot for temperaturedefine SVG_temp SVG FileLog_temp:SVG_temp:CURRENTattr SVG_temp room Plotsattr 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 sunsetdefine evening_lights at *{sunset()} set livingroom_light onattr evening_lights room Automation
# Turn off all lights at midnightdefine midnight_off at 00:00:00 set light_.*,TYPE=MQTT_DEVICE offattr 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 Automationattr arrive_home alias Arrival Automation
# Turn off lights when leavingdefine leave_home notify phone_john:absent.* {\ fhem("set livingroom_light off");;\ fhem("set kitchen_light off");;\}attr leave_home room Automationattr leave_home alias Departure Automation
# ============================================# Sensor-Based Automation# ============================================
# Turn on heating when temperature drops below 18°Cdefine 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 blindsdefine 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 awaydefine 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 hourlydefine power_log at +*01:00:00 {\ my $power = ReadingsVal("power_meter","power",0);;\ fhem("setreading power_daily consumption $power");;\}attr power_log room EnergyStep 7: Create Environment Configuration
Create a .env.example file to document optional environment variables:
# FHEM Environment Configuration# Copy to .env and customize as needed
# Timezone for FHEMTZ=UTC
# FHEM directories (these are defaults in Dockerfile)FHEM_DIR=/opt/fhemFHEM_LOG_DIR=/opt/fhem/logFHEM_DATA_DIR=/opt/fhem/data
# Security settings# Set to 1 to enable HTTPS for FHEMWEBFHEM_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-passwordStep 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 GitHub2. Create a new app on Klutch.sh3. Connect your GitHub repository4. Deploy with HTTP traffic on port 80835. 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 password3. 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:
# Build the Docker imagedocker build -t fhem-klutch .
# Run FHEM locallydocker 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 logsdocker logs -f fhem-test
# Access FHEM at http://localhost:8083
# Stop and remove when donedocker stop fhem-testdocker rm fhem-testFor 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:
docker-compose up -ddocker-compose logs -f fhemNote: 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:
git add Dockerfile fhem.cfg devices.cfg.example automation.cfg.example .env.example README.mdgit commit -m "Add FHEM Docker configuration for Klutch.sh"git remote add origin https://github.com/yourusername/fhem-klutch.gitgit push -u origin mainDeploying 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.
-
Log in to Klutch.sh
Navigate to klutch.sh/app and sign in to your account.
-
Create a New Project
Go to Create Project and give your project a meaningful name (e.g., “FHEM Smart Home”).
-
Create a New App
Navigate to Create App and configure the following settings.
-
Select Your Repository
- Choose GitHub as your Git source
- Select the repository containing your FHEM Dockerfile
- Choose the branch you want to deploy (usually
mainormaster)
-
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)
-
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.
-
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.
-
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)
-
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
-
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.shYou 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
-
Set Web Interface Password
In the FHEM web interface command input at the top, enter:
set WEB password your-secure-passwordThen reload the page. You’ll be prompted to enter your password.
-
Restrict Telnet Access
The telnet interface should only be accessible from localhost (already configured in
fhem.cfg). To verify:list telnetPortEnsure it shows
127.0.0.1:7072orlocalhost:7072. -
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:
-
Verify Autocreate is Enabled
The example
fhem.cfgalready includes autocreate. Check by entering in the command input:list autocreate -
Configure Protocol-Specific Discovery
Depending on your devices, configure the appropriate discovery modules:
For MQTT devices:
define mqttBroker MQTT mqtt.example.com:1883attr mqttBroker clientId fhem-klutchattr mqttBroker username your-mqtt-usernameattr mqttBroker password your-mqtt-passwordFor Zigbee2MQTT:
define zigbee2mqtt MQTT2_DEVICEattr zigbee2mqtt IODev mqttBrokerattr zigbee2mqtt subscribeReading_bridge_state zigbee2mqtt/bridge/state
Add Your First Device
Let’s add a simple MQTT temperature sensor as an example:
-
Define the Device
In the FHEM command input, enter:
define living_room_temp MQTT_DEVICEattr living_room_temp IODev mqttBrokerattr living_room_temp subscribeReading_temperature home/livingroom/temperatureattr living_room_temp room Living Roomattr living_room_temp alias Living Room Temperature -
Save Configuration
save -
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:
-
Create an Automation Rule
define morning_greeting notify global:INITIALIZED {\Log 1, "FHEM started successfully!";;\}attr morning_greeting room System -
Create a Scheduled Task
define evening_lights at *{sunset()} {\Log 1, "Evening lights automation triggered";;\}attr evening_lights room Automation -
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:
-
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:1883attr mqttBroker clientId fhem-smart-homeattr mqttBroker username mqtt_userattr mqttBroker password secure_passwordattr mqttBroker room System -
Add MQTT Device
# Temperature and humidity sensordefine bedroom_sensor MQTT_DEVICEattr bedroom_sensor IODev mqttBrokerattr bedroom_sensor subscribeReading_temperature home/bedroom/temperatureattr bedroom_sensor subscribeReading_humidity home/bedroom/humidityattr bedroom_sensor room Bedroomattr bedroom_sensor alias Bedroom Climate Sensor -
Add Controllable MQTT Device
# Smart light bulbdefine bedroom_light MQTT_DEVICEattr bedroom_light IODev mqttBrokerattr bedroom_light subscribeReading_state home/bedroom/light/stateattr bedroom_light publishReading_on home/bedroom/light/set ONattr bedroom_light publishReading_off home/bedroom/light/set OFFattr bedroom_light setList on offattr bedroom_light room Bedroomattr bedroom_light alias Bedroom Light
Zigbee Devices (via Zigbee2MQTT)
Zigbee2MQTT is a popular bridge for Zigbee devices. To integrate with FHEM:
-
Deploy Zigbee2MQTT
If you haven’t already, deploy Zigbee2MQTT with MQTT broker support.
-
Configure Zigbee2MQTT Bridge in FHEM
define zigbee2mqtt MQTT2_DEVICEattr zigbee2mqtt IODev mqttBrokerattr zigbee2mqtt room Systemattr zigbee2mqtt subscribeReading_state zigbee2mqtt/bridge/stateattr zigbee2mqtt subscribeReading_devices zigbee2mqtt/bridge/devices -
Add Zigbee Devices
# Philips Hue bulbdefine hue_living MQTT2_DEVICEattr hue_living IODev mqttBrokerattr hue_living subscribeReading_state zigbee2mqtt/hue_living/stateattr hue_living subscribeReading_brightness zigbee2mqtt/hue_living/brightnessattr hue_living setList on:noArg off:noArg brightness:slider,0,1,254attr hue_living room Living Roomattr hue_living alias Hue Living Room# Xiaomi temperature sensordefine xiaomi_temp MQTT2_DEVICEattr xiaomi_temp IODev mqttBrokerattr xiaomi_temp subscribeReading_temperature zigbee2mqtt/xiaomi_temp/temperatureattr xiaomi_temp subscribeReading_humidity zigbee2mqtt/xiaomi_temp/humidityattr xiaomi_temp subscribeReading_battery zigbee2mqtt/xiaomi_temp/batteryattr xiaomi_temp room Living Roomattr 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):
-
Configure CCU Connection
define HM_CCU HMCCU 192.168.1.50attr HM_CCU ccuflags expertsattr HM_CCU room System -
Add Homematic Devices
# Radiator thermostatdefine living_thermostat HMCCUDEV ABC1234567attr living_thermostat IODev HM_CCUattr living_thermostat room Living Roomattr living_thermostat alias Living Room Thermostat
Network-Based Presence Detection
Detect presence based on device network connectivity:
# Phone presence detection via pingdefine phone_alice PRESENCE lan-ping 192.168.1.101attr phone_alice room Presenceattr phone_alice alias Alice's Phoneattr phone_alice timeout 180
# Trigger automation based on presencedefine welcome_home notify phone_alice:present.* {\ fhem("set living_light on");;\ Log 1, "Alice arrived home";;\}attr welcome_home room AutomationData Logging and Visualization
FHEM includes powerful built-in tools for logging device data and creating visualizations.
Configure File Logging
-
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 Logsattr FileLog_temperature logtype text -
Create a Plot
define SVG_temperature SVG FileLog_temperature:SVG_temperature:CURRENTattr SVG_temperature room Plotsattr SVG_temperature label "Living Room Temperature History" -
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:
-
Deploy PostgreSQL on Klutch.sh
Follow the PostgreSQL deployment guide to create a database instance.
-
Configure DbLog Module
define myDbLog DbLog postgresql:database=fhem;host=postgres-app.klutch.sh;port=8000 fhem fhem_passwordattr myDbLog room Logsattr myDbLog DbLogType Currentattr myDbLog DbLogSelectionMode Include -
Configure What to Log
attr myDbLog DbLogInclude living_room_temp:temperature.*,bedroom_sensor:.*
Create a Dashboard
FHEM’s FHEMWEB interface supports customizable dashboards:
-
Create a Dashboard Room
define Dashboard dashboardattr Dashboard room Dashboard -
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_tempattr WEB dashboard_row1col2 bedroom_sensorattr 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 automationdefine 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 sunsetdefine 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 bedtimedefine 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 AutomationSensor-Triggered Automation
# Motion-activated lightingdefine 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 controldefine 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 AutomationPresence-Based Automation
# Arriving homedefine 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 homedefine 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 AutomationComplex Scenes
# Movie scenedefine movie_scene dummyattr movie_scene room Scenesattr movie_scene alias Movie Sceneattr 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 modedefine vacation_mode dummyattr vacation_mode room Scenesattr vacation_mode alias Vacation Modeattr 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 AutomationProduction Best Practices
Security Hardening
-
Use Strong Passwords
Set a strong password for the FHEM web interface:
set WEB password $(openssl rand -base64 32) -
Disable Telnet from Internet
Telnet should only listen on localhost (already configured in example
fhem.cfg):attr telnetPort globalattr 127.0.0.1:7072 -
Use HTTPS
Klutch.sh automatically provides HTTPS for your app URL, ensuring encrypted communication.
-
Restrict Web Access by IP (Optional)
attr WEB allowedHttpHosts example-app.klutch.shattr WEB HTTPS 1 -
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:
-
Manual Configuration Backup
FHEM stores all configuration in
fhem.cfgand the/opt/fhem/data/directory. These are automatically persisted to your Klutch.sh volumes. -
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 -
Export Configuration
Regularly export your configuration to version control:
Terminal window # From the FHEM web interface command linesaveThen download
/opt/fhem/fhem.cfgand commit to Git. -
Volume Snapshots
Klutch.sh’s persistent volumes ensure data durability. Consider additional off-site backups for critical configurations.
Performance Optimization
-
Optimize Database Logging
If using DbLog, set appropriate retention policies:
attr myDbLog DbLogKeepDays 365 -
Reduce Log Verbosity
For production, reduce log verbosity:
attr global verbose 2 -
Disable Unused Modules
Comment out or delete unused device definitions to reduce memory usage.
-
Use Efficient Polling Intervals
Avoid polling devices too frequently:
# Good: Poll every 60 secondsattr temperature_sensor interval 60# Bad: Poll every second (unnecessary load)# attr temperature_sensor interval 1
Monitoring and Alerting
-
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.
-
Create System Health Notifications
define fhem_restart notify global:REREADCFG {\Log 1, "FHEM restarted at " . TimeNow();;\}attr fhem_restart room System -
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 -
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:
- Use Persistent Volumes (already configured)
- Implement regular backups (see Backup Strategy above)
- Monitor health checks (included in Dockerfile)
- 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.cfgsyntax is correct (no Perl syntax errors) - Ensure all required Perl modules are installed in Dockerfile
- Check file permissions for
/opt/fhem/dataand/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_nameto 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/dataand/opt/fhem/log - Check volume mount paths in Klutch.sh dashboard
- Ensure you’re running
savecommand 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:
-
Modify Dockerfile to Install CPAN Modules
RUN cpan -T \Your::Custom::Module \Another::Module -
Create Custom FHEM Modules
Create a file
99_mymodule.pmin your repository:package main;use strict;use warnings;sub mymodule_Initialize {my $hash = shift;# Module initialization code}1; -
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 integrationdefine weather_api dummyattr 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 WeatherMulti-Language Support
FHEM supports multiple languages. To change the interface language:
attr WEB language DE# Options: EN, DE, NL, FR, PLMobile App Integration
FHEM can integrate with mobile apps:
-
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)
- URL:
-
Home Assistant Integration
FHEM can export devices to Home Assistant via MQTT autodiscovery.
-
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:
-
Backup Current Configuration
On your existing FHEM instance:
Terminal window cd /opt/fhem./fhem.pl fhem.cfg savetar czf fhem-backup.tar.gz fhem.cfg data/ log/ -
Export Configuration File
Copy your
fhem.cfgto your new repository:Terminal window cp /opt/fhem/fhem.cfg /path/to/your/repo/fhem.cfg -
Update Configuration for Klutch.sh
Edit
fhem.cfgand 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 -
Deploy to Klutch.sh
Follow the deployment steps in this guide.
-
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 IntegrationTelegram Bot Integration
Control FHEM via Telegram:
# Define Telegram botdefine myBot TelegramBot YOUR_BOT_TOKENattr myBot defaultPeer @YOUR_TELEGRAM_ID
# Define command handlerdefine 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 IntegrationGrafana Dashboard Integration
Visualize FHEM data in Grafana:
- Configure DbLog to PostgreSQL (see Data Logging section)
- Add PostgreSQL data source in Grafana
- 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 integrationdefine myAlexa alexaattr myAlexa room VoiceAdditional Resources
- Klutch.sh Documentation
- Official FHEM Website
- FHEM Community Wiki
- FHEM Forum (German & English)
- FHEM Docker Repository
- Klutch.sh Volumes Guide
- Klutch.sh Networking Guide
- PostgreSQL on Klutch.sh (for DbLog)
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.