GithubHelp home page GithubHelp logo

hadotnet's People

Contributors

qjake avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hadotnet's Issues

ClientFactory.Initialize, how to check if connection is established ?

Hi, how to check if connection with Home Assistance is established correcly? Im asking because after checking with ClientFactory.IsInitialized I see true even if I set wrong ip adress of my Home Assistance.

Another question, Can I use ClientFactory.Initialize with local adress ?

e. g ClientFactory.Initialize("https://homeassistant.local:8123/", "abcd....

C# Friendly Entity Classes

New Feature Description

Hey, I'd love to help with this project, and I will give the caveat that I'm still fairly new to C# and .NET so I want to make sure I'm not reinventing the wheel or missing that this feature may already be present.

Any feedback on if this should not be done this way, or if this has already been done, or if there's a better way/reason to just plain not do it would be welcome. I'd obviously be doing things like passing brightness and color as optional parameters, this is a very very basic example to check if this is something you'd like to have added.

Code Example

   public class Light
    {
        private static string domain => "light";

        /// <summary>
        /// The entity name in HA for the light
        /// </summary>
        public string EntityName { get; }

        /// <summary>
        /// Constructor that takes the entity name of the light to control as a string (Do not prepend light. to the entity name.)
        /// </summary>
        /// <param name="lightEntityName"></param>
        public Light(string lightEntityName)
        {
            EntityName = lightEntityName;
            serviceClient = ClientFactory.GetClient<ServiceClient>();
        }

        /// <summary>
        /// Calls the turn_on service in HA for the light
        /// </summary>
        /// <returns></returns>
        public List<StateObject> TurnOn()
        {
            var resultingState = serviceClient.CallService(domain, "turn_on", new { entity_id = $"{domain}.{EntityName}" });

            return resultingState.Result;
        }

        /// <summary>
        /// Calls the turn_off service in HA for the light
        /// </summary>
        /// <returns></returns>
        public List<StateObject> TurnOff()
        {
            var resultingState = serviceClient.CallService(domain, "turn_off", new { entity_id = $"{domain}.{EntityName}" });

            return resultingState.Result;
        }

        private ServiceClient serviceClient;
    }

HA API Docs or Sample

Deserializing array in attributes does not work

Describe the Problem

When calling the GetAttributeValue on a StateObject, it does not work in the case of (string) arrays.

Code Sample

Simple unittest example

[Test]
public async Task DeserializeArrayShouldWork()
{
    var statesClient = ClientFactory.GetClient<StatesClient>();
    var thermostat = await statesClient.GetState("climate.my_climate");

    // This throws an exception because it is actually a `JArray`
    var hvacModes = thermostat.GetAttributeValue<string[]>("hvac_modes");

    // This works
    var hvacModesJArray = thermostat.GetAttributeValue<JArray>("hvac_modes").Select(mode => (string) mode).ToArray();
}

Possible solutions:

  • Accept this and first cast to a JArray
    Feels hacky to me, because I have to know about Json in my host project.
  • Add a custom deserializer for the Attributes
  • Add a custom method something like public T GetAttributeArray<T>(string name) => ((JArray) Attributes[name]).Select(v => (T) v).ToArray();

HADotNet stopped working after 0.118 update

I'm using the latest HDDotNet.Core (1.3.2) to connect to my HomeAssistant server, which I updated today to 0.118.
However, suddenly my code stopped at this point:

// intialise hass client
ClientFactory.Initialize(Variables.HassIp, Variables.HassToken);

// retrieve config
 _configClient = ClientFactory.GetClient<ConfigClient>();

It's giving me this exception:

2020-11-19 12:46:05.253 +01:00 [FTL] Unexpected response code 0 from Home Assistant API endpoint /api/config.
System.Exception: Unexpected response code 0 from Home Assistant API endpoint /api/config.
   at HADotNet.Core.BaseClient.<Get>d__5`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at HADotNet.Core.Clients.ConfigClient.<GetConfiguration>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at HomeAssistantGrafanaUpdater.HomeAssistant.HassManager.<Initialise>d__4.MoveNext() in [REDACTED]HassManager.cs:line 31

Visual Studio is on the latest version (16.8.1), and the project uses .NET Framework 4.8.

Any idea what's happening?

TLS 1.3 - Authentication failed because the remote party sent a TLS alert: 'ProtocolVersion'.

Environment

  • Home Assistant Version: 2023.1.6
  • HADotNet Library Version: compiled from the source (06cc98c)
  • Visual Studio Version: 17.4.4
  • API call or endpoint that is failing: authentication

Describe the Problem

My HA instance forces to use TLS 1.3 and I'm trying to use HASS.Agent which uses this library but during initial connection I got an error: The SSL connection could not be established, see inner exception.

Code Sample

ClientFactory.Initialize("https://my-home-assistant-url/", "AbCdEf0123456789...");
var configClient = ClientFactory.GetClient<ConfigClient>();
var config = await configClient.GetConfiguration(); //error

Exception logs:

System.Net.Http.HttpRequestException
  HResult=0x80131501
  Message=The SSL connection could not be established, see inner exception.
  Source=System.Net.Http
  Stack tracek:
   w System.Net.Http.ConnectHelper.<EstablishSslConnectionAsync>d__2.MoveNext()
   w System.Threading.Tasks.ValueTask`1.get_Result()
   w System.Net.Http.HttpConnectionPool.<ConnectAsync>d__98.MoveNext()
   w System.Threading.Tasks.ValueTask`1.get_Result()
   w System.Net.Http.HttpConnectionPool.<CreateHttp11ConnectionAsync>d__100.MoveNext()
   w System.Threading.Tasks.ValueTask`1.get_Result()
   w System.Net.Http.HttpConnectionPool.<AddHttp11ConnectionAsync>d__74.MoveNext()
   w System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.<WaitWithCancellationAsync>d__1.MoveNext()
   w System.Threading.Tasks.ValueTask`1.get_Result()
   w System.Net.Http.HttpConnectionPool.HttpConnectionWaiter`1.<WaitForConnectionAsync>d__5.MoveNext()
   w System.Threading.Tasks.ValueTask`1.get_Result()
   w System.Net.Http.HttpConnectionPool.<SendWithVersionDetectionAndRetryAsync>d__84.MoveNext()
   w System.Threading.Tasks.ValueTask`1.get_Result()
   w System.Net.Http.RedirectHandler.<SendAsync>d__4.MoveNext()
   w System.Net.Http.HttpClient.<<SendAsync>g__Core|83_0>d.MoveNext()
   w HADotNet.Core.BaseClient.<Get>d__6`1.MoveNext() w C:\Users\user\Desktop\HADotNet-master\HADotNet.Core\BaseClient.cs:wiersz 38
   w HADotNet.Core.Clients.ConfigClient.<GetConfiguration>d__1.MoveNext() w C:\Users\user\Desktop\HADotNet-master\HADotNet.Core\Clients\ConfigClient.cs:wiersz 22
   w Program.<<Main>$>d__0.MoveNext() w C:\Users\user\Desktop\HADotNet-master\ConsoleApp1\Program.cs:wiersz 10

Inner Exception 1:
AuthenticationException: Authentication failed because the remote party sent a TLS alert: 'ProtocolVersion'.

Inner Exception 2:
Win32Exception: The message received was unexpected or badly formatted.

project test

Hello,
in order to test the test project,
you need to have installed in visual studio 2017, asp.net core??
Thanks you, Víctor.

Donation

Hey Jake, not really an issue but you're a hard man to reach - not even an e-mail address on your site ;)

This project saved me a lot of time and is really great & fun to use, so I'd love to do a one-time donation. However, the github sponsoring system is monthly-based. Maybe add a donation button on the readme page? There are a bunch of services that provide such a service.

Regardless; thanks for all your hard work and making it opensource!

Exception: Unexpected response code 404 from Home Assistant API endpoint /api/states/.

System.Exception: Unexpected response code 404 from Home Assistant API endpoint /api/states/.
at HADotNet.Core.BaseClient.Get[T](String path)
at HADotNet.Core.Clients.StatesClient.GetState(String entityId)
at Hass_Alarm.Controllers.HomeController.Panel() in D:\HassIo\Hass-Alarm\Hass-Alarm\Controllers\HomeController.cs:line 63

i will test with the source to see where is the error, because the error message dont say much ...

home assistant core version : 0.105.5
operating system: 3.11
Supervisor version : 209

asp.net core 3.0

usage : https://github.com/werddomain/Hass-Alarm/blob/master/Hass-Alarm/Controllers/HomeController.cs

Issue with the Await and <EntityClient>

Hi there,
Thanks alot for the library, this is just what I needed for my project. I fairly new to APIs and I am trying to build an app that retrieves data from HassIO API. I have all the HassIO setup ready and I tried to retrieve data from the API using Python and it worked. However, I need to write my app using C#. I have installed your library and I tried to copy your code into an empty console program but I am getting these 2 errors that I didn't understand.

using System;
using HADotNet;
using HADotNet.Core;

namespace HASIO_API
{

class MainClass
{
    public static void Main(string[] args)
    {
        string toekn = "xxxxxxxx";
        string url = "http://hassio.local:8123";

        ClientFactory.Initialize(url, toekn);

        var entityClient = ClientFactory.GetClient<EntityClient>(); 

First Error The type or namespace name 'EntityClient' could not be found (are you missing a using directive or an assembly reference?)

        var filteredEntityList = await entityClient.GetEntities("sun.sun");

second error The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'

        Console.WriteLine(filteredEntityList);

    }

}

}

Thanks alot

Error deserializing /API/SERVICES

Hello,

when I do
var _ServiceClient = ClientFactory.GetClient<ServiceClient>(); var Services = await _ServiceClient.GetServices();

I get this strange exception at BaseCliente.CS line 49:

return JsonConvert.DeserializeObject<T>(resp.Content);

Unexpected character encountered while parsing value: {. Path '[7].services.apply.fields.entities.example', line 1, position 5643.

from newtonsoft.Json

The Json from HA is valid, but the library is having a problem parsing it.

I am using Home Assistant 0.107.6

this is the Json I got from HA.


[
   ...
   {
      "domain":"scene",
      "services":{
         "apply":{
            "description":"Activate a scene. Takes same data as the entities field from a single scene in the config.",
            "fields":{
               "entities":{
                  "description":"The entities and the state that they need to be.",
                  "example":{
                     "light.ceiling":{
                        "brightness":80,
                        "state":"on"
                     },
                     "light.kitchen":"on"
                  }
               }
            }
         },
         "create":{
            "description":"Creates a new scene.",
            "fields":{
               "entities":{
                  "description":"The entities to control with the scene.",
                  "example":{
                     "light.ceiling":{
                        "brightness":200,
                        "state":"on"
                     },
                     "light.tv_back_light":"on"
                  }
               },
               "scene_id":{
                  "description":"The entity_id of the new scene.",
                  "example":"all_lights"
               },
               "snapshot_entities":{
                  "description":"The entities of which a snapshot is to be taken",
                  "example":[
                     "light.ceiling",
                     "light.kitchen"
                  ]
               }
            }
         },
         "reload":{
            "description":"Reload the scene configuration",
            "fields":{

            }
         },
         "turn_on":{
            "description":"Activate a scene.",
            "fields":{
               "entity_id":{
                  "description":"Name(s) of scenes to turn on",
                  "example":"scene.romantic"
               }
            }
         }
      }
   }
   ...
]

Exposing RestClient or adding helper methods (solves client certificate auth)

New Feature Description

Right now if you use client certificate based auth with HA this library will fail. RestClient easily supports client certificates but it is protected in all the client classes so we can't add certs.

Options I see:

  • Just flip RestClient Client to public:
    protected RestClient Client { get; set; }
  • Add a .Configure(Action client) (not sure is much better)
  • Add specific method for adding client certs (although there may be other client prefs a user would want access to)

I can do a PR with the best action if desired

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.