Create custom scene with .NET on Home Assist with use of Netdeamon plugin!
Introduction
This blog is explaining how to create a custom scene in Home Assistant and netDaemon using C# to make a lamp flash when motion is detected by a motion sensor:
Step 1: Install netDaemon and Home Assistant
Install netDaemon on your machine by following the instructions on the official documentation https://netdaemon.github.io/ Install Home Assistant on your computer, Raspberry Pi, or other compatible platform by following the instructions on https://www.home-assistant.io/installation/
Step 2: Set up your development environment for C#
Install Visual Studio or Visual Studio Code as your integrated development environment (IDE) Install the .NET 5.0 runtime and SDK if you haven’t done so already
Step 3: Create a new netDaemon app
Open Visual Studio or Visual Studio Code Create a new .NET Core console app Add the netDaemon nuget package to the project Make sure the app is set up to target the .NET 5.0 runtime
Step 4: Edit the Program.cs file
using System;
using System.Threading.Tasks;
using NetDaemon.Common;
using NetDaemon.Daemon;
class MotionDetector : NetDaemonApp
{
public override Task InitializeAsync()
{
Entity("binary_sensor.motion_sensor")
.WhenStateChange(from: "off", to: "on")
.Call(async (entityId, newState) =>
{
await Log("Motion detected! It's time to turn on the party lights.");
await CallService("light", "turn_on", new { entity_id = "light.lamp", flash = "short" });
});
Entity("binary_sensor.motion_sensor")
.WhenStateChange(from: "on", to: "off")
.Call(async (entityId, newState) =>
{
await Log("No motion detected. Time to turn off the party lights.");
await CallService("light", "turn_off", new { entity_id = "light.lamp" });
});
return Task.CompletedTask;
}
}
Step 5: Run the netDaemon app
- In Visual Studio or Visual Studio Code, press F5 to run the application
- The app should now be up and running and waiting for events from Home Assistant
And that’s it! Your lamp will now flash when motion is detected by the motion sensor. Make sure to replace the entity IDs with the correct IDs for your Home Assistant setup. Get ready to turn your home into a dance party every time motion is detected!