예제 #1
0
    public BedroomMode(IHaContext ha, ILogger <BedroomMode> logger)
    {
        _logger   = logger;
        _entities = new Entities(ha);

        BedroomModeRelaxing();
    }
예제 #2
0
 public BasicTests(
     MakeSureNetDaemonIsRunningFixture _,
     IHaContext haContext
     )
 {
     _haContext = haContext;
 }
예제 #3
0
    public WeatherStationAmbientLight(IHaContext ha, ILogger <WeatherStationAmbientLight> logger)
    {
        _logger   = logger;
        _entities = new Entities(ha);

        SetBrightness();
    }
예제 #4
0
        public M3App(IHaContext ha)
        {
            Ha = ha;

            // Ha.CallService("notify", "persistent_notification", new { message = "Hello", title = "Yay it works in HassModel via HaContext" }, true);;

            _climateEntity = new ClimateEntity(ha, "climate.dummy_thermostat");

            _climateEntity.StateAllChanges().Where(e => e.New?.Attributes?.Temperature > 20).Subscribe();
            _climateEntity.StateAllChanges().Subscribe(OnNext);

            string?  state       = _climateEntity.State;
            string?  state2      = _climateEntity.EntityState?.State; // is the same
            DateTime?lastChanged = _climateEntity.EntityState?.LastChanged;

            Ha.StateChanges().Subscribe(e =>
            {
            });

            // Entity that has not changed yet is retrieved on demand
            var zone = new ZoneEntity(Ha, "zone.home");

            var lat = zone.Attributes?.latitude;

            var netEnergySensor = new NumericSensorEntity(Ha, "sensor.netto_energy");
            // NumericSensor has double? as state
            double?netEnergy  = netEnergySensor.State;
            double?netEnergy2 = netEnergySensor.EntityState?.State;

            netEnergySensor.StateChanges().Subscribe(e =>
                                                     Console.WriteLine($"{e.New?.Attributes?.FriendlyName} {e.New?.State} {e.New?.Attributes?.UnitOfMeasurement}"));

            // Prints: 'Netto energy 8908.81 kWh'
        }
예제 #5
0
 public static StateChange Map(this HassStateChangedEventData source, IHaContext haContext)
 {
     return(new StateChange(
                new Entity(haContext, source.EntityId),
                Map(source.OldState),
                Map(source.NewState)));
 }
예제 #6
0
 public ScheduledApp(IHaContext ha, INetDaemonScheduler scheduler)
 {
     scheduler.RunAt(new DateTime(2021, 11, 03, 9, 27, 0), () =>
     {
         //  ha.CallService("notify", "persistent_notification", data: new { message = "Another scheduled message", title = "Scheduled message!" });
     });
 }
예제 #7
0
 public Isolation3(IHaContext ha)
 {
     Console.WriteLine("isolator 2");
     ha.StateAllChanges().Subscribe(_ =>
     {
         Console.WriteLine("app 3");
     });
 }
예제 #8
0
 public YamlApp(IHaContext ha, IAppConfig <TestConfig> config)
 {
     ha?.CallService("notify", "persistent_notification", data: new
     {
         message = $"My sensor is {config?.Value.MySensor}",
         title   = "Hello config!"
     });
 }
예제 #9
0
 /// <summary>
 /// The observable state stream state change
 /// </summary>
 /// <remarks>
 /// Old state != New state
 /// </remarks>
 public static IObservable <StateChange> StateChanges(this IHaContext haContext)
 {
     if (haContext == null)
     {
         throw new ArgumentNullException(nameof(haContext));
     }
     return(haContext.StateAllChanges().StateChangesOnly());
 }
예제 #10
0
 public HelloApp(IHaContext ha, ILogger <HelloApp> logger)
 {
     // .Where(n => n.EventType == "test_event")
     ha?.Events.Where(n => n.EventType == "test_event").Subscribe(n =>
     {
         logger.LogInformation("Hello testevent");
     });
     ha?.CallService("notify", "persistent_notification", data: new { message = "Notify me", title = "Hello world!" });
 }
예제 #11
0
        public Isolation2(IHaContext ha)
        {
            Console.WriteLine("isolator 2");
            ha.StateAllChanges().Subscribe(_ =>
            {
                Console.WriteLine("app 2");

                //throw new Exception();
            });
        }
    public SetCurrentModes(IHaContext ha, INetDaemonScheduler scheduler, ILogger <HouseStateManager> logger)
    {
        _haContext = ha;
        _scheduler = scheduler;
        _log       = logger;
        _entities  = new Entities(ha);

        InitHouseStateTimeOfDay();
        InitHouseStateModes();
    }
예제 #13
0
    public FrontDoor(IHaContext ha, ILogger <FrontDoor> logger, IScheduler scheduler)
    {
        _logger    = logger;
        _entities  = new Entities(ha);
        _scheduler = scheduler;

        // TODO: Doorbell turn hallway light on
        // Perhaps also consider some do not disturb mode
        // TODO: Include door/doorbell to control porch light too
    }
예제 #14
0
        public CallServiceApp(IHaContext ha)
        {
            var climate = new ClimateEntity(ha, "climate.dummy_thermostat");

            climate.CallService("set_temperature",
                                new SetTemperatureData
            {
                HvacMode    = "heat",
                Temperature = 20,
            }
                                );
        }
예제 #15
0
    public SleepAnalyser(IHaContext ha, ILogger <SleepAnalyser> logger)
    {
        _logger   = logger;
        _entities = new Entities(ha);

        // TODO: Handle only one getting in or out of bed i.e. one is away
        // Possibly check if other sensor has been in off state > 30 mins
        // OR better still one is away
        ClaireThenAndyInBed();
        AndyThenClaireInBed();
        ClaireThenAndyOutOfBed();
        AndyThenClaireOutOfBed();
    }
예제 #16
0
 public BackDoorLightControl(IHaContext ha, ITextToSpeechService tts, ILogger <BackDoorLightControl> logger)
 {
     _tts      = tts;
     _logger   = logger;
     _entities = new Entities(ha);
     //var t = new Services(ha);
     //ha.Services.Tts.Say.
     PatioCameraPersonDetected();
     PatioCameraCarDetected();
     PatioDoorIsOpened();
     PatioNoMotionAndDoorClosed();
     PatioDoorClosed();
 }
예제 #17
0
 public Isolation1(IHaContext ha)
 {
     Console.WriteLine("isolator 1");
     ha.StateAllChanges().Subscribe(_ =>
     {
         Console.WriteLine("app 1.1");
         throw new Exception("Exception 1.1");
     });
     ha.StateAllChanges().Subscribe(_ =>
     {
         Console.WriteLine("app 1.2");
     });
 }
예제 #18
0
 public BasicApp(
     IHaContext haContext
     )
 {
     haContext.StateChanges()
     .Where(n =>
            n.Entity.EntityId == "input_select.who_cooks"
            )
     .Subscribe(
         s => haContext.CallService("input_text", "set_value",
                                    ServiceTarget.FromEntities("input_text.test_result"), new { value = s.New?.State })
         );
 }
    public BasementLights(IHaContext ha, ILogger <BasementLights> logger)
    {
        _logger   = logger;
        _entities = new Entities(ha);

        BasementHallLightOnMovement();
        BasementHallLightOffNoMovement();

        DiningRoomLightOnMovement();
        DiningRoomLightOffNoMovement();
        UtilityRoomLightOnMovement();
        UtilityRoomLightOffNoMovement();
        ToiletLightOnMovement();
        ToiletLightOffNoMovement();
    }
예제 #20
0
    /// <summary>
    ///     Creates a service in Home Assistant and registers a callback to be invoked when the service is called
    /// </summary>
    /// <param name="haContext">IHaContext to use</param>
    /// <param name="serviceName">The name of the service to create in Home Assistant. Will be prefixes with 'NetDaemon.'</param>
    /// <param name="callBack">The Action to invoke when the Service is called</param>
    /// <typeparam name="T">Type to deserialize the payload of the service into</typeparam>
    public static void RegisterServiceCallBack <T>(this IHaContext haContext, string serviceName, Action <T> callBack)
    {
        ArgumentNullException.ThrowIfNull(haContext);
        if (string.IsNullOrWhiteSpace(serviceName))
        {
            throw new ArgumentException("serviceName must have a value", serviceName);
        }

        haContext.CallService("netdaemon", "register_service", data: new { service = serviceName });

        haContext.Events.Filter <HassServiceEventData <T> >("call_service")
        .Where(e => e.Data?.domain == "netdaemon" &&
               string.Equals(e.Data?.service, serviceName, StringComparison.OrdinalIgnoreCase))
        .Subscribe(e => callBack.Invoke(e.Data !.service_data));
    }
예제 #21
0
    public HouseStateManager(IHaContext ha, INetDaemonScheduler scheduler, ILogger <HouseStateManager> logger)
    {
        _haContext = ha;
        _scheduler = scheduler;
        _log       = logger;
        _entities  = new Entities(ha);

        SetDayTime();
        //SetCleaning();
        SetEveningWhenLowLightLevel();
        SetNightTime();
        SetMorningWhenBrightLightLevel();

        InitHouseStateSceneManagement();
    }
예제 #22
0
    public LightModes(IHaContext ha, ILogger <LightModes> logger,
                      IScheduler scheduler, ILightingStates lightingStates)
    {
        _logger         = logger;
        _entities       = new Entities(ha);
        _scheduler      = scheduler;
        _lightingStates = lightingStates;

        _insideNoRoomControlNotBasement = new LightEntity[]
        {
            _entities.Light.Bathroom,
            _entities.Light.Mirror,
            _entities.Light.DrawingRoom,
            _entities.Light.Bookshelf,
            _entities.Light.DressingRoom,
            _entities.Light.GuestRoom,
            _entities.Light.Hallway,
            _entities.Light.HallwayLamp,
            _entities.Light.Kitchen,
            _entities.Light.BreakfastBarLamp,
            _entities.Light.Landing,
            _entities.Light.Studio
        };

        _bedroomLights = new LightEntity[]
        {
            _entities.Light.Bedroom,
            _entities.Light.BedsideLamp
        };

        _brightLightsNoRoomControl = new LightEntity[]
        {
            _entities.Light.Bathroom,
            _entities.Light.Hallway,
            _entities.Light.DrawingRoom,
            _entities.Light.Kitchen
        };

        _loungeLights = new LightEntity[]
        {
            _entities.Light.Lounge,
            _entities.Light.LoungeCornerLamp,
            _entities.Light.LoungeFloorLamp
        };

        BrightnessChanged();
        LightControlModeChanged();
    }
예제 #23
0
    /// <summary>
    ///     Set application state
    /// </summary>
    /// <param name="haContext">IHaContext to use</param>
    /// <param name="entityId">EntityId of the entity to create</param>
    /// <param name="state">Entity state</param>
    /// <param name="attributes">Entity attributes</param>
    public static void SetEntityState(this IHaContext haContext, string entityId, string state,
                                      object?attributes = null)
    {
        ArgumentNullException.ThrowIfNull(haContext);
        var currentState = haContext.GetState(entityId);
        var service      = currentState is null ? "entity_create" : "entity_update";

        // We have an integration that will help persist
        haContext.CallService("netdaemon", service,
                              data: new
        {
            entity_id = entityId,
            state,
            attributes
        });
    }
    public UpstairsLights(IHaContext ha, ILogger <UpstairsLights> logger, ILightingStates lightingStates)
    {
        _logger         = logger;
        _entities       = new Entities(ha);
        _lightingStates = lightingStates;

        LandingLightOnMovement();
        LandingLightOffNoMovement();
        BathroomLightsOnMovement();
        BathroomLightsOffNoMovement();
        BedroomLightsOnMovement();
        BedroomLightsOffNoMovement();
        GuestRoomLightOnMovement();
        GuestRoomLightOffNoMovement();
        DressingRoomLightOnMovement();
        DressingRoomLightOffNoMovement();
    }
예제 #25
0
    public LocalApp(
        IHaContext ha
        )
    {
        ha.StateChanges()
        .Where(n => n.Entity.EntityId == "binary_sensor.mypir" && n.New?.State == "on")
        .Subscribe(_ =>
        {
            ha.CallService("light", "turn_on", ServiceTarget.FromEntities("light.my_light"));
        });

        ha.StateChanges()
        .Where(n => n.Entity.EntityId == "binary_sensor.mypir_creates_fault" && n.New?.State == "on")
        .Subscribe(_ =>
        {
            throw new InvalidOperationException("Ohh nooo!");
        });
    }
예제 #26
0
 public ConcurrencyTestApp2(IHaContext context, ILogger <ConcurrencyTestApp2> logger)
 {
     context.StateChanges()
     .Where(n => n.Entity.EntityId == "input_select.who_cooks")
     .SubscribeAsyncConcurrent(async _ =>
     {
         logger.LogInformation("{Now}: Subscription 5 starts", DateTime.Now);
         await Task.Delay(1000).ConfigureAwait(false);
         logger.LogInformation("{Now}: Subscription 5 delay 1 s", DateTime.Now);
     });
     context.StateChanges()
     .Where(n => n.Entity.EntityId == "input_select.who_cooks")
     .Subscribe(_ =>
     {
         logger.LogInformation("{Now}: Subscription 6 starts", DateTime.Now);
         Task.Delay(2000).Wait();
         logger.LogInformation("{Now}: Subscription 6 delay 2 s", DateTime.Now);
     });
 }
    public DownstairsLights(IHaContext ha, ILogger <DownstairsLights> logger,
                            IScheduler scheduler, ILightingStates lightingStates)
    {
        _logger         = logger;
        _entities       = new Entities(ha);
        _scheduler      = scheduler;
        _lightingStates = lightingStates;

        // TODO: Fix Hallway motion sensor
        // TODO: Include door/doorbell to control hall lights too
        // HallwayLightOnMovement();
        // HallwayLightOffNoMovement();
        // HallwayLampOnMovement();
        // HallwayLampOffNoMovement();
        LoungeLightsOnMovement();
        LoungeLightsOffNoMovement();
        DrawingRoomLightsOnMovement();
        DrawingRoomLightsOffNoMovement();
        KitchenLightsOnMovement();
        KitchenLightsOffNoMovement();
    }
예제 #28
0
 /// <summary>
 /// Creates a new Entity instance
 /// </summary>
 public static Entity Entity(this IHaContext haContext, string entityId) => new (haContext, entityId);
예제 #29
0
 public HelloNewModelApp(IHaContext ha, INetDaemonScheduler scheduler)
 {
     // ha.CallService("notify", "persistent_notification", data: new { message = "it is a test app", title = "Hello HassModel!!" });
 }
예제 #30
0
 /// <summary>Constructor from haContext and entityId</summary>
 protected Entity(IHaContext haContext, string entityId) : base(haContext, entityId)
 {
 }