qjake / hadotnet Goto Github PK
View Code? Open in Web Editor NEW🏡 A .NET Standard library for Home Assistant.
License: Apache License 2.0
🏡 A .NET Standard library for Home Assistant.
License: Apache License 2.0
It would be great to be able to receive server sent events form the endpoint /api/stream and call a callback function when a event is received.
var ServerEventClient = ClientFactory.GetClient<ServerEventClient>();
ServerEventClient.Listen(ServerEventCallback());
https://developers.home-assistant.io/docs/external_api_server_sent_events
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....
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.
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;
}
When calling the GetAttributeValue
on a StateObject
, it does not work in the case of (string) arrays.
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();
}
JArray
Attributes
public T GetAttributeArray<T>(string name) => ((JArray) Attributes[name]).Select(v => (T) v).ToArray();
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?
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.
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.
Hello,
in order to test the test project,
you need to have installed in visual studio 2017, asp.net core??
Thanks you, Víctor.
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!
When accessing the GetStates the following error messages is thrown.
Unexpected response code 0 from Home Assistant API endpoint /api/states.
Any pointers would be greatly appreciated. This has only started happening recently. The version of HA that I am using is 2021.2.1
Thanks!
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
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
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"
}
}
}
}
}
...
]
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:
HADotNet/HADotNet.Core/BaseClient.cs
Line 18 in f2d6d25
I can do a PR with the best action if desired
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.