Giter Club home page Giter Club logo

csharptradfrilibrary's Introduction

C# Tradfri Library

This is a .NET Standard (2.0) library to communicate with the IKEA Trådfri (Tradfri) ZigBee-based Gateway. Using this library you can, by communicating with the gateway, control IKEA lights (including the RGB ones).

Build Status GitHub last commit NuGet downloads

This library is still in development, latest version:

NuGet downloads

Latest Gateway version tested and working - 1.10.43.

  • Get information on the gateway
  • Observe lights, groups and other resources
  • Get notified when lights, groups and other resources change
  • List all devices connected to gateway
  • List all lights and get attributes of lights (name, state, color temp, dimmer level etc)
  • Change attribute values of lights (currently only turn them on/off)
  • Restart and reset gateway

1. Usage

Download the nuget package v1.0.0.x+. You will need the following values:

  • gatewayName is your nickname to your gateway, currently this doesn't have an effect. It is here if you have access to multiple gateways so you can easily differentiate them.
  • gatewayIp is the IP-address to your gateway.
  • appName your name for your application. Be creative but wise with characters.
  • appSecret Instead of reusing key written on the back of your IKEA Tradfri Gateway you have to acquire new secret key specific for your application and then you should use appName and appSecret to connect. TradfriUI has an example on this, but it still does not implement encryption for the appSecret.

2. Example

From Gateway version 1.8.25 you can't use original PSK to connect to gateway anymore. You can only use it to create an application secret for your application which you can later reuse with it.

    // recommended
    // This line should only be called ONCE!!! per applicationName -> you define applicationName as you want
    // Gateway generates one appSecret key per applicationName
    TradfriAuth appSecret = controller.GenerateAppSecret("GatewaySecret", "ApplicationName");

    // You should now save programatically appSecret.PSK value (appsettings) and reuse it
    // when connecting to your gateway every other time
    controller.ConnectAppKey(appSecret.PSK, "ApplicationName");

    GatewayController gatewayController = controller.GatewayController;
    var devices = await gatewayController.GetDeviceObjects();

    DeviceController deviceController = controller.DeviceController;
    await deviceController.SetLight(devices[0], true);
    await deviceController.SetColor(devices[0], TradfriColors.SaturatedRed);

    // same works for `controller.GroupController`

3. Acknowledgements

This is an implementation based on analysis I found here by ggravlingen and here by vidarlo.

4. Authors

5. Old library

Old library is still available as nuget (latest version: 0.3.0.22) and won't be updated anymore. You can still read it's ReadMe if you are using it but we recommend to migrate to newer library as soon as you can.

6. Changelog

You can check the changelog here.

csharptradfrilibrary's People

Contributors

bjornpoppe avatar coriumalpha avatar davidwallis3101 avatar dependabot[bot] avatar dominicusmento avatar domjancik avatar johanjonsson1 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

csharptradfrilibrary's Issues

Observer Implementation

Hi tomidix,

I've seen in other Tradfri related libraries that they're using CoAP's Observe (CoAP Observe) functionality, after some simple and fast testing, I'd begin developing some Observe based controllers for the existing Get methods and they work properly.

I'd be glad to know if you're currently developing these methods (or going to in near future) yourself or if you will be interested in a pull request from mine with that implementation. Just let me know, because I think it will be interesting to have access to thoose controller methods and to be able to access the status of the devices without polling recursively. Thank you for your time.

Lights are not turning on/off when observing device

Hi,

I have created a UI app similar to the old GUI application which works with the .Net Standard library.
I have added 2 buttons:

  1. button which will turn all lights on:
    private async void button1_Click(object sender, EventArgs e) { foreach (var device in _devices) { if (device.DeviceType == DeviceType.Light) await _tradfriController.DeviceController.SetLight(device, true); } }
    _devices is my List instance with all devices, retrieved with tradfriController.GatewayController.GetDeviceObjects
  2. button which will turn the lights on using the group (I only have 1 group with 4 lights):
    await _tradfriController.GroupController.SetLight(_group, true);

Button 1 only turns the last light (of 4 lights) on (or off).
Button 2 does not turn a light on/off at all.

So, I tried to turn the lights on/off individually. I have tried to call await _tradfriController.DeviceController.SetLight(xx, true); for all 4 light device ID's, but it does not matter which ID I pass to the SetLight method, it always turns on/off the last light.

I think this is really strange behavior, so I analyzed my code a bit more and I also added the ObserveDevice method calls on the DeviceController property of the tradfriController instance. When I removed these method call, all lights and groups are correctly turned on/off.
So there is some strange behavior with the ObserveDevice method.

Does anyone have an idea what the problem is?

Thanks,
Danny

P.s. I am using a copy of the Tradfri project, where I set the CoapClient property of the TradfriController to public, so I am able to use this property for the ObserveDevice method call.

Please cleanup TradFriLibrary references

Hi,
First of all, this is a great library, so thanks a lot!

I noticed that a lot of referenced assemblies exist in the TradFriLibrary project:
image
I have created a new project and copied all the source code from this library (and tested if everything still worked) and see the references which are actually needed:
image

Could you please cleanup your library?
Thx,
Danny

C# use without UI

Hi
How do you use your library without GUI ? For example, I guess there is a function to connect to the gateway.

Since Ikea change the way to connect to the gateway, I can't connect anymore wth my own C# code :(

NullReferenceException in TradfriUI/main.cs

NullReferenceException occures in line 73 of TradfriUI/main.cs:
TradfriAuth appSecret = tradfriController.GenerateAppSecret(form.AppSecret, Properties.Settings.Default.appName);

tradfriController is not initialized yet at this stage.

It happens if EnterGatewayPSK dialog gets terminated by the button "Generate and Save".

IKEA Tradfri Gateway :

  • Firmware Version [1.9.27]

No devices returned by GetDeviceObjects, stalls application

Everything worked fine up until some days ago when GetDeviceObjects started to "break" my application. I added the source code to my project so I could debug the code, I've found that inside GatewayController the GetEntityCollectionIDs task doesn't return anything and silently stalls my application. Therefore GetDeviceObjects doesn't even hit its return statement.
If anyone could look into this that would be great.
Since this is quite a breaking issue I've taken it upon me to mention you
@tomidix

Interfaces

Has anyone any plans to implement interfaces to make mocking this easier?

[BUG] - Method not found Exception

This might be an obvious problem, but I am not sure if I have to add RestSharp manually.

Describe the bug
I get this exception when attempting to declare a controller.

To Reproduce
Steps to reproduce the behavior:

Just started a new implementation of the basic example (as seen in the screenshot), and just added the nuget package Tomidix.CSharpTradFriLibrary.

Screenshots
image

[Feature] - Rename a Device

Hi,

it would be great if it were possible to rename a Device. 👍

Thanks in Advance & Greetings ... Peter

[Question] - API Documentation

I want to play around with the Tradfri Gateway myself. Do you have documented the API you are using and are willing to share it?

CoapClient instance needed for ObserveDevice method on DeviceController

Hi,

I am trying to implement the new version (1.0.0.31) of the TradfriLibrary.
When I want to observe updates on a device, so I need to call the ObserveDevice method on the DeviceController:
public CoapObserveRelation ObserveDevice(CoapClient cc, TradfriDevice device, Action<TradfriDevice> callback, Action<CoapClient.FailReason> error = null)

You'll notice that a reference to the CoapClient is needed, which is a private member of the TradfriController instance:
private CoapClient _coapClient;

Can you update the code, so the CoapClient is public visible or change the ObserveDevice method, so the CoapClient instance is not needed anymore?

Thx,
Danny

[BUG] - GenerateAppSecret timeout

Thanks for your work! I think I've encountered a bug:

Describe the bug
Calling GenerateAppSecret when the hub is not available takes 145 seconds to complete, after which it throws a nullreference exception.

To Reproduce
Steps to reproduce the behavior:

  1. call GenerateAppSecret when the hub is not online.
  2. wait

Expected behavior
Throw some sort of descriptive error. Also the timeout should be configurable.

New GW-Firmware with new Authentication

tomidix,

first I would like to thank you for the cool library. I'm about to create a disco-light using NAudio and your tradfri-library.

While doing so I cam acrosse the following:
home-assistant/core#10252

IKEA apparently changed authentication in order not to require to save the GW-key in every app for apparent security reasons.

Instead, the introduce a connection oriented authentication with a connection-name and connection-key. This pair needs to be once obtained with the use of the GW-key.

Could you please adapt your library accordingly.

Thanks
Marioqx

Timeout connecting to Tradfri gateway

** Environment**
Visual Studio 2019 on Windows 10
Tradfri Gateway version 1.9.27 with DHCP IP 10.1.5.7

Code that fails
tradfriController = new TradfriController("GW", "10.1.5.7");
TradfriAuth appSecret = tradfriController.GenerateAppSecret("XXXXXXXXX", "Tradfri");

Where XXXXXXXXX is the gateway secret from the back of the gateway.

On execution the code hangs for about 30 seconds. When it returns appSecret is null.

I can ping 10.1.5.7. The Idea Tradfri App works fine.

Any suggestions of what im doing wrong if this isnt a bug would be hugely appreciated.

Thanks.

[BUG] - Generate Secret method doesn't work with newer gateway fw version (1.11.47)

My gateway version is 1.11.47
I tried to use this sample code:

const string password = "ThisIsMySecretPassword";
const string applicationName = "TradfriControllerApp";
const string ipAddress = "192.168.0.230";
var controller = new TradfriController("Tradfri", ipAddress);
TradfriAuth appSecret = controller.GenerateAppSecret(password, applicationName);

It throws an exception: "Timeout Generating App Secret."
I've tried to increase the AckTimeout value but no luck.

Also the app writes this to the console:
"15:11:10 [DTLSClientChannel] Error - Failed to establish a DTLS session"

When checked the raw network data with Wireshark, this was the result:

image

image

[Feature] - Set light Color & Dimmer with transition in one call

Hi, first thank you for this library!
With LINQPad and your library, it's a matter of few minutes to start writing first simple lights automation scripts.

Is your feature request related to a problem? Please describe.
When I want to change both Color and Dimmer of the light, I have to do 2 separate calls:
DeviceController.SetColor(device, color, transition);
DeviceController.SetDimmer(device, dimmer, transition);

But when I include transition, first call transition effect is simply skipped by executing second call.

Describe the solution you'd like
Solution would be to add public method which allows to set both color and dimmer with transition time.
It looks like internal lower level API inside SetColor/SetDimmer allows to set both values inluding transition, it just needs to add appropriate public methods.

[request] implement wrapper for setting CIE Yxy colors

I have made use of the preset Tradfri colors in the library. However when I wanted to create custom colors by setting the value in coap 5709 and 5710 there really weren't any function available.
Perhaps someone could take a crack at implementing it, as I find great use in the library!
Some material to explain what CIE colors are:
Info on the colors:
https://github.com/ffleurey/ThingML-Tradfri

If anyone needs additional info, I can hopefully supply it.

"implementation requirements"

  • The ability to put values between 0 and 65535 into 5709 (x color) and 5710 (y color)
  • (Optional) color conversion from say RGB to CIE Yxy colors to put into x color and y color

[BUG] - Unable to connect to gateway

Describe the bug
I have a newly installed IKEA gateway up and running on my local network. I have one smart blind with the repeater working and the IKEA app works as expected.
When I try to run the example code, the connection to the gateway eventually times out and I end up on row 172 in TradfriController.cs

To Reproduce
Steps to reproduce the behavior:

  1. Setup a fresh IKEA gateway with one IKEA smart blind connected
  2. Download a fresh repo of the CSharpTradFriLibrary
  3. Fix the missing Restsharp reference issue (I already sent a PR for this)
  4. Try and run the following code:
    var controller = new TradfriController("my-gw", "1.2.3.4"); // Replace with actual IP
    TradfriAuth appSecret = controller.GenerateAppSecret("GatewaySecret", "ApplicationName");

The code ends up with a timeout exception in the GenerateAppSecret method on row 172 in TradfriController.cs:

if (r.IsTimedOut)
    throw new Exception("Timeout Generating App Secret.");

Expected behavior
I would expected to get a generated app secret back

Desktop (please complete the following information):

  • OS: Windows 10 Pro
  • Browser: Chrome based Edge

IKEA Tradfri Gateway (please complete the following information):

  • Firmware Version: 1.10.36 (according to the IKEA app)

[Feature] - documentation

Dear

Is it posible to use some documentation ?
For example a simple blinky?

With best regards Ben

Connect Method with invalid details doesnt throw

In the example you have this:

            try
            {
                devices = new List<TradFriDevice>();
                gatewayConnection = new TradFriCoapConnector(Properties.Settings.Default.GatewayName, Properties.Settings.Default.GatewayIP, Properties.Settings.Default.GatewaySecret);
                gatewayConnection.Connect();
            }
            catch (Exception)
            {
                MessageBox.Show("Couldn't connect to TradFri gateway with provided settings");
                Environment.Exit(0);
            }

however if you feed duff names (ie imaginary ip address and secret) no exeception is thrown

Status

Am I missing it somewhere but is it possible to get the status of the bulb from the controller.. IE if I switch it on with the remote - can I get the status from the gateway?

Available for Net Core?

Hello, good day!

Just wondering if this project is compatible with .Net Core? I see in te dependencies that it only lists .NetStandard, so I am inclined to believe that is not yet there?

Is this planned in the roadmap?

Thank you for your time!

Observing a device only works for a short time

I am using the ObserveDevice method on the DeviceController instance to observe updates on a device. When I immediately use my remote control to toggle the lights on/off, I get a notification through the observer. But when I wait for some time (2 minutes) the notifications are not being received anymore.

Is there a way to observe devices for a longer time?

[BUG] - TlsFatalAlert on GenerateAppSecret

Describe the bug
Hello, I'm trying to connect to my gateway, but every time I try to invoke GenerateAppSecret I get the following exception:

Exception thrown: 'Org.BouncyCastle.Crypto.Tls.TlsFatalAlert' in BouncyCastle.Crypto.dll
bad_record_mac(20)

Source Link data for BouncyCastle.Crypto.dll (embedded) failed to parse or does not conform to the schema: {"documents":{}}

IKEA Tradfri Gateway (please complete the following information):

  • Firmware Version 1.10.36

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.