Exemplo n.º 1
0
        public async Task TestFetchStates()
        {
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ");

            Assert.True(result);
            Assert.True(wscli.States.Count == 19);
            Assert.True(wscli.States["binary_sensor.vardagsrum_pir"].State == "on");
            await wscli.CloseAsync();
        }
Exemplo n.º 2
0
        public async Task TestBasicLoginFail()
        {
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "WRONG PASSWORD",
                                                   false);

            Assert.False(result);
            Assert.True(wscli.States.Count == 0);

            await wscli.CloseAsync();
        }
Exemplo n.º 3
0
        public async Task TestBasicLoginOK()
        {
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                   false);

            Assert.True(result);
            Assert.True(wscli.States.Count == 0);

            await wscli.CloseAsync();
        }
Exemplo n.º 4
0
        public async Task RemoteCloseThrowsException()
        {
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                   false).ConfigureAwait(false);

            // Skip first authorize message
            var eventTask = wscli.ReadEventAsync();
            await wscli.SendMessage(new CommandMessage { Id = 2, Type = "fake_disconnect_test" }).ConfigureAwait(false);

            await Assert.ThrowsAsync <OperationCanceledException>(async() => await eventTask.ConfigureAwait(false)).ConfigureAwait(false);
        }
Exemplo n.º 5
0
        public async Task TestPingPong()
        {
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                   false);

            Assert.True(result);

            bool pongReceived = await wscli.PingAsync(1000);

            Assert.True(pongReceived);
            await wscli.CloseAsync();
        }
Exemplo n.º 6
0
        public async Task TestServerFailedConnect()
        {
            var loggerFactoryMock = new LoggerFactoryMock();

            await using var wscli = new HassClient(loggerFactoryMock);
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket_not_exist"),
                                                   "ABCDEFGHIJKLMNOPQ");

            Assert.False(result);
            Assert.True(loggerFactoryMock.LoggedError);
            Assert.True(loggerFactoryMock.LoggedDebug);
            Assert.False(loggerFactoryMock.LoggedTrace);
            await wscli.CloseAsync();
        }
Exemplo n.º 7
0
        public async Task TestClose()
        {
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                   false);

            Assert.True(result);
            Assert.True(wscli.States.Count == 0);
            // Wait for event that never comes
            var eventTask = wscli.ReadEventAsync();
            // Do close
            await wscli.CloseAsync();

            Assert.Throws <AggregateException>(() => eventTask.Result);
        }
Exemplo n.º 8
0
        public async Task TestSubscribeEvents()
        {
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                   false);

            Assert.True(result);

            Assert.True(await wscli.SubscribeToEvents());
            HassEvent eventMsg = await wscli.ReadEventAsync();

            var stateMessage = eventMsg?.Data as HassStateChangedEventData;

            Assert.True(stateMessage != null && stateMessage.EntityId == "binary_sensor.vardagsrum_pir");

            Assert.True(stateMessage.OldState?.EntityId == "binary_sensor.vardagsrum_pir");
            Assert.True(stateMessage.OldState?.Attributes != null &&
                        ((JsonElement)stateMessage.OldState?.Attributes?["battery_level"]).GetInt32() ! == 100);
            Assert.True(((JsonElement)stateMessage.OldState?.Attributes?["on"]).GetBoolean() !);
            Assert.True(((JsonElement)stateMessage.OldState?.Attributes?["friendly_name"]).GetString() ! ==
                        "Rörelsedetektor TV-rum");

            // Test the date and time conversions that it matches UTC time
            DateTime?lastChanged = stateMessage.OldState?.LastChanged;
            // Convert utc date to local so we can compare, this test will be ok on any timezone
            DateTime targetChanged = new DateTime(2019, 2, 17, 11, 41, 08, DateTimeKind.Utc).ToLocalTime();

            // Test the date and time conversions that it matches UTC time
            DateTime?lastUpdated = stateMessage.OldState?.LastUpdated;
            // Convert utc date to local so we can compare, this test will be ok on any timezone
            DateTime targetUpdated = new DateTime(2019, 2, 17, 11, 42, 08, DateTimeKind.Utc).ToLocalTime();

            Assert.True(lastChanged.Value.Year == targetChanged.Year);
            Assert.True(lastChanged.Value.Month == targetChanged.Month);
            Assert.True(lastChanged.Value.Day == targetChanged.Day);
            Assert.True(lastChanged.Value.Hour == targetChanged.Hour);
            Assert.True(lastChanged.Value.Minute == targetChanged.Minute);
            Assert.True(lastChanged.Value.Second == targetChanged.Second);

            Assert.True(lastUpdated.Value.Year == targetUpdated.Year);
            Assert.True(lastUpdated.Value.Month == targetUpdated.Month);
            Assert.True(lastUpdated.Value.Day == targetUpdated.Day);
            Assert.True(lastUpdated.Value.Hour == targetUpdated.Hour);
            Assert.True(lastUpdated.Value.Minute == targetUpdated.Minute);
            Assert.True(lastUpdated.Value.Second == targetUpdated.Second);
            await wscli.CloseAsync();
        }
Exemplo n.º 9
0
        public async Task TestGetAreas()
        {
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ", false);


            // ACT
            // HassEvent eventMsg = await hassClient.ReadEventAsync();
            var areas = await wscli.GetAreas().ConfigureAwait(false);

            var first = areas.FirstOrDefault();

            // ASSERT
            Assert.NotNull(areas);
            Assert.NotNull(first);
            Assert.Equal("Bedroom", first.Name);
            Assert.Equal("5a30cdc2fd7f44d5a77f2d6f6d2ccd76", first.Id);

            Assert.Equal(3, areas.Count());
        }
Exemplo n.º 10
0
        public async Task TestGetEntities()
        {
            // ARRANGE
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ", false);

            // ACT

            var entities = await wscli.GetEntities().ConfigureAwait(false);

            var first = entities.FirstOrDefault();

            // ASSERT
            Assert.NotNull(entities);
            Assert.NotNull(first);
            Assert.Null(first.Name);
            Assert.Null(first.Icon);
            Assert.Equal("42cdda32a2a3428e86c2e27699d79ead", first.DeviceId);
            Assert.Equal("media_player.tv_uppe2", first.EntityId);

            Assert.Equal(2, entities.Count());
        }
Exemplo n.º 11
0
        public async Task TestGetDevices()
        {
            // ARRANGE
            await using var wscli = new HassClient();
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ", false);


            // ACT
            var devices = await wscli.GetDevices().ConfigureAwait(false);

            var first = devices.FirstOrDefault();

            // ASSERT
            Assert.NotNull(devices);
            Assert.NotNull(first);
            Assert.Null(first.NameByUser);
            Assert.Null(first.AreaId);
            Assert.Equal("Google Inc.", first.Manufacturer);
            Assert.Equal("42cdda32a2a3428e86c2e27699d79ead", first.Id);
            Assert.Equal("Chromecast", first.Model);
            Assert.Equal("My TV", first.Name);

            Assert.Equal(2, devices.Count());
        }
Exemplo n.º 12
0
        private static async Task ConnectToHomeAssistant(string ip, short port, bool events, string token)
        {
            ILoggerFactory factory = LoggerFactory.Create(builder =>
            {
                builder
                .ClearProviders()
                // .AddFilter("HassClient.HassClient", LogLevel.Trace)
                .AddConsole()
                .AddDebug()
                .SetMinimumLevel(LogLevel.Trace);
            });

            await using IHassClient client = new HassClient(factory);
            var token_env = Environment.GetEnvironmentVariable("HASS_TOKEN");

            if (token_env != null)
            {
                token = token_env;
            }

            bool connected = await client.ConnectAsync(ip, port, false, token, true);

            if (!connected)
            {
                Console.WriteLine("Failed to connect to Home assistant.. bailing...");
                return;
            }

            Console.WriteLine("Login success");
            if (client.States != null)
            {
                Console.WriteLine($"Number of states: {client.States.Count}");
            }

            var services = await client.GetServices();

            var tempTest = client.States["sensor.frysnere_temperature"];

            if (events)
            {
                // Subscribe to all events
                await client.SubscribeToEvents();
            }

            // await client.CallService("light", "toggle", new { entity_id = "light.tomas_rum" });
            await client.CallService("light", "no_exist", new { entity_id = "light.tomas_rum_not_exist" });

            //var tt = await client.SetState("sensor.csharp", "cool", new {daemon = true});

            //var result = await client.SendEvent("test_event", new { data="hello" });
            while (true)
            {
                try
                {
                    HassEvent eventMsg = await client.ReadEventAsync();

                    // if (nrOfTimes++ > 8)
                    // {
                    //     await client.DisposeAsync();
                    //     System.Console.WriteLine("Closing and returning...");
                    //     return;
                    // }
                    //Console.WriteLine($"Eventtype: {eventMsg.EventType}");
                    if (eventMsg.EventType == "state_changed")
                    {
                        var stateMessage = eventMsg?.Data as HassStateChangedEventData;

                        Console.WriteLine(
                            $"{stateMessage.EntityId}: {stateMessage.OldState.State}->{stateMessage.NewState.State}");
                    }
                    else if (eventMsg.EventType == "call_service")
                    {
                        var serviceMessage = eventMsg?.Data as HassServiceEventData;
                        serviceMessage.ServiceData = null;
                        Console.WriteLine($"{serviceMessage.Service}: {serviceMessage.ServiceData}");
                    }
                    else
                    {
                        Console.WriteLine("event!");
                    }
                }
                catch (OperationCanceledException)
                {
                    // Graceful
                    return;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error", e);
                    return;
                }
            }
        }
Exemplo n.º 13
0
        private static async Task DoPerformanceTest()
        {
            using var mock = new HomeAssistantMockHandler();
            int  NR_OF_REQUESTS = 200000;
            var  wscli          = new HassClient();
            bool result         = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                           false);

            var  wscli2  = new HassClient();
            bool result2 = await wscli2.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                     false);

            var  wscli3  = new HassClient();
            bool result3 = await wscli3.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                     false);

            var  wscli4  = new HassClient();
            bool result4 = await wscli4.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                     false);

            var  wscli5  = new HassClient();
            bool result5 = await wscli5.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                     false);

            var  wscli6  = new HassClient();
            bool result6 = await wscli6.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket"), "ABCDEFGHIJKLMNOPQ",
                                                     false);

            var stopWatch = Stopwatch.StartNew();
            var first     = Task.Run(async() =>
            {
                for (int i = 0; i < NR_OF_REQUESTS; i++)
                {
                    await wscli.PingAsync(1000);
                }
            });
            var second = Task.Run(async() =>
            {
                for (int i = 0; i < NR_OF_REQUESTS; i++)
                {
                    await wscli2.PingAsync(1000);
                }
            });

            var third = Task.Run(async() =>
            {
                for (int i = 0; i < NR_OF_REQUESTS; i++)
                {
                    await wscli3.PingAsync(1000);
                }
            });

            var fourth = Task.Run(async() =>
            {
                for (int i = 0; i < NR_OF_REQUESTS; i++)
                {
                    await wscli4.PingAsync(1000);
                }
            });

            var fifth = Task.Run(async() =>
            {
                for (int i = 0; i < NR_OF_REQUESTS; i++)
                {
                    await wscli5.PingAsync(1000);
                }
            });

            var sixth = Task.Run(async() =>
            {
                for (int i = 0; i < NR_OF_REQUESTS; i++)
                {
                    await wscli6.PingAsync(1000);
                }
            });

            Console.WriteLine("WAIT ALL");
            Task.WaitAll(first); //, second, third, fourth, fifth, sixth
            stopWatch.Stop();
            Console.WriteLine(stopWatch.ElapsedMilliseconds);
            Console.WriteLine("Took {0} seconds with performance of {1} roundtrips/s",
                              stopWatch.ElapsedMilliseconds / 1000, NR_OF_REQUESTS * 6 / (stopWatch.ElapsedMilliseconds / 1000));
            Console.WriteLine("DISCONNECTS!");
            await wscli.CloseAsync();

            await wscli2.CloseAsync();

            await wscli3.CloseAsync();

            await wscli4.CloseAsync();

            await wscli5.CloseAsync();

            await wscli6.CloseAsync();
        }