Пример #1
0
        public async Task SensorAlarm()
        {
            // the nodeID of the motion sensor
            byte motionSensorID = 5;

            // create the controller
            var controller = new ZWaveController("COM1");

            // open the controller
            controller.Open();

            // get the included nodes
            var nodes = await controller.GetNodes();

            // get the motionSensor
            var motionSensor = nodes[motionSensorID];

            // get the SensorAlarm commandclass
            var sensorAlarm = motionSensor.GetCommandClass<SensorAlarm>();

            // subscribe to alarm event
            sensorAlarm.Changed += (s, e) => Console.WriteLine("Alarm");

            // wait
            Console.ReadLine();

            // close the controller
            controller.Close();
        }
Пример #2
0
 public void TestMethod1()
 {
     var controller = new ZWaveController("COM3");
     controller.Open();
     var version = controller.GetVersion().Result;
     controller.Close();
 }
Пример #3
0
        static void Main(string[] args)
        {
            var portName = System.IO.Ports.SerialPort.GetPortNames().Where(element => element != "COM1").First();

            var controller = new ZWaveController("COM3");

            // netsh http add urlacl url=http://+:80/ user=Everyone
            // http://localhost:80/api/v1.0/controller/nodes/19/basic/get/

            //controller.Channel.Log = Console.Out;

            controller.Open();
            try
            {
                Run(controller).Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var inner in ex.InnerExceptions)
                {
                    LogMessage($"{inner}");
                }
            }
            catch (Exception ex)
            {
                LogMessage($"{ex}");
            }
            finally
            {
                Console.ReadLine();

                controller.Close();
            }
        }
Пример #4
0
        public async Task TurnWallPlugOn()
        {
            // the nodeID of the wallplug
            byte wallPlugNodeID = 3;

            // create the controller
            var controller = new ZWaveController("COM1");
            
            // open the controller
            controller.Open();

            // get the included nodes
            var nodes = await controller.GetNodes();
            
            // get the wallplug
            var wallPlug = nodes[wallPlugNodeID];
            
            // get the SwitchBinary commandclass
            var switchBinary = wallPlug.GetCommandClass<SwitchBinary>();

            // turn wallplug on
            await switchBinary.Set(true);

            // close the controller
            controller.Close();
        }
Пример #5
0
        static void Main(string[] args)
        {
            var portName = System.IO.Ports.SerialPort.GetPortNames().Where(element => 
                element != "COM1" 
                && element != "COM10" 
                && element != "COM11").First();

            var controller = new ZWaveController(portName);
            //controller.Channel.Log = Console.Out;

            controller.Open();
            try
            {
                Run(controller).Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var inner in ex.InnerExceptions)
                {
                    LogMessage($"{inner}");
                }
            }
            catch (Exception ex)
            {
                LogMessage($"{ex}");
            }
            finally
            {
                Console.ReadLine();
                controller.Close();
            }
        }
Пример #6
0
        static private async Task Run(ZWaveController controller)
        {
            LogMessage($"Version: {await controller.GetVersion()}");
            LogMessage($"HomeID: {await controller.GetHomeID():X}");

            var controllerNodeID = await controller.GetNodeID();
            LogMessage($"ControllerID: {controllerNodeID:D3}");

            var nodes = await controller.GetNodes();
            foreach (var node in nodes)
            {
                var protocolInfo = await node.GetProtocolInfo();
                LogMessage($"Node: {node}, Generic = {protocolInfo.GenericType}, Basic = {protocolInfo.BasicType}, Listening = {protocolInfo.IsListening} ");

                var neighbours = await node.GetNeighbours();
                LogMessage($"Node: {node}, Neighbours = {string.Join(", ", neighbours.Cast<object>().ToArray())}");

                // subcribe to changes
                Subscribe(node);
            }


            //await InitializeWallPlug(nodes[2]);
            //await InitializeWallPlug(nodes[3]);
            //await InitializeShockSensor(nodes[4]);
            //await InitializeGarageDoorSensor(nodes[5]);
            //await InitializeThermostat(nodes[6]);
            //await InitializeMultiSensor(nodes[7]);
            await InitializeDoorSensor(nodes[10]);

            Console.ReadLine();
        }
Пример #7
0
        static private async Task Run(ZWaveController controller)
        {
            LogMessage($"Version: {await controller.GetVersion()}");
            LogMessage($"HomeID: {await controller.GetHomeID():X}");

            var controllerNodeID = await controller.GetNodeID();
            LogMessage($"ControllerID: {controllerNodeID:D3}");

            var nodes = await controller.GetNodes();
            unknownDevices = new List<byte>();
            unknownDevices.AddRange(nodes.Select(el => el.NodeID));

            foreach (var node in nodes.Where(el => el.NodeID != controllerNodeID))
            {
                try
                {
                    await RequestNodeType(node);
                }
                catch
                {
                    LogMessage($"Node: {node} not found, waiting for wake up event");
                    // subcribe to changes
                    Subscribe(node);
                }
            }

            LogMessage($"Waiting for wake up events from {unknownDevices.Count} unknown nodes");
            Console.ReadLine();
        }
Пример #8
0
        public Node(byte nodeID, ZWaveController contoller)
        {
            NodeID     = nodeID;
            Controller = contoller;

            _commandClasses.Add(new Basic(this));
            _commandClasses.Add(new ManufacturerSpecific(this));
            _commandClasses.Add(new Battery(this));
            _commandClasses.Add(new SwitchMultiLevel(this));
            _commandClasses.Add(new Alarm(this));
            _commandClasses.Add(new Association(this));
            _commandClasses.Add(new SensorBinary(this));
            _commandClasses.Add(new SensorAlarm(this));
            _commandClasses.Add(new SensorMultiLevel(this));
            _commandClasses.Add(new WakeUp(this));
            _commandClasses.Add(new Meter(this));
            _commandClasses.Add(new SwitchBinary(this));
            _commandClasses.Add(new ZWave.CommandClasses.Version(this));
            _commandClasses.Add(new Configuration(this));
            _commandClasses.Add(new Color(this));
            _commandClasses.Add(new MultiChannel(this));
            _commandClasses.Add(new ThermostatSetpoint(this));
            _commandClasses.Add(new Clock(this));
            _commandClasses.Add(new CentralScene(this));
            _commandClasses.Add(new SceneActivation(this));
            _commandClasses.Add(new MultiChannelAssociation(this));
        }
Пример #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            // Register the Controller event handlers (see methods example below)
            var controller = new ZWaveController("COM5");

            controller.Open();
            var nodesTask = controller.GetNodes();

            nodesTask.Wait();
            var nodes = nodesTask.Result;

            foreach (var node in nodes)
            {
                Subscribe(node);
            }
            while (true)
            {
                Thread.Sleep(1000);
            }
        }
Пример #10
0
        static void Main(string[] args)
        {
            var portName = System.IO.Ports.SerialPort.GetPortNames().Where(element =>
                element != "COM1"
                && element != "COM10"
                && element != "COM11").First();

            var controller = new ZWaveController(portName);
            if (Directory.Exists(@"D:\Temp"))
            {
                controller.Channel.Log = File.CreateText(@"D:\Temp\ZWave_Driver.log");
            }

            controller.Open();
            try
            {
                Run(controller).Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var inner in ex.InnerExceptions)
                {
                    LogMessage($"{inner}");
                }
            }
            catch (Exception ex)
            {
                LogMessage($"{ex}");
            }
            finally
            {
                Console.ReadLine();
                controller.Close();
            }
        }
Пример #11
0
 /// <summary>
 /// Invoked when the application is launched normally by the end user.  Other entry points
 /// will be used such as when the application is launched to open a specific file.
 /// </summary>
 /// <param name="e">Details about the launch request and process.</param>
 protected override void OnLaunched(LaunchActivatedEventArgs e)
 {
     Task.Run(() =>
     {
         var controller = new ZWaveController(0x0658, 0x0200);
         controller.Open();
         var version = controller.GetVersion().Result;
         controller.Close();
     });
 }
Пример #12
0
        public Endpoint(byte nodeID, byte endpointID, ZWaveController controller)
        {
            if (nodeID == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(nodeID), nodeID, "nodeID must be greater than 0");
            }

            NodeID     = nodeID;
            EndpointID = endpointID;
            Controller = controller ?? throw new ArgumentNullException(nameof(controller));
        }
Пример #13
0
        public Module()
        {
            var portName = System.IO.Ports.SerialPort.GetPortNames().Where(element =>
                element != "COM1"
                && element != "COM10"
                && element != "COM11").First();

            controller = new ZWaveController(portName);
            controller.Open();

            LoadNodes();
        }
Пример #14
0
        internal Node(byte nodeID, ZWaveController controller) : base(nodeID, 0, controller)
        {
            if (nodeID == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(nodeID), nodeID, "nodeID must be greater than 0");
            }
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            Endpoints = new EndpointCollection(this);
        }
Пример #15
0
        public static Node CreateNode(byte nodeID, ZWaveController controller)
        {
            if (nodeID == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(nodeID), nodeID, "nodeID must be greater than 0");
            }
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            var generator = new ProxyGenerator();
            var options   = CreateProxyGeneratorOptions(nodeID, 0, controller);

            return((Node)generator.CreateClassProxy(typeof(Node), options, new object[] { nodeID, controller }));
        }
Пример #16
0
        static private async Task Run(ZWaveController controller)
        {
            LogMessage($"Version: {await controller.GetVersion()}");
            LogMessage($"HomeID: {await controller.GetHomeID():X}");

            var controllerNodeID = await controller.GetNodeID();

            LogMessage($"ControllerID: {controllerNodeID:D3}");


            await controller.DiscoverNodes();

            var nodes = await controller.GetNodes();

            await Task.Delay(2000);

            foreach (var node in nodes)
            {
                var protocolInfo = await node.GetProtocolInfo();

                LogMessage($"Node: {node}, Generic = {protocolInfo.GenericType}, Basic = {protocolInfo.BasicType}, Listening = {protocolInfo.IsListening} ");

                var neighbours = await node.GetNeighbours();

                LogMessage($"Node: {node}, Neighbours = {string.Join(", ", neighbours.Cast<object>().ToArray())}");

                // subcribe to changes
                Subscribe(node);
            }
            //var command =nodes[2].GetCommandClass<SwitchBinary>();
            var command = nodes[5].GetCommandClass <MultiChannel>();
            //await Task.Delay(2000);

            await Task.Delay(1000);

            await command.BinarySwitchSet(1, true);

            await Task.Delay(1000);

            await command.BinarySwitchSet(2, true);

            await Task.Delay(1000);

            await command.BinarySwitchSet(1, false);

            await Task.Delay(1000);

            await command.BinarySwitchSet(2, false);

            await Task.Delay(1000);

            await command.BinarySwitchSet(2, true);

            await Task.Delay(1000);

            await command.BinarySwitchSet(1, false);

            await Task.Delay(1000);

            await command.BinarySwitchSet(2, false);

            //await InitializeWallPlug(nodes[2]);
            //await InitializeWallPlug(nodes[3]);
            //await InitializeShockSensor(nodes[4]);
            //await InitializeGarageDoorSensor(nodes[5]);
            //await InitializeThermostat(nodes[6]);
            //await InitializeMultiSensor(nodes[18]);
            //await InitializeDoorSensor(nodes[10]);
            //await InitializePowerSwitch(nodes[19]);
            //await InitializePowerSwitch(nodes[20]);
            //await InitializePowerSwitch(nodes[24]);
            //await InitializePowerSwitch(nodes[25]);
            //await InitializePowerSwitch(nodes[2]);
            //var neighborUpdateStatus = await nodes[19].RequestNeighborUpdate((status) => LogMessage($"RequestNeighborUpdate: {status} "));

            Console.ReadLine();
        }
Пример #17
0
        private static IEnumerable <CommandClassService> CreateCommandClasseServices(byte nodeID, byte endpointID, ZWaveController controller)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }
            if (nodeID == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(nodeID), nodeID, "nodeID must be greater than 0");
            }

            foreach (var commandClasseServiceType in _commandClasseServiceTypes)
            {
                yield return((CommandClassService)Activator.CreateInstance(commandClasseServiceType, nodeID, endpointID, controller));
            }
        }
Пример #18
0
        private static ProxyGenerationOptions CreateProxyGeneratorOptions(byte nodeID, byte endpointID, ZWaveController controller)
        {
            var options = new ProxyGenerationOptions();

            foreach (var service in CreateCommandClasseServices(nodeID, endpointID, controller))
            {
                options.AddMixinInstance(service);
            }
            return(options);
        }
Пример #19
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length != 2)
                {
                    Console.WriteLine("Duplicate the ZWave network and setup channels to a new controller");
                    Console.WriteLine("Asumes that the ControlStick is installed");
                    Console.WriteLine("Usage:");
                    Console.WriteLine("       DuplicateZwaveNetwork.exe <Configuration File Name> <Controller Name>");
                    Console.WriteLine();
                    Console.WriteLine("       Configuration File Name - The path to the JSON file with the network ");
                    Console.WriteLine("                                 configuration details");
                    Console.WriteLine("       Controller Name - The name of the controller to duplicate (The controller");
                    Console.WriteLine("                          is expected to be defined in the config file");
                    return;
                }

                var ser    = new DataContractJsonSerializer(typeof(ConfigurationFile.ConfigFile));
                var config = default(ConfigurationFile.ConfigFile);
                using (FileStream stream = new FileStream(args[0], FileMode.Open))
                {
                    // Skip the UTF8 headers in the file
                    while (stream.ReadByte() != '{')
                    {
                        ;
                    }
                    stream.Seek(-1, SeekOrigin.Current);
                    config = ser.ReadObject(stream) as ConfigurationFile.ConfigFile;
                }

                ZWaveController cont = new ZWaveController();
                Console.WriteLine("Connecting to Think Stick");
                cont.Connect();
                Console.WriteLine("Connected");
                var controllerConfig = config.GetControllerByName(args[1]);
                Console.WriteLine("Copying network settings and channels to controller " + controllerConfig.Name);
                var replicationScenes = new List <ZWaveController.ReplicationScene>();
                foreach (var s in controllerConfig.Scenes)
                {
                    var repScene = new ZWaveController.ReplicationScene(s.Channell);
                    var Scene    = config.GetSceneById(s.SceneId);
                    Console.WriteLine("Channel " + s.Channell + " --> " + Scene.Name);
                    foreach (var d in Scene.Devices)
                    {
                        var device = config.GetDeviceById(d.DeviceId);
                        Console.WriteLine("                       " + device.Name + " " + (d.Level == 0 ? "off" : "on"));
                        var deviceFromController = cont.Devices[device.NodeId - 1];
                        repScene.SceneItems.Add(deviceFromController, d.Level);
                    }
                    replicationScenes.Add(repScene);
                }
                Console.WriteLine("Make sure to put the controller in \"Receive Network Configuration\" state ");
                Console.WriteLine("to do so on HA07");
                Console.WriteLine(" * Press and hold the INCLUDE Button for 5 seconds. COPY will flash.");
                Console.WriteLine(" * Release the INCLUDE button.");
                Console.WriteLine(" * Press and release the channel 1 OFF/DIM.");
                Console.WriteLine("   The display will show \"RA\" which means \"Receive All Information\"");
                Console.WriteLine();
                Console.WriteLine("On the HA09 the steps are the same but the lights will flash instead");
                Console.WriteLine("of the display.");
                var addedController = cont.AddController(new ZWaveController.ReplicationGroup[] { }, replicationScenes.ToArray());
                if (addedController == null)
                {
                    throw new Exception("Failed to add controller");
                }
                Console.WriteLine("Done!!!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #20
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length != 2)
                {
                    Console.WriteLine("Duplicate the ZWave network and setup channels to a new controller");
                    Console.WriteLine("Asumes that the ControlStick is installed");
                    Console.WriteLine("Usage:");
                    Console.WriteLine("       DuplicateZwaveNetwork.exe <Configuration File Name> <Controller Name>");
                    Console.WriteLine();
                    Console.WriteLine("       Configuration File Name - The path to the JSON file with the network ");
                    Console.WriteLine("                                 configuration details");
                    Console.WriteLine("       Controller Name - The name of the controller to duplicate (The controller");
                    Console.WriteLine("                          is expected to be defined in the config file");
                    return;
                }

                var ser = new DataContractJsonSerializer(typeof(ConfigurationFile.ConfigFile));
                var config = default(ConfigurationFile.ConfigFile);
                using (FileStream stream = new FileStream(args[0], FileMode.Open))
                {
                    // Skip the UTF8 headers in the file
                    while (stream.ReadByte() != '{') ;
                    stream.Seek(-1, SeekOrigin.Current);
                    config = ser.ReadObject(stream) as ConfigurationFile.ConfigFile;
                }

                ZWaveController cont = new ZWaveController();
                Console.WriteLine("Connecting to Think Stick");
                cont.Connect();
                Console.WriteLine("Connected");
                var controllerConfig = config.GetControllerByName(args[1]);
                Console.WriteLine("Copying network settings and channels to controller " + controllerConfig.Name);
                var replicationScenes = new List<ZWaveController.ReplicationScene>();
                foreach (var s in controllerConfig.Scenes)
                {
                    var repScene = new ZWaveController.ReplicationScene(s.Channell);
                    var Scene = config.GetSceneById(s.SceneId);
                    Console.WriteLine("Channel " + s.Channell + " --> " + Scene.Name);
                    foreach (var d in Scene.Devices)
                    {
                        var device = config.GetDeviceById(d.DeviceId);
                        Console.WriteLine("                       " + device.Name + " " + (d.Level == 0 ? "off" : "on"));
                        var deviceFromController = cont.Devices[device.NodeId - 1];
                        repScene.SceneItems.Add(deviceFromController, d.Level);
                    }
                    replicationScenes.Add(repScene);
                }
                Console.WriteLine("Make sure to put the controller in \"Receive Network Configuration\" state ");
                Console.WriteLine("to do so on HA07");
                Console.WriteLine(" * Press and hold the INCLUDE Button for 5 seconds. COPY will flash.");
                Console.WriteLine(" * Release the INCLUDE button.");
                Console.WriteLine(" * Press and release the channel 1 OFF/DIM.");
                Console.WriteLine("   The display will show \"RA\" which means \"Receive All Information\"");
                Console.WriteLine();
                Console.WriteLine("On the HA09 the steps are the same but the lights will flash instead");
                Console.WriteLine("of the display.");
                var addedController = cont.AddController(new ZWaveController.ReplicationGroup[] { }, replicationScenes.ToArray());
                if (addedController == null)
                {
                    throw new Exception("Failed to add controller");
                }
                Console.WriteLine("Done!!!");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ContinueWith(_ => { });

            if (string.IsNullOrEmpty(_comPortName))
            {
                _messageQueue.Publish(new NotifyUserMessage("Add z-wave configuration (port) to config file."));
                return;
            }

            var validComPorts = new HashSet<string>(SerialPort.GetPortNames(), StringComparer.Ordinal);
            if (!validComPorts.Contains(_comPortName))
            {
                _messageQueue.Publish(new NotifyUserMessage("COM Port for z-wave configuration is invalid."));
                return;
            }

            try
            {
                await Policy
                    .Handle<WebException>()
                    .Or<Exception>()
                    .WaitAndRetryForeverAsync(_ => TimeSpan.FromSeconds(1))
                    .ExecuteAsync(async () =>
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            return;
                        }
                        await _library.Load(cancellationToken);
                    });

                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                _controller = new ZWaveController(_comPortName);
                _controller.Open();
                _controller.Channel.NodeEventReceived += (s, e) => ContinueNodeQueueWorker(e.NodeID);

                while (!cancellationToken.IsCancellationRequested)
                {
                    _log.Debug("Discover Nodes");
                    await DiscoverNodes(cancellationToken);
                    await Task.Delay(TimeSpan.FromHours(1), cancellationToken).ContinueWith(_ => { });
                }
            }
            catch (Exception e)
            {
                _log.Error(e.Message, e);
            }
        }