Giter Club home page Giter Club logo

zigbeenet's Introduction

ZigBeeNet

Twitter Follow

ZigBeeNet is a implementation of the Zigbee 3.0 Cluster Library for .NET Standard.

It is fully implemented in Netstandard 2.0 and NET Core 3.0 so that it runs on multiple platform

Build Status

Name Status
master Build status
develop Build status

Packages

Package name NuGet Description
ZigBeeNet NuGet Core library
ZigBeeNet.Transport.SerialPort NuGet Platform indipendent SerialPort implementation
ZigBeeNet.Hardware.TI.CC2531 NuGet Texas Instruments CC25XX dongle implementation
ZigBeeNet.Hardware.Digi.XBee NuGet Digi XBee dongle implementation
ZigbeeNet.Hardware.ConBee NuGet Dresden Elektronik ConBee dongle implementation
ZigbeeNet.Hardware.Ember NuGet Silicon Labs ember dongle implementation
ZigbeeNet.DataStore.JSON NuGet JSON DataStore
ZigbeeNet.DataStore.MongoDb NuGet MongoDb DataStore

Smart Home

With Zigbee 3.0 you can also build your own Smart Home solution and control Zigbee devices from different manufactures like Philips with Philips Hue and IKEA with Tradfri at the same time in the same network. So you are very flexible and the components are very cheap.

Usage

For a detailed description about how to use ZigBeeNet see our wiki page:

You can also take a look at the Playground Demo project

If you need further information we will help you whenever you need it. Just open an new issue for it.

A basic example here:

using System;

namespace ZigBeeNet.PlayGround
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ZigBeeSerialPort zigbeePort = new ZigBeeSerialPort("COM4");

                IZigBeeTransportTransmit dongle = new ZigBeeDongleTiCc2531(zigbeePort);

                ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(dongle);

                // Initialise the network
                networkManager.Initialize();

                networkManager.AddSupportedCluster(0x06);

                ZigBeeStatus startupSucceded = networkManager.Startup(false);

                if (startupSucceded == ZigBeeStatus.SUCCESS)
                {
                    Log.Logger.Information("ZigBee console starting up ... [OK]");
                }
                else
                {
                    Log.Logger.Information("ZigBee console starting up ... [FAIL]");
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.ReadLine();
        }
    }
}

Supported Dongles and Chipsets / Zigbee Stacks

Because Zigbee is just a specification you need a stack of a manufacturer that implements it. ZigBeeNet is developed with a strict seperation of the Zigbee Cluster Library (ZCL) and the various manufacturer stacks. Because of that it is possible to use different hardware for your Zigbee solution

If there is a manufacturer solution missing, feel free to open an issue or take part of it's implementation

Texas Instruments ( Z-Stack )

Z-Stack 3.0.x is TI's Zigbee 3.0 compliant protocol suite for the CC2530, CC2531, and CC2538 Wireless MCU. Z-Stack comunicates through TI's Unified Network Processor Interface (NPI) which is used for establishing a serial data link between a TI SoC and external MCUs or PCs. UNPI is also implemented in this project and is also implemented for different plattforms.

The easiest solution is the CC2531 USB Stick with the ZNP (Zigbee Network Processor) Image, so that it works as an Zigbee gateway via serial port

Source: http://www.ti.com/tool/z-stack

Digi XBee

Digi XBee is the brand name of a family of form factor compatible radio modules from Digi International.

Source: https://en.wikipedia.org/wiki/XBee

We have tested it with the XBee ZigBee S2C chip

ConBee

ConBee is a hardware dongle from Dresden Elektronik

Source: https://www.phoscon.de/en/conbee2

We have tested it with the ConBee 2

Silicon Labs Ember EM35x / EFR32

The library supports the Silicon Labs EZSP protocol using ASH protocol over a serial interface. The implementation of the SPI protocol assumes that the SPI provides a TTY-like software interface to the application, or is otherwise abstracted via the ZigBeePort interface.

It is worth noting that EM3588 devices that have an embedded USB core will likely work with any baud rate, where dongles using external USB interface (eg CP2102 used with an EM3581) will likely require a specific baud rate.

Currently there are two main NCP images - one that supports hardware flow control with a baud rate of 115200, and one that supports software flow control with a rate of 57600.

Free beer !!

No. Sorry. But now that I have your attention .. we need your help! Since it is hardly possible to test all devices, let us know with which devices you have already successfully tested ZigBeeNet or where you encountered problems. Just open an Issue.

See also:

Related Issue
Wiki

Many thanks!

Hint

This project is highly inspired by https://github.com/zsmartsystems/com.zsmartsystems.zigbee and many ideas were adopted (almost a java -> c# port).

Contributing

Feel free to open an issue if you have any idea or enhancement. If you want to implement on code create a fork and open a pull request.

Coding guidelines

For a cleaner code we have some coding guidelines. you can find them here.

License and Copyright

ZigBeeNet is licensed under the Eclipse Public License. Refer to the license file for further information.

Some parts of this project are converted to c# from com.zsmartsystems.zigbee.

com.zsmartsystems.zigbee use code from zigbee4java which in turn is derived from ZB4O projects which are licensed under the Apache-2 license.

ZigBee Documentation

Some documentation used to create parts of this framework is copyright © ZigBee Alliance, Inc. All rights Reserved. The following copyright notice is copied from the ZigBee documentation.

Elements of ZigBee Alliance specifications may be subject to third party intellectual property rights, including without limitation, patent, copyright or trademark rights (such a third party may or may not be a member of ZigBee). ZigBee is not responsible and shall not be held responsible in any manner for identifying or failing to identify any or all such third party intellectual property rights.

No right to use any ZigBee name, logo or trademark is conferred herein. Use of any ZigBee name, logo or trademark requires membership in the ZigBee Alliance and compliance with the ZigBee Logo and Trademark Policy and related ZigBee policies.

This document and the information contained herein are provided on an “AS IS” basis and ZigBee DISCLAIMS ALL WARRANTIES EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO (A) ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OF THIRD PARTIES (INCLUDING WITHOUT LIMITATION ANY INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENT, COPYRIGHT OR TRADEMARK RIGHTS) OR (B) ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR NONINFRINGEMENT. IN NO EVENT WILL ZIGBEE BE LIABLE FOR ANY LOSS OF PROFITS, LOSS OF BUSINESS, LOSS OF USE OF DATA, INTERRUPTION OF BUSINESS, OR FOR ANY OTHER DIRECT, INDIRECT, SPECIAL OR EXEMPLARY, INCIDENTIAL, PUNITIVE OR CONSEQUENTIAL DAMAGES OF ANY KIND, IN CONTRACT OR IN TORT, IN CONNECTION WITH THIS DOCUMENT OR THE INFORMATION CONTAINED HEREIN, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE.

All Company, brand and product names may be trademarks that are the sole property of their respective owners.

Dongle Documentation

Some documentation used to implement dongle drivers is copywrite to the respective holders, including Silicon Labs, Texas Instruments, Dresden Electronics, Digi International.

zigbeenet's People

Contributors

andreasfedermann avatar davidkarlas avatar gallimathias avatar genesiscz avatar jannemattila avatar ker-markus avatar maksim789456 avatar mr-markus avatar nicolaiw avatar oblaise avatar reinux avatar spudwebb avatar theblubb14 avatar thombrink 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

zigbeenet's Issues

NodeUpdated never called

When a node is first added NodeAdded is called, but the node passed as parameter has an empty Endpoints dictionary, which I guess is expected?

Then ZigBeeDiscoveryExtension does its job and queries the node for its capabilities. The Endpoints dictionary is populated, but NodeUpdated is never called.

I think ZigBeeNetworkManager.RefreshNode() is supposed to trigger the NodeUpdated callback for all the listeners but it never does because it always returns here:

               // Return if there were no updates
                if (!currentNode.UpdateNode(node))
                {
                    Log.Debug("{IeeeAddress}: Node {NwkAddress} is not updated", node.IeeeAddress, node.NetworkAddress);
                    return;
                }

I don't understand how it is supposed to work: currentNode.UpdateNode(node) always returns false because here currentNode and node are the same reference so UpdateNode correctly says they are equal.

I'm testing with the PlayGround sample

Make ZigbeeNet 100 % netstandard

Currently ZigbeeNet is not 100 % netstandard, because it references unpi-net which uses SerialPort class that is not availible in netstandard.

A solution for ZigbeeNet is needed, that it is not necessary to reference unpi-net directly

Any idea?

Potential license problem

Since the project is a port of zsmartsystems, which is equivalent to a copy in the broadest sense, the copyright and also the license must be respected.

zsmartsystems/com.zsmartsystems.zigbee uses the EPL-1.0.

This is a CopyLeft license so the notes as well as the license of the original project have to be taken over. MIT in this form is not allowed.

I recommend a quick customization so you don't get into legal trouble as the owner ;)

manufacturer / model specific extensions of autogenerated code

Does it make sense, for example, to expand the autogenerated ZclCluster classes in derived classes?
Currently I am testing with an Ikea-Tradfi bulb. Here the imprinted Model Id is stored in the ZclBasic cluster under the vendor-specific attribute 0x000a. Currently I am expanding the cluster in my own code.

Tested devices

We need your help!

Do you already have tested some devices with ZigbeeNet? Please let us know which devices and which clusters or functionality you have tested so that we can create a "supported devices" section in our README

Thanks!

Code style

If there is a preferred code style, please set up a ReSharper rules file for it and I will follow.

Fix reader thread code to fit the CC protocol

This code need to be fixed so the CC protocol is implemented correct. My assumptions when writing it was more than slightly off, but should be a good basis.

  • Reading and parsing

    private async void ReadSerialPort(UnifiedNetworkProcessorInterface port)
    {
    if (port == null) throw new ArgumentNullException(nameof(port));
    while (true)
    try
    {
    var serialPacket = await SerialPacket.ReadAsync(port.InputStream).ConfigureAwait(false);
    // SerialPacket.ReadAsync() return the correct package class, so
    // we can start processing them into the correct queue here
    if (serialPacket is SynchronousResponse)
    {
    responseQueue.Add(serialPacket);
    continue;
    }
    if (serialPacket is AsynchronousRequest) eventQueue.Add(serialPacket);
    // Ok, not sure but if we reach here something is afoot?
    }
    catch (Exception e)
    {
    // TODO improve this by adding a good error handling
    OnError(e);
    }
    }

  • Sending and waiting for response

    public Task<byte[]> Send(SubSystem subSystem, CancellationToken cancellationToken, params byte[] payload)
    {
    return Send(subSystem, payload,
    msg => { return msg is SynchronousResponse && msg.SubSystem == subSystem; },
    cancellationToken);
    }

  • Code does now allow the Cmd1

    private Task<byte[]> Send(SubSystem subSystem, byte[] payload, Func<SynchronousResponse, bool> predicate,
    CancellationToken cancellationToken)
    {
    return RetryAsync(async () =>
    {
    var request = new SynchronousRequest(subSystem, 0, payload);
    transmitQueue.Add(request);
    var response = await WaitForResponse(msg => predicate((SynchronousResponse) msg), cancellationToken)
    .ConfigureAwait(false);
    return ((SynchronousResponse) response).Payload;
    }, $"{subSystem} {(payload != null ? BitConverter.ToString(payload) : string.Empty)}", cancellationToken);
    }

Make ToString method of Request and Response handle List

currently most ZDO and ZCL request/response do not handle well properties that are list. They rely on the Object.ToString() method that just print the type of the list:

[14:21:10 DBG] RX CMD: NetworkAddressResponse [20978/0 -> 0/0, cluster=32768, transId=, status=SUCCESS, ieeeAddrRemoteDev=17880104E15812, nwkAddrRemoteDev=20978, startIndex=0, nwkAddrAssocDevList=System.Collections.Generic.List`1[System.Int32]]

we need to see the content of the list

For ZCL that means the code generator need to be modified to handle lists

Pairing a Zigbee device

Hello,

I saw your code last week and have implemented the level/brightness cluster.
(pull request is coming when the remaining problems are solved)

The 'only' problem is that I can't seem to get it working.
I believe I have to bind my device (Ikea Tradfri lamp), before it accepts the commands I send to it.

With debug logging enabled, I can see incoming DeviceAnnounce messages. But I think its not enough to just process this message and let the device be added to my nodes.

In the cluster class I also found a Bind method, but this also doesn't seem to work.

Maybe it's a problem with the Zigbee link key, but the cc2531 has no support for it? (at least the current code doesn't)

Is there a possibility you could help me with this?

Replace ShareProjects

Currently we are working with ShareProjects, so that we are able to create different targets.

But because this project should be a netstandard library there is no reason to do this. All referencing projects should be at version that support netstandard 2.0 as minimum.

For the serialport class you have to implement the IZigBeePort class in your project (see ZigBeeNetPlayground example)

Seperate hardware implementations from ZigBeeNet base library

Actually the implementation for Texas Instruments CC2531 hardware is within the ZigBeeNet shared project.
If there will be more implementations the target assembly will always contain all hardware implementations even if you only use one of it.

To minimize the assembly file and make development easier it will be better to create seperate project files for each hardware. Also creation of NuGet packages will be simplified and correct target platform can be choosed.

Following structure:

  • ZigBeeNet
  • ZigBeeNet.Hardware.TI.CC2531

The base library ZigBeeNet should always be netstandard, but CC2531 needs System.IO.Ports.SerialPort which is only possible on full framework or .NET Core 3.0 and newer or with explicit reference with it's package from NuGet.

For this case we need seperate assemblies and NuGet packages

Use T4 template for generating zpi and zcl code

Currently there are two Meta classes (ZpiMeta and ZclMeta) that parse JSON files and provide Methods to get instances for ZpiObject and ZclCommand.

ZpiMeta

public static ZpiObject GetCommand(SubSystem subSystem, byte cmdId)
{
      return ZpiObjects[subSystem].SingleOrDefault(cmd => cmd.CommandId == cmdId);
}

ZclMeta

public static ZclGlobalCommand GetGlobalCommand(byte cmdId)
{
      return GlobalCommands.Single(fc => fc.Id.Equals(cmdId));
}

public static ZclClusterCommand GetClusterCommand(string cluster, string cmd)
{
      return ClusterCommands.Single(fc => fc.Cluster.Equals(cluster) && fc.Name.Equals(cmd));
}

This was just a first solution to get an object with correct and typed Parameters as a ArgumentCollection.

As next step a code generation with T4 template could be a possible solution. Code in meta classes for parsing JSON file can be reused.

But i think that we still need the posibillity to dynamically create an instance of an object because we do not know the type if an message is incomming. At this point we have to parse the object and ist arguments into the right type.

Add .editorconfig

Can you please create an .editorconfig so that we can easily adhere to the code style you have defined? In VS19 there is an extra button that creates the config for you.
grafik

Abstract Hardware Interface

A end user should probably only need to do:

var zigbeeInt = ZigbeeNet.CC2531(); // Static function to initialize the interface
zigbeeInt.PacketReceived += MyPacketHandler;
zigbeeint.Send(amazing stuff);

Originally posted by @eiaro in #6 (comment)

Most of log statements in catch blocks do not log the exception

For example:

Log.Error("Synchronous command send failed due to unexpected exception.", ex);

will not log the exception as there is no parameter in the message template. So we should replace it with:

Log.Error("Synchronous command send failed due to unexpected exception. {Exception}", ex);

or I saw that Serilog also have methods that takes an exception as the first parameter:

public static void Error(Exception exception, string messageTemplate);

but I'm not sure how it works.

ConBee II support

Hi All,

Does the current XBee support work for a ConBee II dongle please?

Thanks,
Jim

Logger Interface

For better logging experience it would be great if the caller of ZigbeeNet could choose his own logger library.

So an interface with common Methods like Log(LogLevel level) could be a possible solution.

Ideas are wellcome at all time :-)

Change project workflow

To make the work with each other easier I suggest to get closer to GitFlow for this project.

At least a separation of master (deployed) and develop (current alpha) is useful and advisable. Especially with regard to issue #33 and possible auto builds of the nuget packages.

Support for Ember stack

Any plan or anyone currently working on supporting Ember stack?

I may need this in a near future, so I wanted to ask before I start trying to add it myself.

Attribute reporting

I'm trying to configure attribute reporting on a light bulb, so that the value is automatically reported to my program when on/off status change or every 10 seconds:

var cluster = endpoint.GetInputCluster(ZclOnOffCluster.CLUSTER_ID);
if (cluster != null)
{
	var result = await cluster.Bind(networkManager.LocalIeeeAddress, 1);

	if (result.IsSuccess())
	{
		result = await ((ZclOnOffCluster)cluster).SetOnOffReporting(1, 10);

		if (result.IsSuccess())
		{
		}
	}
}

but I always get the following response:

[11:21:46 DBG] RX APS: ZigBeeApsFrame [sourceAddress=20978/11, destinationAddress=0/1, profile=260, cluster=6, addressMode=0, radius=0, apsCounter=0, payload=24 14 7 140 0 0 0]
[11:21:46 DBG] RX ZCL: ZclHeader [frameType=ENTIRE_PROFILE_COMMAND, manufacturerSpecific=False, direction=SERVER_TO_CLIENT, disableDefaultResponse=True, manufacturerCode=0, sequenceNumber=14, commandId=7]
[11:21:46 DBG] RX CMD: ConfigureReportingResponse [On/Off: 20978/11 -> 0/1, cluster=6, transId=14, Status=SUCCESS, Records=[Attribute Status Record: status=UNREPORTABLE_ATTRIBUTE, direction=False, attributeIdentifier=0,]]

first I don't know if I need to bind? I'm not clear what a bind request does and when I should send it?
I tried with or without bind, I tried with different attributes but I always get status=UNREPORTABLE_ATTRIBUTE

any idea? have you ever tested reporting?

Note: see my PR #77 for some fixes needed for bind and config reporting command

Code generator for cluster classes and commands

There are many clusters and commands in the ZigBee standard which have all the same structure and methods.
So it should be possible to create them by a code generator and a ressource file.

As an existing resource file it could be used this file from zsmartsystems

The generated code should be outputted here: ZigbeeNet/ZigBeeNet/ZCL/Clusters/

At the moment there are already some clusters which were written by hand, but they can be overwritten with generated code.

It would be important that the documentation will be generated as XML comments, too.

Digi Xbee support

Hi there,

do you plan to support the digi Xbee device too? Looking at #29 you will. But is there a timeline when you will begin implementing it?
Really great work so far guys!

Let me know if you need help.

Dongle Support for Nortek Security Control / Ember

I have a Nortek Security Control (https://www.amazon.com/GoControl-CECOMINOD016164-HUSBZB-1-USB-Hub/dp/B01GJ826F8/ref=asc_df_B01GJ826F8/?tag=hyprod-20&linkCode=df0&hvadid=193989831776&hvpos=1o1&hvnetw=g&hvrand=11729360482103299148&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9031961&hvtargid=pla-312424172362&psc=1). What do I need to get this running? Can I just treat this as a serial port? I have some programming experience if we need to build some sort of adapter for this, though I'd probably need a little help to get started as I don't do much hardware programming.

Create NuGet Packages

There should be NuGet packages for the ZigBeeNet libraries on nuget.org

They should be provided with lowest possible version

See #32 which have to be done first

Following packages should be created first:

  • ZigBeeNet as netstandard2.0
  • ZigBeeNet.Hardware.TI.CC2531

Creating NuGet packages should be done with AppVayor as part of CI

Compile error

ZpiObject.cs(120,26): error CS0246: The type or namespace name 'DEBUG' could not be found (are you missing a using directive or an assembly reference?) [/home/pi/src/ZigbeeNet/src/ZigbeeNet.CCZnp/ZigbeeNet.CC.csproj]

ZpiSREQ.cs(80,24): error CS0246: The type or namespace name 'DEBUG' could not be found (are you missing a using directive or an assembly reference?) [/home/pi/src/ZigbeeNet/src/ZigbeeNet.CCZnp/ZigbeeNet.CC.csproj]

Process AREQ SerialPacket as Response

if (serialPacket is AsynchronousRequest) eventQueue.Add(serialPacket);

At this Point it can happen that a packet with type AREQ can be read from InputStream. This is defined by TI in UNPI

Asynchronous Request transfer initiated by Host Asynchronous Indication – transfer initiated by NP. Both types of asynchronous messages use the same message type bit field (0x02). The type of message (request/indication) depends on which processor initiated the transaction.

Two Scenarios:

  1. You send an SREQ and will return a SRSP with Status. But as second Response you receive an AREQ packet, too.
    Example: nodeDescReq which is send as SREQ but awaits a SRSP with Status if it was sent correct and a second AREQ that contains device info
    This is an AREQ packet that is send from client-to-server (Server = end device)

  2. An end device in yout Network (e.g. Thermostat) is sending you new Information because Temperatur changed.
    This is also an AREQ packet. But is is send from server-to-client (Server = end device)

For Scenario 1 i already created a JSON mapping file zdo_ReqRspMap.json that defines which SREQ awaits which AREQ packet, too. In class file ZpiObject the property public ZpiObject IndObject holds the Information if there is an AREQ Response awaited

I think this Information have to be used here

NetworkSerialization

There have to be a solution for NetworkStateSerialization, which means that if network is shutdown or startup all known devices should still be there

Replace LibLog with Serilog

Because LibLog often creates errors if you reference the library in your project we would replace it with serilog

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.