Пример #1
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     request.Response = ""; //default success value
     //
     if (request.Command == Command.CAMERA_GETPICTURE)
     {
         // get picture from camera <nodeid>
         // TODO: there is actually only single camera support
         if (cameraSource != IntPtr.Zero)
         {
             lock (this)
             {
                 var pictureBuffer = CameraCaptureV4LInterop.GetFrame(cameraSource);
                 var data          = new byte[pictureBuffer.Size];
                 Marshal.Copy(pictureBuffer.Data, data, 0, pictureBuffer.Size);
                 return(data);
             }
         }
     }
     else if (request.Command == Command.CAMERA_GETLUMINANCE)
     {
         // TODO: ....
     }
     else if (request.Command == Command.CAMERA_GETDEVICE)
     {
         //request.Response = JsonSerializeObject( cameraDevice );
     }
     else if (request.Command == Command.CAMERA_SETDEVICE)
     {
         SetVideoInput(request.GetOption(0).Replace("|", "/"), uint.Parse(request.GetOption(1)), uint.Parse(request.GetOption(2)), uint.Parse(request.GetOption(3)));
         //request.Response = "OK"; // Utility.GetSimpleJson( ... )
     }
     //
     return(request.Response);
 }
Пример #2
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            request.response = ""; //default success value
            //
            if (request.command == Command.CAMERA_GETPICTURE)
            {
                // get picture from camera <nodeid>
                // there is actually only single camera support though

                // TODO: check if file exists before opening it ("/dev/video0")
                if (_camerasource != IntPtr.Zero)
                {
                    PictureBuffer pb   = CameraCaptureV4LInterop.GetFrame(_camerasource);
                    var           data = new byte[pb.Size];
                    Marshal.Copy(pb.Data, data, 0, pb.Size);
                    //System.IO.File.WriteAllBytes("html/test.jpg", data);
                    return(data);
                }
            }
            else if (request.command == Command.CAMERA_GETLUMINANCE)
            {
                // TODO: ....
            }
            //
            return(request.response);
        }
Пример #3
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     request.Response = ""; //default success value
     //
     if (request.Command == Command.CAMERA_GETPICTURE)
     {
         // get picture from camera <nodeid>
         // TODO: there is actually only single camera support
         if (cameraSource != IntPtr.Zero)
         {
             lock (readPictureLock)
             {
                 var pictureBuffer = CameraCaptureV4LInterop.GetFrame(cameraSource);
                 var data          = new byte[pictureBuffer.Size];
                 Marshal.Copy(pictureBuffer.Data, data, 0, pictureBuffer.Size);
                 return(data);
             }
         }
     }
     else if (request.Command == Command.CAMERA_GETLUMINANCE)
     {
         // TODO: ....
     }
     else if (request.Command == Command.CAMERA_SETDEVICE)
     {
         this.GetOption("Configuration").Value = request.GetOption(0) + "," + request.GetOption(1) + "," + request.GetOption(2) + "," + request.GetOption(3);
         Connect();
     }
     //
     return(request.Response);
 }
Пример #4
0
        public void AddCommand(MIGInterfaceCommand cmd)
        {
            double delay = 0;

            switch (delayType)
            {
            case MacroDelayType.Mimic:
                // calculate pause between current and previous command
                delay = new TimeSpan(DateTime.Now.Ticks - currentTimestamp.Ticks).TotalSeconds;
                break;

            case MacroDelayType.Fixed:
                // put a fixed pause
                delay = delaySeconds;
                break;
            }
            //
            try
            {
                if (delay > 0 && macroCommands.Count > 0)
                {
                    // add a pause command to the macro
                    macroCommands.Add(new MIGInterfaceCommand("HomeAutomation.HomeGenie/Automation/Program.Pause/" + delay.ToString(System.Globalization.CultureInfo.InvariantCulture)));
                }
                macroCommands.Add(cmd);
            }
            catch
            {
                //HomeGenieService.LogEvent(Domains.HomeAutomation_HomeGenie, "migservice_ServiceRequestPostProcess(...)", ex.Message, "Exception.StackTrace", ex.StackTrace);
            }
            //
            currentTimestamp = DateTime.Now;
        }
Пример #5
0
 public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migcmd)
 {
     switch (migcmd.command)
     {
     case "Events.Push":
         //TODO: implemet security and trust mechanism
         string      objstream = new StreamReader(request.InputStream).ReadToEnd();
         ModuleEvent mev       = JsonConvert.DeserializeObject <ModuleEvent>(objstream);
         //
         Module mod = _hg.Modules.Find(delegate(Module o)
         {
             return(o.Domain == mev.Module.Domain && o.Address == mev.Module.Address);
         });
         if (mod == null)
         {
             mod = mev.Module;
             _hg.Modules.Add(mod);
         }
         else
         {
             Utility.ModuleParameterSet(mod, mev.Parameter.Name, mev.Parameter.Value);
         }
         // "<ip>:<port>" remote endpoint port is passed as the first argument from the remote point itself
         mod.RoutingNode = request.RequestOrigin + (migcmd.GetOption(0) != "" ? ":" + migcmd.GetOption(0) : "");
         //
         _hg.LogBroadcastEvent(mev.Module.Domain, mev.Module.Address, request.RequestOrigin, mev.Parameter.Name, mev.Parameter.Value);
         _hg.RouteParameterChangedEvent(request.RequestOrigin, mod, mev.Parameter);
         break;
     }
 }
Пример #6
0
        private void ExecuteProgramCommand(ProgramCommand programCommand)
        {
            string command          = programCommand.Domain + "/" + programCommand.Target + "/" + programCommand.CommandString + "/" + System.Uri.EscapeDataString(programCommand.CommandArguments);
            var    interfaceCommand = new MIGInterfaceCommand(command);

            homegenie.InterfaceControl(interfaceCommand);
        }
Пример #7
0
        private void _mcp_executeCommand(ProgramCommand c)
        {
            string wrequest         = c.Domain + "/" + c.Target + "/" + c.CommandString + "/" + c.CommandArguments;
            MIGInterfaceCommand cmd = new MIGInterfaceCommand(wrequest);

            _homegenie.InterfaceControl(cmd);
            _homegenie.WaitOnPending(c.Domain);
        }
Пример #8
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            Command command     = (Command)request.command;
            string  returnvalue = "";

            //
            if (command == Command.CONTROL_ON)
            {
                this.OutputPin((enumPIN)int.Parse(request.nodeid), true);
                GPIOPins[request.nodeid] = true;
                if (InterfacePropertyChangedAction != null)
                {
                    try
                    {
                        InterfacePropertyChangedAction(new InterfacePropertyChangedAction()
                        {
                            Domain = this.Domain, SourceId = request.nodeid, SourceType = "Raspberry Pi GPIO", Path = ModuleParameters.MODPAR_STATUS_LEVEL, Value = 1
                        });
                    }
                    catch { }
                }
            }
            //
            if (command == Command.CONTROL_OFF)
            {
                this.OutputPin((enumPIN)int.Parse(request.nodeid), false);
                GPIOPins[request.nodeid] = false;
                if (InterfacePropertyChangedAction != null)
                {
                    try
                    {
                        InterfacePropertyChangedAction(new InterfacePropertyChangedAction()
                        {
                            Domain = this.Domain, SourceId = request.nodeid, SourceType = "Raspberry Pi GPIO", Path = ModuleParameters.MODPAR_STATUS_LEVEL, Value = 0
                        });
                    }
                    catch { }
                }
            }
            //
            if (command == Command.PARAMETER_STATUS)
            {
                GPIOPins[request.nodeid] = this.InputPin((enumPIN)int.Parse(request.nodeid));
            }
            //
            if (command == Command.CONTROL_RESET)
            {
                this.CleanUpAllPins();
                foreach (KeyValuePair <string, bool> kv in GPIOPins)
                {
                    GPIOPins[kv.Key] = false;
                }
            }
            //
            return(returnvalue);
        }
Пример #9
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     request.Response = ""; //default success value
     //
     if (request.Command == Command.REMOTES_SEARCH)
     {
         request.Response = JsonConvert.SerializeObject(
             SearchRemotes(request.GetOption(0)),
             Formatting.Indented
             );
     }
     else if (request.Command == Command.REMOTES_ADD)
     {
         var remote = remotesData.Find(r => r.Manufacturer.ToLower() == request.GetOption(0).ToLower() && r.Model.ToLower() == request.GetOption(1).ToLower());
         if (remote != null && remotesConfig.Find(r => r.Model.ToLower() == remote.Model.ToLower() && r.Manufacturer.ToLower() == remote.Manufacturer.ToLower()) == null)
         {
             var    webClient = new WebClient();
             string config    = webClient.DownloadString("http://lirc.sourceforge.net/remotes/" + remote.Manufacturer + "/" + remote.Model);
             remote.Configuration = GetBytes(config);
             remotesConfig.Add(remote);
             SaveConfig();
         }
     }
     else if (request.Command == Command.REMOTES_REMOVE)
     {
         var remote = remotesConfig.Find(r => r.Manufacturer.ToLower() == request.GetOption(0).ToLower() && r.Model.ToLower() == request.GetOption(1).ToLower());
         if (remote != null)
         {
             remotesConfig.Remove(remote);
             SaveConfig();
         }
     }
     else if (request.Command == Command.REMOTES_LIST)
     {
         request.Response = JsonConvert.SerializeObject(remotesConfig, Formatting.Indented);
     }
     else if (request.Command == Command.CONTROL_IRSEND)
     {
         string commands = "";
         int    c        = 0;
         while (request.GetOption(c) != "")
         {
             var options = request.GetOption(c).Split('/');
             foreach (string o in options)
             {
                 commands += "\"" + o + "\" ";
             }
             c++;
         }
         ShellCommand("irsend", "SEND_ONCE " + commands);
     }
     //
     return(request.Response);
 }
Пример #10
0
 private void _interfacecontrol(Module module, MIGInterfaceCommand cmd)
 {
     cmd.domain = module.Domain;
     cmd.nodeid = module.Address;
     //string options = "";
     //for (int o = 0; o < cmd.options.Length; o++ )
     //{
     //    options += cmd.options[o] + "/";
     //}
     _homegenie.InterfaceControl(cmd); //new Command("/" + module.Domain + "/" + module.Address + "/" + cmd.command + "/" + options));
     _homegenie.WaitOnPending(module.Domain);
 }
Пример #11
0
        public object InterfaceControl(MIGInterfaceCommand command)
        {
            string returnValue          = "";
            bool   raisePropertyChanged = false;
            string parameterPath        = "Status.Level";
            string raiseParameter       = "";

            switch (command.Command)
            {
            case "Control.On":
                controller.TurnOn(int.Parse(command.NodeId));
                raisePropertyChanged = true;
                raiseParameter       = "1";
                break;

            case "Control.Off":
                raisePropertyChanged = true;
                controller.TurnOff(int.Parse(command.NodeId));
                raiseParameter = "0";
                break;

            case "Control.Level":
                raisePropertyChanged = true;
                raiseParameter       = (double.Parse(command.GetOption(0)) / 100).ToString();
                controller.Dim(int.Parse(command.NodeId), (int)Math.Round(double.Parse(command.GetOption(0))));
                break;

            default:
                Console.WriteLine("TS:" + command.Command + " | " + command.NodeId);
                break;
            }

            if (raisePropertyChanged)
            {
                try
                {
                    //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction()
                    {
                        Domain     = this.Domain,
                        SourceId   = command.NodeId,
                        SourceType = "Tellstick Node",
                        Path       = parameterPath,
                        Value      = raiseParameter
                    });
                }
                catch
                {
                }
            }
            return(returnValue);
        }
Пример #12
0
 public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migCommand)
 {
     switch (migCommand.Command)
     {
     case "Events.Push":
         //TODO: implemet security and trust mechanism
         var stream      = new StreamReader(request.InputStream).ReadToEnd();
         var moduleEvent = JsonConvert.DeserializeObject <ModuleEvent>(
             stream,
             new JsonSerializerSettings()
         {
             Culture = System.Globalization.CultureInfo.InvariantCulture
         }
             );
         //
         // prefix remote event domain with HGIC:<remote_node_address>.<domain>
         moduleEvent.Module.Domain = "HGIC:" + request.RequestOrigin.Replace(".", "_") + "." + moduleEvent.Module.Domain;
         //
         var module = homegenie.Modules.Find(delegate(Module o)
         {
             return(o.Domain == moduleEvent.Module.Domain && o.Address == moduleEvent.Module.Address);
         });
         if (module == null)
         {
             module = moduleEvent.Module;
             homegenie.Modules.Add(module);
         }
         else
         {
             Utility.ModuleParameterSet(module, moduleEvent.Parameter.Name, moduleEvent.Parameter.Value);
         }
         // "<ip>:<port>" remote endpoint port is passed as the first argument from the remote point itself
         module.RoutingNode = request.RequestOrigin + (migCommand.GetOption(0) != "" ? ":" + migCommand.GetOption(0) : "");
         //
         homegenie.LogBroadcastEvent(
             moduleEvent.Module.Domain,
             moduleEvent.Module.Address,
             request.RequestOrigin,
             moduleEvent.Parameter.Name,
             moduleEvent.Parameter.Value
             );
         HomeGenie.Service.HomeGenieService.RoutedEvent eventData = new HomeGenie.Service.HomeGenieService.RoutedEvent()
         {
             Sender    = request.RequestOrigin,
             Module    = module,
             Parameter = moduleEvent.Parameter
         };
         ThreadPool.QueueUserWorkItem(new WaitCallback(homegenie.RouteParameterChangedEvent), eventData);
         break;
     }
 }
Пример #13
0
		public object InterfaceControl(MIGInterfaceCommand command)
		{
			string returnValue = "";
            bool raisePropertyChanged = false;
            string parameterPath = "Status.Level";
            string raiseParameter = "";
            switch (command.Command)
            {
            case "Control.On":
                controller.TurnOn(int.Parse(command.NodeId));
                raisePropertyChanged = true;
                raiseParameter = "1";
                break;
            case "Control.Off":
                raisePropertyChanged = true;
                controller.TurnOff(int.Parse(command.NodeId));
                raiseParameter = "0";
                break;
			case "Control.Level":
				raisePropertyChanged = true;
				raiseParameter = (double.Parse(command.GetOption(0)) / 100).ToString();
				controller.Dim(int.Parse(command.NodeId), (int)Math.Round(double.Parse(command.GetOption(0))));
			    break;
            default:
                Console.WriteLine("TS:" + command.Command + " | " + command.NodeId);
                break;
            }

            if (raisePropertyChanged)
            {
                try
                {
                    //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                        Domain = this.Domain,
                        SourceId = command.NodeId,
                        SourceType = "Tellstick Node",
                        Path = parameterPath,
                        Value = raiseParameter
                    });
                }
                catch
                {
                }
            }
			return returnValue;
		}
Пример #14
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     request.response = ""; //default success value
     //
     if (request.command == Command.REMOTES_SEARCH)
     {
         request.response = JsonConvert.SerializeObject(SearchRemotes(request.GetOption(0)), Formatting.Indented);
     }
     else if (request.command == Command.REMOTES_ADD)
     {
         LircRemoteData lrd = _remotesdata.Find(r => r.Manufacturer.ToLower() == request.GetOption(0).ToLower() && r.Model.ToLower() == request.GetOption(1).ToLower());
         if (lrd != null && _remotesconfig.Find(r => r.Model.ToLower() == lrd.Model.ToLower() && r.Manufacturer.ToLower() == lrd.Manufacturer.ToLower()) == null)
         {
             WebClient wb     = new WebClient();
             string    config = wb.DownloadString("http://lirc.sourceforge.net/remotes/" + lrd.Manufacturer + "/" + lrd.Model);
             lrd.Configuration = GetBytes(config);
             _remotesconfig.Add(lrd);
             _configsave();
         }
     }
     else if (request.command == Command.REMOTES_REMOVE)
     {
         LircRemoteData lrd1 = _remotesconfig.Find(r => r.Manufacturer.ToLower() == request.GetOption(0).ToLower() && r.Model.ToLower() == request.GetOption(1).ToLower());
         if (lrd1 != null)
         {
             _remotesconfig.Remove(lrd1);
             _configsave();
         }
     }
     else if (request.command == Command.REMOTES_LIST)
     {
         request.response = JsonConvert.SerializeObject(_remotesconfig, Formatting.Indented);
     }
     else if (request.command == Command.CONTROL_IRSEND)
     {
         string commands = "";
         int    c        = 0;
         while (request.GetOption(c) != "")
         {
             commands += "\"" + request.GetOption(c) + "\" ";
             c++;
         }
         ShellCommand("irsend", "SEND_ONCE " + commands);
     }
     //
     return(request.response);
 }
Пример #15
0
        /// <summary>
        ///
        /// A MIG interface class automatically receives a call to this function
        /// for each request made to the webservice and that is addressed to its
        /// driver namespace (domain). A driver request has the form:
        /// http://<server_addr>/<notimplauthkey>/<interface_domain>/<nodeid>/<command>[<other_slash_separated_parameters>]
        /// eg. http://192.168.1.8/api/HomeAutomation.ExampleDriver/G73/Control.On
        /// (tells ExampleDriver to turn on the module with address G73)
        ///
        /// the parameter "request" of this function will contain only the relevant
        /// part of the whole http request:
        /// <nodeid>/<command>[<other_slash_separated_parameters>]
        /// eg.: "G73/Control.Level/50"
        ///
        /// </summary>
        /// <returns>
        /// optional string reply to request (usually xml encoded reply)
        /// </returns>
        /// <param name='request'>
        /// a formatted string containging a valid request for this domain
        /// eg: "A8/Control.Level/75"
        /// </param>
        ///
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            request.Response = ""; //default success value
            // this is an example set of commands:
            // for each received command
            // add the needed code to perform
            // the desired action on the <nodeid> device
            switch (request.Command)
            {
            case "Control.On":

                break;

            case "Control.Off":

                break;

            case "Control.Level":

                break;

            case "Control.Bright":

                break;

            case "Control.Dim":

                break;

            case "Controll.AllLightsOn":

                break;

            case "Control.AllUnitsOff":

                break;
            }
            //
            return(request.Response);
        }
Пример #16
0
        public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migcmd)
        {
            List <LogEntry> logs = new List <LogEntry>();

            try
            {
                switch (migcmd.command)
                {
                case "Recent.From":
                    logs = _hg.RecentEventsLog.ToList().FindAll(le => le != null && le.Domain.StartsWith("MIG.") == false && (le.UnixTimestamp >= double.Parse(migcmd.GetOption(0))));
                    break;

                case "Recent.Last":
                    logs = _hg.RecentEventsLog.ToList().FindAll(le => le != null && le.Domain.StartsWith("MIG.") == false &&
                                                                le.Timestamp > DateTime.UtcNow.AddMilliseconds(-int.Parse(migcmd.GetOption(0))));
                    //                            (DateTime.UtcNow - le.Timestamp.AddMilliseconds(int.Parse(cmd.option))).TotalMilliseconds >= 0);
                    break;
                }
            }
            catch { }
            migcmd.response = JsonConvert.SerializeObject(logs); //, Formatting.Indented);
        }
Пример #17
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string response = "[{ ResponseValue : 'OK' }]";

            var address = request.NodeId.Split('.');

            if (address.Length == 2)
            {
                byte nodeId   = byte.Parse(address[0]);
                byte sensorId = byte.Parse(address[1]);
                var  command  = request.Command;

                if (command.ToLower() == "control.on")
                {
                    _gateway.SendSetMessage(nodeId, sensorId, "1");
                }
                else if (command.ToLower() == "control.off")
                {
                    _gateway.SendSetMessage(nodeId, sensorId, "0");
                }
            }

            return(response);
        }
Пример #18
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     request.Response = ""; //default success value
     //
     if (request.Command == Command.CAMERA_GETPICTURE)
     {
         // get picture from camera <nodeid>
         // TODO: there is actually only single camera support 
         if (cameraSource != IntPtr.Zero)
         {
             lock (this)
             {
                 var pictureBuffer = CameraCaptureV4LInterop.GetFrame(cameraSource);
                 var data = new byte[pictureBuffer.Size];
                 Marshal.Copy(pictureBuffer.Data, data, 0, pictureBuffer.Size);
                 return data;
             }
         }
     }
     else if (request.Command == Command.CAMERA_GETLUMINANCE)
     {
         // TODO: ....
     }
     else if (request.Command == Command.CAMERA_GETDEVICE)
     {
         //request.Response = JsonSerializeObject( cameraDevice );
     }
     else if (request.Command == Command.CAMERA_SETDEVICE)
     {
         SetVideoInput(request.GetOption(0).Replace("|", "/"), uint.Parse(request.GetOption(1)), uint.Parse(request.GetOption(2)), uint.Parse(request.GetOption(3)));
         //request.Response = "OK"; // Utility.GetSimpleJson( ... )
     }
     //
     return request.Response;
 }
Пример #19
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     string returnValue = "";
     bool raisePropertyChanged = false;
     string parameterPath = "Status.Level";
     string raiseParameter = "";
     //
     string nodeId = request.NodeId;
     Command command = (Command)request.Command;
     ////----------------------
     try
     {
         if (command == Command.CONTROLLER_DISCOVERY)
         {
             controller.Discovery();
         }
         else if (command == Command.CONTROLLER_SOFTRESET)
         {
             controller.SoftReset();
         }
         else if (command == Command.CONTROLLER_HARDRESET)
         {
             controller.HardReset();
             Thread.Sleep(500);
             controller.Discovery();
         }
         else if (command == Command.CONTROLLER_NODEADD)
         {
             lastAddedNode = 0;
             byte addedId = controller.BeginNodeAdd();
             for (int i = 0; i < 20; i++)
             {
                 if (lastAddedNode > 0)
                 {
                     break;
                 }
                 Thread.Sleep(500);
             }
             controller.StopNodeAdd();
             //
             returnValue = lastAddedNode.ToString();
         }
         else if (command == Command.CONTROLLER_NODEREMOVE)
         {
             lastRemovedNode = 0;
             byte remcid = controller.BeginNodeRemove();
             for (int i = 0; i < 20; i++)
             {
                 if (lastRemovedNode > 0)
                 {
                     break;
                 }
                 Thread.Sleep(500);
             }
             controller.StopNodeRemove();
             //
             returnValue = lastRemovedNode.ToString();
         }
         ////----------------------
         else if (command == Command.BASIC_SET)
         {
             raisePropertyChanged = true;
             double raiseValue = double.Parse(request.GetOption(0)) / 100;
             if (raiseValue > 1) raiseValue = 1;
             raiseParameter = raiseValue.ToString(CultureInfo.InvariantCulture);
             //
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Basic.Set(node, (byte)int.Parse(request.GetOption(0)));
         }
         else if (command == Command.BASIC_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Basic.Get(node);
         }
         ////-----------------------
         else if (command == Command.MULTIINSTANCE_GETCOUNT)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             //
             switch (request.GetOption(0))
             {
             case "Switch.Binary":
                 MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SwitchBinary);
                 break;
             case "Switch.MultiLevel":
                 MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SwitchMultilevel);
                 break;
             case "Sensor.Binary":
                 MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SensorBinary);
                 break;
             case "Sensor.MultiLevel":
                 MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SensorMultilevel);
                 break;
             }
         }
         else if (command == Command.MULTIINSTANCE_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
             //
             switch (request.GetOption(0))
             {
             case "Switch.Binary":
                 MultiInstance.SwitchBinaryGet(node, instance);
                 break;
             case "Switch.MultiLevel":
                 MultiInstance.SwitchMultiLevelGet(node, instance);
                 break;
             case "Sensor.Binary":
                 MultiInstance.SensorBinaryGet(node, instance);
                 break;
             case "Sensor.MultiLevel":
                 MultiInstance.SensorMultiLevelGet(node, instance);
                 break;
             }
         }
         else if (command == Command.MULTIINSTANCE_SET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
             int value = int.Parse(request.GetOption(2));
             //
             //raisepropchanged = true;
             //parampath += "." + instance; // Status.Level.<instance>
             //
             switch (request.GetOption(0))
             {
             case "Switch.Binary":
                 MultiInstance.SwitchBinarySet(node, instance, value);
                     //raiseparam = (double.Parse(request.GetOption(2)) / 255).ToString();
                 break;
             case "Switch.MultiLevel":
                 MultiInstance.SwitchMultiLevelSet(node, instance, value);
                     //raiseparam = (double.Parse(request.GetOption(2)) / 100).ToString(); // TODO: should it be 99 ?
                 break;
             }
         }
         else if (command == Command.SENSORBINARY_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             SensorBinary.Get(node);
         }
         else if (command == Command.SENSORMULTILEVEL_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             SensorMultilevel.Get(node);
         }
         else if (command == Command.METER_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             // see ZWaveLib Sensor.cs for EnergyMeterScale options
             int scaleType = 0; int.TryParse(request.GetOption(0), out scaleType);
             Meter.Get(node, (byte)(scaleType << 0x03));
         }
         else if (command == Command.METER_SUPPORTEDGET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Meter.GetSupported(node);
         }
         else if (command == Command.METER_RESET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Meter.Reset(node);
         }
         else if (command == Command.NODEINFO_GET)
         {
             controller.GetNodeInformationFrame((byte)int.Parse(nodeId));
         }
         ////-----------------------
         else if (command == Command.BATTERY_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Battery.Get(node);
         }
         ////-----------------------
         else if (command == Command.ASSOCIATION_SET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Association.Set(node, (byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
         }
         else if (command == Command.ASSOCIATION_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Association.Get(node, (byte)int.Parse(request.GetOption(0))); // groupid
         }
         else if (command == Command.ASSOCIATION_REMOVE)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Association.Remove(node, (byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1))); // groupid
         }
         ////-----------------------
         else if (command == Command.MANUFACTURERSPECIFIC_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             ManufacturerSpecific.Get(node);
         }
         ////------------------
         else if (command == Command.CONFIG_PARAMETERSET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             //byte[] value = new byte[] { (byte)int.Parse(option1) };//BitConverter.GetBytes(Int16.Parse(option1));
             //Array.Reverse(value);
             Configuration.Set(node, (byte)int.Parse(request.GetOption(0)), int.Parse(request.GetOption(1)));
         }
         else if (command == Command.CONFIG_PARAMETERGET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Configuration.Get(node, (byte)int.Parse(request.GetOption(0)));
         }
         ////------------------
         else if (command == Command.WAKEUP_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             WakeUp.Get(node);
         }
         else if (command == Command.WAKEUP_SET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             WakeUp.Set(node, uint.Parse(request.GetOption(0)));
         }
         ////------------------
         else if (command == Command.CONTROL_ON)
         {
             raisePropertyChanged = true;
             raiseParameter = "1";
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             int level = 0xFF;
             if (node.GenericClass == (byte)GenericType.SwitchMultilevel)
             {
                 level = 99;
             }
             Basic.Set(node, level);
             SetNodeLevel(node, level);
         }
         else if (command == Command.CONTROL_OFF)
         {
             raisePropertyChanged = true;
             raiseParameter = "0";
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Basic.Set(node, 0x00);
             SetNodeLevel(node, 0x00);
         }
         else if (command == Command.CONTROL_LEVEL)
         {
             raisePropertyChanged = true;
             raiseParameter = Math.Round(double.Parse(request.GetOption(0)) / 100D, 2).ToString(CultureInfo.InvariantCulture);
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             var level = (int)(Math.Round(double.Parse(request.GetOption(0)) / 100D * 99D, 2));
             Basic.Set(node, level);
             SetNodeLevel(node, level);
         }
         else if (command == Command.CONTROL_TOGGLE)
         {
             raisePropertyChanged = true;
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             if (GetNodeLevel(node) == 0)
             {
                 raiseParameter = "1";
                 Basic.Set(node, 0xFF);
                 SetNodeLevel(node, 0xFF);
             }
             else
             {
                 raiseParameter = "0";
                 Basic.Set(node, 0x00);
                 SetNodeLevel(node, 0x00);
             }
         }
         else if (command == Command.THERMOSTAT_MODEGET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Thermostat.GetMode(node);
         }
         else if (command == Command.THERMOSTAT_MODESET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Thermostat.Mode mode = (Thermostat.Mode)Enum.Parse(typeof(Thermostat.Mode), request.GetOption(0));
             //
             raisePropertyChanged = true;
             parameterPath = "Thermostat.Mode";
             raiseParameter = request.GetOption(0);
             //
             Thermostat.SetMode(node, mode);
         }
         else if (command == Command.THERMOSTAT_SETPOINTGET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Thermostat.SetPointType mode = (Thermostat.SetPointType)Enum.Parse(typeof(Thermostat.SetPointType), request.GetOption(0));
             Thermostat.GetSetPoint(node, mode);
         }
         else if (command == Command.THERMOSTAT_SETPOINTSET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Thermostat.SetPointType mode = (Thermostat.SetPointType)Enum.Parse(typeof(Thermostat.SetPointType), request.GetOption(0));
             double temperature = double.Parse(request.GetOption(1).Replace(',', '.'), CultureInfo.InvariantCulture);
             //
             raisePropertyChanged = true;
             parameterPath = "Thermostat.SetPoint." + request.GetOption(0);
             raiseParameter = temperature.ToString(CultureInfo.InvariantCulture);
             //
             Thermostat.SetSetPoint(node, mode, temperature);
         }
         else if (command == Command.THERMOSTAT_FANMODEGET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Thermostat.GetFanMode(node);
         }
         else if (command == Command.THERMOSTAT_FANMODESET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Thermostat.FanMode mode = (Thermostat.FanMode)Enum.Parse(typeof(Thermostat.FanMode), request.GetOption(0));
             //
             raisePropertyChanged = true;
             parameterPath = "Thermostat.FanMode";
             raiseParameter = request.GetOption(0);
             //
             Thermostat.SetFanMode(node, mode);
         }
         else if (command == Command.THERMOSTAT_FANSTATEGET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Thermostat.GetFanState(node);
         }
         /*
         else if (command == Command.THERMOSTAT_GETALL)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             // TODO: it should query all SetPointType supported by current node, not just Heating
             ((Thermostat)node.DeviceHandler).GetSetPoint(Thermostat.SetPointType.Heating);
             Thread.Sleep(200);
             ((Thermostat)node.DeviceHandler).GetFanState();
             Thread.Sleep(200);
             ((Thermostat)node.DeviceHandler).GetFanMode();
             Thread.Sleep(200);
             ((Thermostat)node.DeviceHandler).GetMode();
             // TODO: find an alternative to the deprecated method below
             //Thread.Sleep(200);
             //node.RequestMultiLevelReport();
         }
         */
         else if (command == Command.THERMOSTAT_OPERATINGSTATE_GET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             Thermostat.GetOperatingState(node);
         }
         else if(command==Command.USERCODE_SET)
         {
             var node = controller.GetDevice((byte)int.Parse(nodeId));
             byte userId = byte.Parse(request.GetOption(0));
             byte userIdStatus = byte.Parse(request.GetOption(1));
             byte[] tagCode = ZWaveLib.Utility.HexStringToByteArray(request.GetOption(2));
             UserCode.Set(node, new ZWaveLib.Values.UserCodeValue(userId, userIdStatus, tagCode));
         }
     }
     catch
     {
         if (raiseParameter != "") raisePropertyChanged = true;
     }
     //
     if (raisePropertyChanged && InterfacePropertyChangedAction != null)
     {
         try
         {
             //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
             InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                 Domain = this.Domain,
                 SourceId = nodeId,
                 SourceType = "ZWave Node",
                 Path = parameterPath,
                 Value = raiseParameter
             });
         }
         catch
         {
         }
     }
     //
     return returnValue;
 }
Пример #20
0
        public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migCommand)
        {
            var logData = new List <LogEntry>();

            try
            {
                switch (migCommand.Command)
                {
                case "Recent.From":
                    logData             = homegenie.RecentEventsLog.ToList().FindAll(le => le != null && le.Domain.StartsWith("MIG.") == false && (le.UnixTimestamp >= double.Parse(migCommand.GetOption(0))));
                    migCommand.Response = JsonConvert.SerializeObject(logData);     //, Formatting.Indented);
                    break;

                case "Recent.Last":
                    logData = homegenie.RecentEventsLog.ToList().FindAll(le => le != null &&
                                                                         le.Domain.StartsWith("MIG.") == false &&
                                                                         le.Timestamp > DateTime.UtcNow.AddMilliseconds(-int.Parse(migCommand.GetOption(0))));
                    migCommand.Response = JsonConvert.SerializeObject(logData);     //, Formatting.Indented);
                    break;

                case "RealTime.EventStream":
                    HttpListenerContext context = (HttpListenerContext)request.Context;
                    //context.Response.KeepAlive = true;
                    context.Response.ContentEncoding = Encoding.UTF8;
                    context.Response.ContentType     = "text/event-stream";
                    context.Response.AddHeader("Cache-Control", "no-cache");
                    context.Response.AddHeader("Access-Control-Allow-Origin", "*");
                    //
                    // 2K padding for IE
                    var    padding     = ":" + new String(' ', 2048) + "\n";
                    byte[] paddingData = System.Text.Encoding.UTF8.GetBytes(padding);
                    context.Response.OutputStream.Write(paddingData, 0, paddingData.Length);
                    byte[] retryData = System.Text.Encoding.UTF8.GetBytes("retry: 1000\n");
                    context.Response.OutputStream.Write(retryData, 0, retryData.Length);
                    context.Response.OutputStream.Flush();
                    //
                    double lastTimeStamp = 0;
                    var    lastId        = context.Request.Headers.Get("Last-Event-ID");
                    if (lastId == null || lastId == "")
                    {
                        var queryValues = HttpUtility.ParseQueryString(context.Request.Url.Query);
                        lastId = queryValues.Get("lastEventId");
                    }

                    if (lastId != null && lastId != "")
                    {
                        double.TryParse(lastId, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out lastTimeStamp);
                    }

                    if (lastTimeStamp == 0)
                    {
                        lastTimeStamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds;
                    }
                    int looped = 0;
                    while (looped < 10)
                    {
                        logData = homegenie.RecentEventsLog.ToList().FindAll(le => le != null &&
                                                                             le.Domain.StartsWith("MIG.") == false &&
                                                                             le.UnixTimestamp > lastTimeStamp);
                        if (logData.Count > 0)
                        {
                            foreach (LogEntry entry in logData)
                            {
                                byte[] data = System.Text.Encoding.UTF8.GetBytes("id: " + entry.UnixTimestamp.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + "\ndata: " + JsonConvert.SerializeObject(entry) + "\n\n");
                                context.Response.OutputStream.Write(data, 0, data.Length);
                                context.Response.OutputStream.Flush();
                                lastTimeStamp = entry.UnixTimestamp;
                            }
                        }
                        System.Threading.Thread.Sleep(1000);
                        looped++;
                    }
                    break;
                }
            }
            catch
            {
            }
        }
Пример #21
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     var command = (Command)request.Command;
     string returnvalue = "";
     //
     if (command == Command.CONTROL_ON)
     {
         this.OutputPin((RaspiGpio)int.Parse(request.NodeId), true);
         GpioPins[request.NodeId] = true;
         if (InterfacePropertyChangedAction != null)
         {
             try
             {
                 InterfacePropertyChangedAction(new InterfacePropertyChangedAction() { Domain = this.Domain, SourceId = request.NodeId, SourceType = "Raspberry Pi GPIO", Path = ModuleParameters.MODPAR_STATUS_LEVEL, Value = 1 });
             }
             catch { }
         }
     }
     //
     if (command == Command.CONTROL_OFF)
     {
         this.OutputPin((RaspiGpio)int.Parse(request.NodeId), false);
         GpioPins[request.NodeId] = false;
         if (InterfacePropertyChangedAction != null)
         {
             try
             {
                 InterfacePropertyChangedAction(new InterfacePropertyChangedAction() { Domain = this.Domain, SourceId = request.NodeId, SourceType = "Raspberry Pi GPIO", Path = ModuleParameters.MODPAR_STATUS_LEVEL, Value = 0 });
             }
             catch { }
         }
     }
     //
     if (command == Command.PARAMETER_STATUS)
     {
         GpioPins[request.NodeId] = this.InputPin((RaspiGpio)int.Parse(request.NodeId));
     }
     //
     if (command == Command.CONTROL_RESET)
     {
         this.CleanUpAllPins();
         foreach (KeyValuePair<string, bool> kv in GpioPins)
         {
             GpioPins[kv.Key] = false;
         }
     }
     //
     return returnvalue;
 }
Пример #22
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     request.Response = ""; //default success value
     //
     if (request.Command == Command.CAMERA_GETPICTURE)
     {
         // get picture from camera <nodeid>
         // TODO: there is actually only single camera support
         if (cameraSource != IntPtr.Zero)
         {
             lock (readPictureLock)
             {
                 var pictureBuffer = CameraCaptureV4LInterop.GetFrame(cameraSource);
                 var data = new byte[pictureBuffer.Size];
                 Marshal.Copy(pictureBuffer.Data, data, 0, pictureBuffer.Size);
                 return data;
             }
         }
     }
     else if (request.Command == Command.CAMERA_GETLUMINANCE)
     {
         // TODO: ....
     }
     else if (request.Command == Command.CAMERA_SETDEVICE)
     {
         this.GetOption("Configuration").Value = request.GetOption(0) + "," + request.GetOption(1) + "," + request.GetOption(2) + "," + request.GetOption(3);
         Connect();
     }
     //
     return request.Response;
 }
Пример #23
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string returnValue          = "";
            bool   raisePropertyChanged = false;
            string parameterPath        = "Status.Level";
            string raiseParameter       = "";
            //
            string  nodeId  = request.NodeId;
            Command command = (Command)request.Command;

            ////----------------------
            try
            {
                if (command == Command.CONTROLLER_DISCOVERY)
                {
                    controller.Discovery();
                }
                else if (command == Command.CONTROLLER_SOFTRESET)
                {
                    controller.SoftReset();
                }
                else if (command == Command.CONTROLLER_HARDRESET)
                {
                    controller.HardReset();
                    Thread.Sleep(500);
                    controller.Discovery();
                }
                else if (command == Command.CONTROLLER_NODEADD)
                {
                    lastAddedNode = 0;
                    byte addedId = controller.BeginNodeAdd();
                    for (int i = 0; i < 20; i++)
                    {
                        if (lastAddedNode > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    controller.StopNodeAdd();
                    //
                    returnValue = lastAddedNode.ToString();
                }
                else if (command == Command.CONTROLLER_NODEREMOVE)
                {
                    lastRemovedNode = 0;
                    byte remcid = controller.BeginNodeRemove();
                    for (int i = 0; i < 20; i++)
                    {
                        if (lastRemovedNode > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    controller.StopNodeRemove();
                    //
                    returnValue = lastRemovedNode.ToString();
                }
                ////----------------------
                else if (command == Command.BASIC_SET)
                {
                    raisePropertyChanged = true;
                    double raiseValue = double.Parse(request.GetOption(0)) / 100;
                    if (raiseValue > 1)
                    {
                        raiseValue = 1;
                    }
                    raiseParameter = raiseValue.ToString(CultureInfo.InvariantCulture);
                    //
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Basic_Set((byte)int.Parse(request.GetOption(0)));
                }
                else if (command == Command.BASIC_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Basic_Get();
                }
                ////-----------------------
                else if (command == Command.MULTIINSTANCE_GETCOUNT)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    //
                    switch (request.GetOption(0))
                    {
                    case "Switch.Binary":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SWITCH_BINARY);
                        break;

                    case "Switch.MultiLevel":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SWITCH_MULTILEVEL);
                        break;

                    case "Sensor.Binary":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SENSOR_BINARY);
                        break;

                    case "Sensor.MultiLevel":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SENSOR_MULTILEVEL);
                        break;
                    }
                }
                else if (command == Command.MULTIINSTANCE_GET)
                {
                    var  node     = controller.GetDevice((byte)int.Parse(nodeId));
                    byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
                    //
                    switch (request.GetOption(0))
                    {
                    case "Switch.Binary":
                        node.MultiInstance_SwitchBinaryGet(instance);
                        break;

                    case "Switch.MultiLevel":
                        node.MultiInstance_SwitchMultiLevelGet(instance);
                        break;

                    case "Sensor.Binary":
                        node.MultiInstance_SensorBinaryGet(instance);
                        break;

                    case "Sensor.MultiLevel":
                        node.MultiInstance_SensorMultiLevelGet(instance);
                        break;
                    }
                }
                else if (command == Command.MULTIINSTANCE_SET)
                {
                    var  node     = controller.GetDevice((byte)int.Parse(nodeId));
                    byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
                    int  value    = int.Parse(request.GetOption(2));
                    //
                    //raisepropchanged = true;
                    //parampath += "." + instance; // Status.Level.<instance>
                    //
                    switch (request.GetOption(0))
                    {
                    case "Switch.Binary":
                        node.MultiInstance_SwitchBinarySet(instance, value);
                        //raiseparam = (double.Parse(request.GetOption(2)) / 255).ToString();
                        break;

                    case "Switch.MultiLevel":
                        node.MultiInstance_SwitchMultiLevelSet(instance, value);
                        //raiseparam = (double.Parse(request.GetOption(2)) / 100).ToString(); // TODO: should it be 99 ?
                        break;
                    }
                }
                else if (command == Command.SENSORBINARY_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.SensorBinary_Get();
                }
                else if (command == Command.SENSORMULTILEVEL_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.SensorMultiLevel_Get();
                }
                else if (command == Command.METER_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Meter_Get();
                }
                else if (command == Command.METER_SUPPORTEDGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Meter_SupportedGet();
                }
                else if (command == Command.METER_RESET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Meter_Reset();
                }
                else if (command == Command.NODEINFO_GET)
                {
                    controller.GetNodeInformationFrame((byte)int.Parse(nodeId));
                }
                ////-----------------------
                else if (command == Command.BATTERY_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Battery_Get();
                }
                ////-----------------------
                else if (command == Command.ASSOCIATION_SET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Association_Set((byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                }
                else if (command == Command.ASSOCIATION_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Association_Get((byte)int.Parse(request.GetOption(0))); // groupid
                }
                else if (command == Command.ASSOCIATION_REMOVE)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Association_Remove(
                        (byte)int.Parse(request.GetOption(0)),
                        (byte)int.Parse(request.GetOption(1))
                        ); // groupid
                }
                ////-----------------------
                else if (command == Command.MANUFACTURERSPECIFIC_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.ManufacturerSpecific_Get();
                }
                ////------------------
                else if (command == Command.CONFIG_PARAMETERSET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    //byte[] value = new byte[] { (byte)int.Parse(option1) };//BitConverter.GetBytes(Int16.Parse(option1));
                    //Array.Reverse(value);
                    node.Configuration_ParameterSet((byte)int.Parse(request.GetOption(0)), int.Parse(request.GetOption(1)));
                }
                else if (command == Command.CONFIG_PARAMETERGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Configuration_ParameterGet((byte)int.Parse(request.GetOption(0)));
                }
                ////------------------
                else if (command == Command.WAKEUP_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.WakeUp_Get();
                }
                else if (command == Command.WAKEUP_SET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.WakeUp_Set(uint.Parse(request.GetOption(0)));
                }
                ////------------------
                else if (command == Command.CONTROL_ON)
                {
                    raisePropertyChanged = true;
                    raiseParameter       = "1";
                    //
                    // Basic.Set 0xFF
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Switch)node.DeviceHandler).On();
                }
                else if (command == Command.CONTROL_OFF)
                {
                    raisePropertyChanged = true;
                    raiseParameter       = "0";
                    //
                    // Basic.Set 0x00
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Switch)node.DeviceHandler).Off();
                }
                else if (command == Command.CONTROL_LEVEL)
                {
                    raisePropertyChanged = true;
                    raiseParameter       = (double.Parse(request.GetOption(0)) / 100).ToString();
                    //
                    // Basic.Set <level>
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Dimmer)node.DeviceHandler).Level = int.Parse(request.GetOption(0));
                }
                else if (command == Command.CONTROL_TOGGLE)
                {
                    raisePropertyChanged = true;
                    //
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    if (((Switch)node.DeviceHandler).Level == 0)
                    {
                        raiseParameter = "1";
                        // Basic.Set 0xFF
                        ((Switch)node.DeviceHandler).On();
                    }
                    else
                    {
                        raiseParameter = "0";
                        // Basic.Set 0x00
                        ((Switch)node.DeviceHandler).Off();
                    }
                }
                else if (command == Command.THERMOSTAT_MODEGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_ModeGet();
                }
                else if (command == Command.THERMOSTAT_MODESET)
                {
                    var             node = controller.GetDevice((byte)int.Parse(nodeId));
                    Thermostat.Mode mode = (Thermostat.Mode)Enum.Parse(typeof(Thermostat.Mode), request.GetOption(0));
                    //
                    raisePropertyChanged = true;
                    parameterPath        = "Thermostat.Mode";
                    raiseParameter       = request.GetOption(0);
                    //
                    ((Thermostat)node.DeviceHandler).Thermostat_ModeSet(mode);
                }
                else if (command == Command.THERMOSTAT_SETPOINTGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_SetPointGet();
                }
                else if (command == Command.THERMOSTAT_SETPOINTSET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    Thermostat.SetPointType mode = (Thermostat.SetPointType)Enum.Parse(typeof(Thermostat.SetPointType), request.GetOption(0));
                    int temperature = int.Parse(request.GetOption(1));
                    //
                    raisePropertyChanged = true;
                    parameterPath        = "Thermostat.SetPoint." + request.GetOption(0);
                    raiseParameter       = temperature.ToString(CultureInfo.InvariantCulture);
                    //
                    ((Thermostat)node.DeviceHandler).Thermostat_SetPointSet(mode, temperature);
                }
                else if (command == Command.THERMOSTAT_FANMODEGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_FanModeGet();
                }
                else if (command == Command.THERMOSTAT_FANMODESET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    Thermostat.FanMode mode = (Thermostat.FanMode)Enum.Parse(typeof(Thermostat.FanMode), request.GetOption(0));
                    //
                    raisePropertyChanged = true;
                    parameterPath        = "Thermostat.FanMode";
                    raiseParameter       = request.GetOption(0);
                    //
                    ((Thermostat)node.DeviceHandler).Thermostat_FanModeSet(mode);
                }
                else if (command == Command.THERMOSTAT_FANSTATEGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_FanStateGet();
                }
                else if (command == Command.THERMOSTAT_GETALL)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_SetPointGet();
                    Thread.Sleep(200);
                    ((Thermostat)node.DeviceHandler).Thermostat_FanStateGet();
                    Thread.Sleep(200);
                    ((Thermostat)node.DeviceHandler).Thermostat_FanModeGet();
                    Thread.Sleep(200);
                    ((Thermostat)node.DeviceHandler).Thermostat_ModeGet();
                    // TODO: find an alternative to the deprecated method below
                    //Thread.Sleep(200);
                    //node.RequestMultiLevelReport();
                }
            }
            catch
            {
                if (raiseParameter != "")
                {
                    raisePropertyChanged = true;
                }
            }
            //
            if (raisePropertyChanged && InterfacePropertyChangedAction != null)
            {
                try
                {
                    //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction()
                    {
                        Domain     = this.Domain,
                        SourceId   = nodeId,
                        SourceType = "ZWave Node",
                        Path       = parameterPath,
                        Value      = raiseParameter
                    });
                }
                catch
                {
                }
            }
            //
            return(returnValue);
        }
Пример #24
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string nodeId = request.NodeId;
            var command = (Command)request.Command;
            string option = request.GetOption(0);

            DeviceBase device = null;
            insteonPlm.Network.TryConnectToDevice(nodeId, out device);

            //TODO: handle types IrrigationControl and PoolAndSpaControl

            if (command == Command.CONTROL_ON)
            {
                if (device != null)
                switch (device.GetType().Name)
                {
                case "LightingControl":
                    (device as LightingControl).TurnOn();
                    break;
                case "DimmableLightingControl":
                    (device as DimmableLightingControl).TurnOn();
                    break;
                case "SwitchedLightingControl":
                    (device as SwitchedLightingControl).TurnOn();
                    break;
                case "SensorsActuators":
                    (device as SensorsActuators).TurnOnOutput(byte.Parse(option));
                    break;
                case "WindowCoveringControl":
                    (device as WindowCoveringControl).Open();
                    break;
                case "PoolAndSpaControl":
                    break;
                case "IrrigationControl":
                    (device as IrrigationControl).TurnOnSprinklerValve(byte.Parse(option));
                    break;
                }
            }
            else if (command == Command.CONTROL_OFF)
            {
                if (device != null)
                switch (device.GetType().Name)
                {
                case "LightingControl":
                    (device as LightingControl).TurnOff();
                    break;
                case "DimmableLightingControl":
                    (device as DimmableLightingControl).TurnOff();
                    break;
                case "SwitchedLightingControl":
                    (device as SwitchedLightingControl).TurnOff();
                    break;
                case "SensorsActuators":
                    (device as SensorsActuators).TurnOffOutput(byte.Parse(option));
                    break;
                case "WindowCoveringControl":
                    (device as WindowCoveringControl).Close();
                    break;
                case "PoolAndSpaControl":
                    break;
                case "IrrigationControl":
                    (device as IrrigationControl).TurnOffSprinklerValve(byte.Parse(option));
                    break;
                }
            }
            else if (command == Command.CONTROL_BRIGHT)
            {
                if (device != null && device is DimmableLightingControl)
                {
                    (device as DimmableLightingControl).BrightenOneStep();
                }
            }
            else if (command == Command.CONTROL_DIM)
            {
                if (device != null && device is DimmableLightingControl)
                {
                    (device as DimmableLightingControl).DimOneStep();
                }
            }
            else if (command == Command.CONTROL_LEVEL)
            {
                byte level = byte.Parse(option);
                if (device != null)
                switch (device.GetType().Name)
                {
                case "DimmableLightingControl":
                    (device as DimmableLightingControl).RampOn(level);
                    break;
                case "WindowCoveringControl":
                    (device as WindowCoveringControl).MoveToPosition(level);
                    break;
                }
            }
            else if (command == Command.CONTROL_TOGGLE)
            {
            }
            else if (command == Command.CONTROL_ALLLIGHTSON)
            {
            }
            else if (command == Command.CONTROL_ALLLIGHTSOFF)
            {
            }
            //
            return "";
        }
Пример #25
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string returnValue = "";
            bool raisePropertyChanged = false;
            string parameterPath = "Status.Level";
            string raiseParameter = "";
            //
            string nodeId = request.NodeId;
            Command command = (Command)request.Command;
            ////----------------------
            try
            {
                if (command == Command.CONTROLLER_DISCOVERY)
                {
                    controller.Discovery();
                }
                else if (command == Command.CONTROLLER_SOFTRESET)
                {
                    controller.SoftReset();
                }
                else if (command == Command.CONTROLLER_HARDRESET)
                {
                    controller.HardReset();
                    Thread.Sleep(500);
                    controller.Discovery();
                }
                else if (command == Command.CONTROLLER_NODEADD)
                {
                    lastAddedNode = 0;
                    byte addedId = controller.BeginNodeAdd();
                    for (int i = 0; i < 20; i++)
                    {
                        if (lastAddedNode > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    controller.StopNodeAdd();
                    //
                    returnValue = lastAddedNode.ToString();
                }
                else if (command == Command.CONTROLLER_NODEREMOVE)
                {
                    lastRemovedNode = 0;
                    byte remcid = controller.BeginNodeRemove();
                    for (int i = 0; i < 20; i++)
                    {
                        if (lastRemovedNode > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    controller.StopNodeRemove();
                    //
                    returnValue = lastRemovedNode.ToString();
                }
                ////----------------------
                else if (command == Command.BASIC_SET)
                {
                    raisePropertyChanged = true;
                    double raiseValue = double.Parse(request.GetOption(0)) / 100;
                    if (raiseValue > 1) raiseValue = 1;
                    raiseParameter = raiseValue.ToString(CultureInfo.InvariantCulture);
                    //
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Basic_Set((byte)int.Parse(request.GetOption(0)));
                }
                else if (command == Command.BASIC_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Basic_Get();
                }
                ////-----------------------
                else if (command == Command.MULTIINSTANCE_GETCOUNT)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    //
                    switch (request.GetOption(0))
                    {
                    case "Switch.Binary":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SWITCH_BINARY);
                        break;
                    case "Switch.MultiLevel":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SWITCH_MULTILEVEL);
                        break;
                    case "Sensor.Binary":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SENSOR_BINARY);
                        break;
                    case "Sensor.MultiLevel":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SENSOR_MULTILEVEL);
                        break;
                    }
                }
                else if (command == Command.MULTIINSTANCE_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
                    //
                    switch (request.GetOption(0))
                    {
                    case "Switch.Binary":
                        node.MultiInstance_SwitchBinaryGet(instance);
                        break;
                    case "Switch.MultiLevel":
                        node.MultiInstance_SwitchMultiLevelGet(instance);
                        break;
                    case "Sensor.Binary":
                        node.MultiInstance_SensorBinaryGet(instance);
                        break;
                    case "Sensor.MultiLevel":
                        node.MultiInstance_SensorMultiLevelGet(instance);
                        break;
                    }
                }
                else if (command == Command.MULTIINSTANCE_SET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
                    int value = int.Parse(request.GetOption(2));
                    //
                    //raisepropchanged = true;
                    //parampath += "." + instance; // Status.Level.<instance>
                    //
                    switch (request.GetOption(0))
                    {
                    case "Switch.Binary":
                        node.MultiInstance_SwitchBinarySet(instance, value);
                            //raiseparam = (double.Parse(request.GetOption(2)) / 255).ToString();
                        break;
                    case "Switch.MultiLevel":
                        node.MultiInstance_SwitchMultiLevelSet(instance, value);
                            //raiseparam = (double.Parse(request.GetOption(2)) / 100).ToString(); // TODO: should it be 99 ?
                        break;
                    }
                }
                else if (command == Command.SENSORBINARY_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.SensorBinary_Get();
                }
                else if (command == Command.SENSORMULTILEVEL_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.SensorMultiLevel_Get();
                }
                else if (command == Command.METER_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Meter_Get();
                }
                else if (command == Command.METER_SUPPORTEDGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Meter_SupportedGet();
                }
                else if (command == Command.METER_RESET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Meter_Reset();
                }
                else if (command == Command.NODEINFO_GET)
                {
                    controller.GetNodeInformationFrame((byte)int.Parse(nodeId));
                }
                ////-----------------------
                else if (command == Command.BATTERY_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Battery_Get();
                }
                ////-----------------------
                else if (command == Command.ASSOCIATION_SET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Association_Set((byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                }
                else if (command == Command.ASSOCIATION_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Association_Get((byte)int.Parse(request.GetOption(0))); // groupid
                }
                else if (command == Command.ASSOCIATION_REMOVE)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Association_Remove(
                        (byte)int.Parse(request.GetOption(0)),
                        (byte)int.Parse(request.GetOption(1))
                    ); // groupid
                }
                ////-----------------------
                else if (command == Command.MANUFACTURERSPECIFIC_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.ManufacturerSpecific_Get();
                }
                ////------------------
                else if (command == Command.CONFIG_PARAMETERSET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    //byte[] value = new byte[] { (byte)int.Parse(option1) };//BitConverter.GetBytes(Int16.Parse(option1));
                    //Array.Reverse(value);
                    node.Configuration_ParameterSet((byte)int.Parse(request.GetOption(0)), int.Parse(request.GetOption(1)));
                }
                else if (command == Command.CONFIG_PARAMETERGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Configuration_ParameterGet((byte)int.Parse(request.GetOption(0)));
                }
                ////------------------
                else if (command == Command.WAKEUP_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.WakeUp_Get();
                }
                else if (command == Command.WAKEUP_SET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.WakeUp_Set(uint.Parse(request.GetOption(0)));
                }
                ////------------------
                else if (command == Command.CONTROL_ON)
                {
                    raisePropertyChanged = true;
                    raiseParameter = "1";
                    //
                    // Basic.Set 0xFF
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Switch)node.DeviceHandler).On();
                }
                else if (command == Command.CONTROL_OFF)
                {
                    raisePropertyChanged = true;
                    raiseParameter = "0";
                    //
                    // Basic.Set 0x00
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Switch)node.DeviceHandler).Off();
                }
                else if (command == Command.CONTROL_LEVEL)
                {
                    raisePropertyChanged = true;
                    raiseParameter = (double.Parse(request.GetOption(0)) / 100).ToString();
                    //
                    // Basic.Set <level>
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Dimmer)node.DeviceHandler).Level = int.Parse(request.GetOption(0));
                }
                else if (command == Command.CONTROL_TOGGLE)
                {
                    raisePropertyChanged = true;
                    //
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    if (((Switch)node.DeviceHandler).Level == 0)
                    {
                        raiseParameter = "1";
                        // Basic.Set 0xFF
                        ((Switch)node.DeviceHandler).On();
                    }
                    else
                    {
                        raiseParameter = "0";
                        // Basic.Set 0x00
                        ((Switch)node.DeviceHandler).Off();
                    }
                }
                else if (command == Command.THERMOSTAT_MODEGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_ModeGet();
                }
                else if (command == Command.THERMOSTAT_MODESET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    Thermostat.Mode mode = (Thermostat.Mode)Enum.Parse(typeof(Thermostat.Mode), request.GetOption(0));
                    //
                    raisePropertyChanged = true;
                    parameterPath = "Thermostat.Mode";
                    raiseParameter = request.GetOption(0);
                    //
                    ((Thermostat)node.DeviceHandler).Thermostat_ModeSet(mode);
                }
                else if (command == Command.THERMOSTAT_SETPOINTGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_SetPointGet();
                }
                else if (command == Command.THERMOSTAT_SETPOINTSET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    Thermostat.SetPointType mode = (Thermostat.SetPointType)Enum.Parse(typeof(Thermostat.SetPointType), request.GetOption(0));
                    int temperature = int.Parse(request.GetOption(1));
                    //
                    raisePropertyChanged = true;
                    parameterPath = "Thermostat.SetPoint." + request.GetOption(0);
                    raiseParameter = temperature.ToString(CultureInfo.InvariantCulture);
                    //
                    ((Thermostat)node.DeviceHandler).Thermostat_SetPointSet(mode, temperature);
                }
                else if (command == Command.THERMOSTAT_FANMODEGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_FanModeGet();
                }
                else if (command == Command.THERMOSTAT_FANMODESET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    Thermostat.FanMode mode = (Thermostat.FanMode)Enum.Parse(typeof(Thermostat.FanMode), request.GetOption(0));
                    //
                    raisePropertyChanged = true;
                    parameterPath = "Thermostat.FanMode";
                    raiseParameter = request.GetOption(0);
                    //
                    ((Thermostat)node.DeviceHandler).Thermostat_FanModeSet(mode);
                }
                else if (command == Command.THERMOSTAT_FANSTATEGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_FanStateGet();
                }
                else if (command == Command.THERMOSTAT_GETALL)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((Thermostat)node.DeviceHandler).Thermostat_SetPointGet();
                    Thread.Sleep(200);
                    ((Thermostat)node.DeviceHandler).Thermostat_FanStateGet();
                    Thread.Sleep(200);
                    ((Thermostat)node.DeviceHandler).Thermostat_FanModeGet();
                    Thread.Sleep(200);
                    ((Thermostat)node.DeviceHandler).Thermostat_ModeGet();
                    // TODO: find an alternative to the deprecated method below
                    //Thread.Sleep(200);
                    //node.RequestMultiLevelReport();
                }

            }
            catch
            {
                if (raiseParameter != "") raisePropertyChanged = true;
            }
            //
            if (raisePropertyChanged && InterfacePropertyChangedAction != null)
            {
                try
                {
                    //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                        Domain = this.Domain,
                        SourceId = nodeId,
                        SourceType = "ZWave Node",
                        Path = parameterPath,
                        Value = raiseParameter
                    });
                }
                catch
                {
                }
            }
            //
            return returnValue;
        }
Пример #26
0
        public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migCommand)
        {
            string       streamcontent = "";
            ProgramBlock currentProgram;
            ProgramBlock newProgram;

            //
            homegenie.ExecuteAutomationRequest(migCommand);
            if (migCommand.Command.StartsWith("Macro."))
            {
                switch (migCommand.Command)
                {
                case "Macro.Record":
                    homegenie.ProgramEngine.MacroRecorder.RecordingEnable();
                    break;

                case "Macro.Save":
                    newProgram          = homegenie.ProgramEngine.MacroRecorder.SaveMacro(migCommand.GetOption(1));
                    migCommand.Response = newProgram.Address.ToString();
                    break;

                case "Macro.Discard":
                    homegenie.ProgramEngine.MacroRecorder.RecordingDisable();
                    break;

                case "Macro.SetDelay":
                    switch (migCommand.GetOption(0).ToLower())
                    {
                    case "none":
                        homegenie.ProgramEngine.MacroRecorder.DelayType = MacroDelayType.None;
                        break;

                    case "mimic":
                        homegenie.ProgramEngine.MacroRecorder.DelayType = MacroDelayType.Mimic;
                        break;

                    case "fixed":
                        double secs = double.Parse(migCommand.GetOption(1), System.Globalization.CultureInfo.InvariantCulture);
                        homegenie.ProgramEngine.MacroRecorder.DelayType    = MacroDelayType.Fixed;
                        homegenie.ProgramEngine.MacroRecorder.DelaySeconds = secs;
                        break;
                    }
                    break;

                case "Macro.GetDelay":
                    migCommand.Response = "[{ DelayType : '" + homegenie.ProgramEngine.MacroRecorder.DelayType + "', DelayOptions : '" + homegenie.ProgramEngine.MacroRecorder.DelaySeconds + "' }]";
                    break;
                }
            }
            else if (migCommand.Command.StartsWith("Scheduling."))
            {
                switch (migCommand.Command)
                {
                case "Scheduling.Add":
                case "Scheduling.Update":
                    var item = homegenie.ProgramEngine.SchedulerService.AddOrUpdate(migCommand.GetOption(0), migCommand.GetOption(1).Replace("|", "/"));
                    item.ProgramId = migCommand.GetOption(2);
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Delete":
                    homegenie.ProgramEngine.SchedulerService.Remove(migCommand.GetOption(0));
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Enable":
                    homegenie.ProgramEngine.SchedulerService.Enable(migCommand.GetOption(0));
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Disable":
                    homegenie.ProgramEngine.SchedulerService.Disable(migCommand.GetOption(0));
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Get":
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.ProgramEngine.SchedulerService.Get(migCommand.GetOption(0)));
                    break;

                case "Scheduling.List":
                    homegenie.ProgramEngine.SchedulerService.Items.Sort((SchedulerItem s1, SchedulerItem s2) =>
                    {
                        return(s1.Name.CompareTo(s2.Name));
                    });
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.ProgramEngine.SchedulerService.Items);
                    break;
                }
            }
            else if (migCommand.Command.StartsWith("Programs."))
            {
                if (migCommand.Command != "Programs.Import")
                {
                    streamcontent = new StreamReader(request.InputStream).ReadToEnd();
                }
                //
                switch (migCommand.Command)
                {
                case "Programs.Import":
                    string archiveName = "homegenie_program_import.hgx";
                    if (File.Exists(archiveName))
                    {
                        File.Delete(archiveName);
                    }
                    //
                    var    encoding = (request.Context as HttpListenerContext).Request.ContentEncoding;
                    string boundary = MIG.Gateways.WebServiceUtility.GetBoundary((request.Context as HttpListenerContext).Request.ContentType);
                    MIG.Gateways.WebServiceUtility.SaveFile(encoding, boundary, request.InputStream, archiveName);
                    //
                    var serializer = new XmlSerializer(typeof(ProgramBlock));
                    var reader     = new StreamReader(archiveName);
                    newProgram = (ProgramBlock)serializer.Deserialize(reader);
                    reader.Close();
                    //
                    newProgram.Address = homegenie.ProgramEngine.GeneratePid();
                    newProgram.Group   = migCommand.GetOption(0);
                    homegenie.ProgramEngine.ProgramAdd(newProgram);
                    //
                    newProgram.IsEnabled    = false;
                    newProgram.ScriptErrors = "";
                    newProgram.AppAssembly  = null;
                    //
                    homegenie.ProgramEngine.CompileScript(newProgram);
                    //
                    homegenie.UpdateProgramsDatabase();
                    //migCommand.response = JsonHelper.GetSimpleResponse(programblock.Address);
                    migCommand.Response = newProgram.Address.ToString();
                    break;

                case "Programs.Export":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    var writerSettings = new System.Xml.XmlWriterSettings();
                    writerSettings.Indent = true;
                    var programSerializer = new System.Xml.Serialization.XmlSerializer(typeof(ProgramBlock));
                    var builder           = new StringBuilder();
                    var writer            = System.Xml.XmlWriter.Create(builder, writerSettings);
                    programSerializer.Serialize(writer, currentProgram);
                    writer.Close();
                    migCommand.Response = builder.ToString();
                    //
                    (request.Context as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment; filename=\"" + currentProgram.Address + "-" + currentProgram.Name.Replace(" ", "_") + ".hgx\"");
                    break;

                case "Programs.List":
                    var programList = new List <ProgramBlock>(homegenie.ProgramEngine.Programs);
                    programList.Sort(delegate(ProgramBlock p1, ProgramBlock p2)
                    {
                        string c1 = p1.Name + " " + p1.Address;
                        string c2 = p2.Name + " " + p2.Address;
                        return(c1.CompareTo(c2));
                    });
                    migCommand.Response = JsonConvert.SerializeObject(programList);
                    break;

                case "Programs.Add":
                    newProgram = new ProgramBlock()
                    {
                        Group = migCommand.GetOption(0), Name = streamcontent, Type = "Wizard", ScriptCondition = "// A \"return true;\" statement at any point of this code block, will cause the program to run.\n// For manually activated program, just leave a \"return false\" statement here.\n\nreturn false;\n"
                    };
                    newProgram.Address = homegenie.ProgramEngine.GeneratePid();
                    homegenie.ProgramEngine.ProgramAdd(newProgram);
                    homegenie.UpdateProgramsDatabase();
                    migCommand.Response = JsonHelper.GetSimpleResponse(newProgram.Address.ToString());
                    break;

                case "Programs.Delete":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        //TODO: remove groups associations as well
                        currentProgram.IsEnabled = false;
                        homegenie.ProgramEngine.ProgramRemove(currentProgram);
                        homegenie.UpdateProgramsDatabase();
                        // remove associated module entry
                        homegenie.Modules.RemoveAll(m => m.Domain == Domains.HomeAutomation_HomeGenie_Automation && m.Address == currentProgram.Address.ToString());
                        homegenie.UpdateModulesDatabase();
                    }
                    break;

                case "Programs.Compile":
                case "Programs.Update":
                    newProgram     = JsonConvert.DeserializeObject <ProgramBlock>(streamcontent);
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == newProgram.Address);
                    //
                    if (currentProgram == null)
                    {
                        newProgram.Address = homegenie.ProgramEngine.GeneratePid();
                        homegenie.ProgramEngine.ProgramAdd(newProgram);
                    }
                    else
                    {
                        if (currentProgram.Type.ToLower() != newProgram.Type.ToLower())
                        {
                            currentProgram.AppAssembly = null;     // dispose assembly and interrupt current task
                        }
                        currentProgram.Type            = newProgram.Type;
                        currentProgram.Group           = newProgram.Group;
                        currentProgram.Name            = newProgram.Name;
                        currentProgram.Description     = newProgram.Description;
                        currentProgram.IsEnabled       = newProgram.IsEnabled;
                        currentProgram.ScriptCondition = newProgram.ScriptCondition;
                        currentProgram.ScriptSource    = newProgram.ScriptSource;
                        currentProgram.Commands        = newProgram.Commands;
                        currentProgram.Conditions      = newProgram.Conditions;
                        currentProgram.ConditionType   = newProgram.ConditionType;
                        // reset last condition evaluation status
                        currentProgram.LastConditionEvaluationResult = false;
                    }
                    //
                    if (migCommand.Command == "Programs.Compile")
                    {
                        // reset previous error status
                        currentProgram.IsEnabled = false;
                        currentProgram.Stop();
                        currentProgram.ScriptErrors = "";
                        //
                        List <ProgramError> errors = homegenie.ProgramEngine.CompileScript(currentProgram);
                        //
                        currentProgram.IsEnabled    = newProgram.IsEnabled;
                        currentProgram.ScriptErrors = JsonConvert.SerializeObject(errors);
                        migCommand.Response         = currentProgram.ScriptErrors;
                    }
                    //
                    homegenie.UpdateProgramsDatabase();
                    //
                    homegenie.modules_RefreshPrograms();
                    homegenie.modules_RefreshVirtualModules();
                    homegenie.modules_Sort();
                    break;

                case "Programs.Run":
                    currentProgram = ProgramRun(migCommand.GetOption(0), migCommand.GetOption(1));
                    break;

                case "Programs.Toggle":
                    currentProgram = ProgramToggle(migCommand.GetOption(0), migCommand.GetOption(1));
                    break;

                case "Programs.Break":
                    currentProgram = ProgramBreak(migCommand.GetOption(0));
                    break;

                case "Programs.Restart":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        currentProgram.IsEnabled = false;
                        try
                        {
                            currentProgram.Stop();
                        }
                        catch { }
                        currentProgram.IsEnabled = true;
                        homegenie.UpdateProgramsDatabase();
                    }
                    break;

                case "Programs.Enable":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        currentProgram.IsEnabled = true;
                        homegenie.UpdateProgramsDatabase();
                    }
                    break;

                case "Programs.Disable":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        currentProgram.IsEnabled = false;
                        try
                        {
                            currentProgram.Stop();
                        }
                        catch { }
                        homegenie.UpdateProgramsDatabase();
                    }
                    break;
                }
            }
        }
Пример #27
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string response = "[{ ResponseValue : 'OK' }]";

            string nodeId = request.NodeId;
            var command = (Command)request.Command;
            string option = request.GetOption(0);

            // Parse house/unit
            var houseCode = XTenLib.Utility.HouseCodeFromString(nodeId);
            var unitCode = XTenLib.Utility.UnitCodeFromString(nodeId);

            // Modules control
            if (command == Command.PARAMETER_STATUS)
            {
                x10lib.StatusRequest(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_ON)
            {
                x10lib.LightOn(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_OFF)
            {
                x10lib.LightOff(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_BRIGHT)
            {
                x10lib.Bright(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_DIM)
            {
                x10lib.Dim(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_LEVEL_ADJUST)
            {
                int dimvalue = int.Parse(option);
                x10lib.ModulesStatus[ nodeId ].Level = ((double)dimvalue/100D);
                InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                    Domain = this.Domain,
                    SourceId = nodeId,
                    SourceType = "X10 Module",
                    Path = "Status.Level",
                    Value = x10lib.ModulesStatus[ nodeId ].Level
                });
            }
            else if (command == Command.CONTROL_LEVEL)
            {
                int dimvalue = int.Parse(option) - (int)(x10lib.ModulesStatus[ nodeId ].Level * 100.0);
                if (dimvalue > 0)
                {
                    x10lib.Bright(houseCode, unitCode, dimvalue);
                }
                else if (dimvalue < 0)
                {
                    x10lib.Dim(houseCode, unitCode, -dimvalue);
                }
            }
            else if (command == Command.CONTROL_TOGGLE)
            {
                string huc = XTenLib.Utility.HouseUnitCodeFromEnum(houseCode, unitCode);
                if (x10lib.ModulesStatus[ huc ].Level == 0)
                {
                    x10lib.LightOn(houseCode, unitCode);
                }
                else
                {
                    x10lib.LightOff(houseCode, unitCode);
                }
            }
            else if (command == Command.CONTROL_ALLLIGHTSON)
            {
                x10lib.AllLightsOn(houseCode);
            }
            else if (command == Command.CONTROL_ALLLIGHTSOFF)
            {
                x10lib.AllUnitsOff(houseCode);
            }
            //
            return response;
        }
Пример #28
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            bool raisePropertyChanged = false;
            string parameterPath = "Status.Level";
            string raiseParameter = "";
            //
            string nodeId = request.NodeId;
            var command = (Command)request.Command;
            string option = request.GetOption(0);

            bool isDottedHexId = (nodeId.IndexOf(".") > 0);

            if (isDottedHexId)
            {
                // Standard Insteon device

                DeviceBase device = null;
                insteonPlm.Network.TryConnectToDevice(nodeId, out device);

                //TODO: handle types IrrigationControl and PoolAndSpaControl

                if (command == Command.CONTROL_ON)
                {
                    raisePropertyChanged = true;
                    raiseParameter = "1";
                    //
                    if (device != null)
                        switch (device.GetType().Name)
                        {
                        case "LightingControl":
                            (device as LightingControl).TurnOn();
                            break;
                        case "DimmableLightingControl":
                            (device as DimmableLightingControl).TurnOn();
                            break;
                        case "SwitchedLightingControl":
                            (device as SwitchedLightingControl).TurnOn();
                            break;
                        case "SensorsActuators":
                            (device as SensorsActuators).TurnOnOutput(byte.Parse(option));
                            break;
                        case "WindowCoveringControl":
                            (device as WindowCoveringControl).Open();
                            break;
                        case "PoolAndSpaControl":
                            break;
                        case "IrrigationControl":
                            (device as IrrigationControl).TurnOnSprinklerValve(byte.Parse(option));
                            break;
                        }
                }
                else if (command == Command.CONTROL_OFF)
                {
                    raisePropertyChanged = true;
                    raiseParameter = "0";
                    //
                    if (device != null)
                        switch (device.GetType().Name)
                        {
                        case "LightingControl":
                            (device as LightingControl).TurnOff();
                            break;
                        case "DimmableLightingControl":
                            (device as DimmableLightingControl).TurnOff();
                            break;
                        case "SwitchedLightingControl":
                            (device as SwitchedLightingControl).TurnOff();
                            break;
                        case "SensorsActuators":
                            (device as SensorsActuators).TurnOffOutput(byte.Parse(option));
                            break;
                        case "WindowCoveringControl":
                            (device as WindowCoveringControl).Close();
                            break;
                        case "PoolAndSpaControl":
                            break;
                        case "IrrigationControl":
                            (device as IrrigationControl).TurnOffSprinklerValve(byte.Parse(option));
                            break;
                        }
                }
                else if (command == Command.CONTROL_BRIGHT)
                {
                    // TODO: raise parameter change event
                    if (device != null && device is DimmableLightingControl)
                    {
                        (device as DimmableLightingControl).BrightenOneStep();
                    }
                }
                else if (command == Command.CONTROL_DIM)
                {
                    // TODO: raise parameter change event
                    if (device != null && device is DimmableLightingControl)
                    {
                        (device as DimmableLightingControl).DimOneStep();
                    }
                }
                else if (command == Command.CONTROL_LEVEL)
                {
                    double adjustedLevel = (double.Parse(option) / 100D);
                    raisePropertyChanged = true;
                    raiseParameter = adjustedLevel.ToString(CultureInfo.InvariantCulture);
                    //
                    byte level = (byte)((double.Parse(option) / 100D) * 255);
                    if (device != null)
                        switch (device.GetType().Name)
                        {
                        case "DimmableLightingControl":
                            (device as DimmableLightingControl).TurnOn(level);
                            break;
                        case "WindowCoveringControl":
                            (device as WindowCoveringControl).MoveToPosition(level);
                            break;
                        }
                }
                else if (command == Command.CONTROL_TOGGLE)
                {
                }
                else if (command == Command.CONTROL_ALLLIGHTSON)
                {
                }
                else if (command == Command.CONTROL_ALLLIGHTSOFF)
                {
                }
            }
            else
            {
                // It is not a dotted hex addres, so fallback to X10 device control
                var x10plm = insteonPlm.Network.X10;

                // Parse house/unit
                string houseCode = nodeId.Substring(0, 1);
                byte unitCode = 0x00;
                if (nodeId.Length > 1) unitCode = byte.Parse(nodeId.Substring(1));

                // Modules control
                if (command == Command.PARAMETER_STATUS)
                {
                    x10plm
                        .House(houseCode.ToString())
                        .Unit(unitCode)
                        .Command(X10Command.StatusRequest);
                }
                else if (command == Command.CONTROL_ON)
                {
                    raisePropertyChanged = true;
                    raiseParameter = "1";
                    //
                    x10plm
                        .House(houseCode)
                        .Unit(unitCode)
                        .Command(X10Command.On);
                }
                else if (command == Command.CONTROL_OFF)
                {
                    raisePropertyChanged = true;
                    raiseParameter = "0";
                    //
                    x10plm
                        .House(houseCode)
                        .Unit(unitCode)
                        .Command(X10Command.Off);
                }
                else if (command == Command.CONTROL_BRIGHT)
                {
                    // TODO: raise parameter change event
                    //int amount = int.Parse(option);
                    // TODO: how to specify bright amount parameter???
                    x10plm
                        .House(houseCode)
                        .Unit(unitCode)
                        .Command(X10Command.Bright);
                }
                else if (command == Command.CONTROL_DIM)
                {
                    // TODO: raise parameter change event
                    //int amount = int.Parse(option);
                    // TODO: how to specify dim amount parameter???
                    x10plm
                        .House(houseCode)
                        .Unit(unitCode)
                        .Command(X10Command.Dim);
                }
                else if (command == Command.CONTROL_LEVEL)
                {
                    double adjustedLevel = (double.Parse(option) / 100D);
                    raisePropertyChanged = true;
                    raiseParameter = adjustedLevel.ToString(CultureInfo.InvariantCulture);
                    //
                    /*int dimvalue = int.Parse(option) - (int)(x10lib.ModulesStatus[ nodeId ].Level * 100.0);
                    if (dimvalue > 0)
                    {
                        x10lib.Bright(houseCode, unitCode, dimvalue);
                    }
                    else if (dimvalue < 0)
                    {
                        x10lib.Dim(houseCode, unitCode, -dimvalue);
                    }*/
                }
                else if (command == Command.CONTROL_TOGGLE)
                {
                    /*
                    string huc = XTenLib.Utility.HouseUnitCodeFromEnum(houseCode, unitCode);
                    if (x10lib.ModulesStatus[ huc ].Level == 0)
                    {
                        x10lib.LightOn(houseCode, unitCode);
                    }
                    else
                    {
                        x10lib.LightOff(houseCode, unitCode);
                    }
                    */
                }
                else if (command == Command.CONTROL_ALLLIGHTSON)
                {
                    // TODO: ...
                    x10plm
                        .House(houseCode)
                        .Command(X10Command.AllLightsOn);
                }
                else if (command == Command.CONTROL_ALLLIGHTSOFF)
                {
                    // TODO: ...
                    x10plm
                        .House(houseCode)
                        .Command(X10Command.AllLightsOff);
                }

            }
            //
            if (raisePropertyChanged && InterfacePropertyChangedAction != null)
            {
                try
                {
                    //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                        Domain = this.Domain,
                        SourceId = nodeId,
                        SourceType = "Insteon Device",
                        Path = parameterPath,
                        Value = raiseParameter
                    });
                }
                catch
                {
                }
            }
            //
            return "";
        }
Пример #29
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            request.Response = ""; //default success value
            //
            if (request.Command == Command.CAMERA_GETPICTURE)
            {
                // get picture from camera <nodeid>
                // there is actually only single camera support though

                // TODO: check if file exists before opening it ("/dev/video0")
                if (cameraSource != IntPtr.Zero)
                {

                    var pictureBuffer = CameraCaptureV4LInterop.GetFrame(cameraSource);
                    var data = new byte[pictureBuffer.Size];
                    Marshal.Copy(pictureBuffer.Data, data, 0, pictureBuffer.Size);
                    //System.IO.File.WriteAllBytes("html/test.jpg", data);
                    return data;

                }
            }
            else if (request.Command == Command.CAMERA_GETLUMINANCE)
            {
                // TODO: ....
            }
            //
            return request.Response;
        }
Пример #30
0
 private object InterfaceControl(Module module, MIGInterfaceCommand migCommand)
 {
     migCommand.Domain = module.Domain;
     migCommand.NodeId = module.Address;
     return(homegenie.InterfaceControl(migCommand));
 }
Пример #31
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            bool   raisePropertyChanged = false;
            string parameterPath        = "Status.Level";
            string raiseParameter       = "";
            //
            string nodeId  = request.NodeId;
            var    command = (Command)request.Command;
            string option  = request.GetOption(0);

            bool isDottedHexId = (nodeId.IndexOf(".") > 0);

            if (isDottedHexId)
            {
                // Standard Insteon device

                DeviceBase device = null;
                insteonPlm.Network.TryConnectToDevice(nodeId, out device);

                //TODO: handle types IrrigationControl and PoolAndSpaControl

                if (command == Command.CONTROL_ON)
                {
                    raisePropertyChanged = true;
                    raiseParameter       = "1";
                    //
                    if (device != null)
                    {
                        switch (device.GetType().Name)
                        {
                        case "LightingControl":
                            (device as LightingControl).TurnOn();
                            break;

                        case "DimmableLightingControl":
                            (device as DimmableLightingControl).TurnOn();
                            break;

                        case "SwitchedLightingControl":
                            (device as SwitchedLightingControl).TurnOn();
                            break;

                        case "SensorsActuators":
                            (device as SensorsActuators).TurnOnOutput(byte.Parse(option));
                            break;

                        case "WindowCoveringControl":
                            (device as WindowCoveringControl).Open();
                            break;

                        case "PoolAndSpaControl":
                            break;

                        case "IrrigationControl":
                            (device as IrrigationControl).TurnOnSprinklerValve(byte.Parse(option));
                            break;
                        }
                    }
                }
                else if (command == Command.CONTROL_OFF)
                {
                    raisePropertyChanged = true;
                    raiseParameter       = "0";
                    //
                    if (device != null)
                    {
                        switch (device.GetType().Name)
                        {
                        case "LightingControl":
                            (device as LightingControl).TurnOff();
                            break;

                        case "DimmableLightingControl":
                            (device as DimmableLightingControl).TurnOff();
                            break;

                        case "SwitchedLightingControl":
                            (device as SwitchedLightingControl).TurnOff();
                            break;

                        case "SensorsActuators":
                            (device as SensorsActuators).TurnOffOutput(byte.Parse(option));
                            break;

                        case "WindowCoveringControl":
                            (device as WindowCoveringControl).Close();
                            break;

                        case "PoolAndSpaControl":
                            break;

                        case "IrrigationControl":
                            (device as IrrigationControl).TurnOffSprinklerValve(byte.Parse(option));
                            break;
                        }
                    }
                }
                else if (command == Command.CONTROL_BRIGHT)
                {
                    // TODO: raise parameter change event
                    if (device != null && device is DimmableLightingControl)
                    {
                        (device as DimmableLightingControl).BrightenOneStep();
                    }
                }
                else if (command == Command.CONTROL_DIM)
                {
                    // TODO: raise parameter change event
                    if (device != null && device is DimmableLightingControl)
                    {
                        (device as DimmableLightingControl).DimOneStep();
                    }
                }
                else if (command == Command.CONTROL_LEVEL)
                {
                    double adjustedLevel = (double.Parse(option) / 100D);
                    raisePropertyChanged = true;
                    raiseParameter       = adjustedLevel.ToString(CultureInfo.InvariantCulture);
                    //
                    byte level = (byte)((double.Parse(option) / 100D) * 255);
                    if (device != null)
                    {
                        switch (device.GetType().Name)
                        {
                        case "DimmableLightingControl":
                            (device as DimmableLightingControl).TurnOn(level);
                            break;

                        case "WindowCoveringControl":
                            (device as WindowCoveringControl).MoveToPosition(level);
                            break;
                        }
                    }
                }
                else if (command == Command.CONTROL_TOGGLE)
                {
                }
                else if (command == Command.CONTROL_ALLLIGHTSON)
                {
                }
                else if (command == Command.CONTROL_ALLLIGHTSOFF)
                {
                }
            }
            else
            {
                // It is not a dotted hex addres, so fallback to X10 device control
                var x10plm = insteonPlm.Network.X10;

                // Parse house/unit
                string houseCode = nodeId.Substring(0, 1);
                byte   unitCode  = 0x00;
                if (nodeId.Length > 1)
                {
                    unitCode = byte.Parse(nodeId.Substring(1));
                }

                // Modules control
                if (command == Command.PARAMETER_STATUS)
                {
                    x10plm
                    .House(houseCode.ToString())
                    .Unit(unitCode)
                    .Command(X10Command.StatusRequest);
                }
                else if (command == Command.CONTROL_ON)
                {
                    raisePropertyChanged = true;
                    raiseParameter       = "1";
                    //
                    x10plm
                    .House(houseCode)
                    .Unit(unitCode)
                    .Command(X10Command.On);
                }
                else if (command == Command.CONTROL_OFF)
                {
                    raisePropertyChanged = true;
                    raiseParameter       = "0";
                    //
                    x10plm
                    .House(houseCode)
                    .Unit(unitCode)
                    .Command(X10Command.Off);
                }
                else if (command == Command.CONTROL_BRIGHT)
                {
                    // TODO: raise parameter change event
                    int amount = int.Parse(option);
                    // TODO: how to specify bright amount parameter???
                    x10plm
                    .House(houseCode)
                    .Unit(unitCode)
                    .Command(X10Command.Bright);
                }
                else if (command == Command.CONTROL_DIM)
                {
                    // TODO: raise parameter change event
                    int amount = int.Parse(option);
                    // TODO: how to specify dim amount parameter???
                    x10plm
                    .House(houseCode)
                    .Unit(unitCode)
                    .Command(X10Command.Dim);
                }
                else if (command == Command.CONTROL_LEVEL)
                {
                    double adjustedLevel = (double.Parse(option) / 100D);
                    raisePropertyChanged = true;
                    raiseParameter       = adjustedLevel.ToString(CultureInfo.InvariantCulture);
                    //

                    /*int dimvalue = int.Parse(option) - (int)(x10lib.ModulesStatus[ nodeId ].Level * 100.0);
                     * if (dimvalue > 0)
                     * {
                     *  x10lib.Bright(houseCode, unitCode, dimvalue);
                     * }
                     * else if (dimvalue < 0)
                     * {
                     *  x10lib.Dim(houseCode, unitCode, -dimvalue);
                     * }*/
                }
                else if (command == Command.CONTROL_TOGGLE)
                {
                    /*
                     * string huc = XTenLib.Utility.HouseUnitCodeFromEnum(houseCode, unitCode);
                     * if (x10lib.ModulesStatus[ huc ].Level == 0)
                     * {
                     *  x10lib.LightOn(houseCode, unitCode);
                     * }
                     * else
                     * {
                     *  x10lib.LightOff(houseCode, unitCode);
                     * }
                     */
                }
                else if (command == Command.CONTROL_ALLLIGHTSON)
                {
                    // TODO: ...
                    x10plm
                    .House(houseCode)
                    .Command(X10Command.AllLightsOn);
                }
                else if (command == Command.CONTROL_ALLLIGHTSOFF)
                {
                    // TODO: ...
                    x10plm
                    .House(houseCode)
                    .Command(X10Command.AllLightsOff);
                }
            }
            //
            if (raisePropertyChanged && InterfacePropertyChangedAction != null)
            {
                try
                {
                    //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction()
                    {
                        Domain     = this.Domain,
                        SourceId   = nodeId,
                        SourceType = "Insteon Device",
                        Path       = parameterPath,
                        Value      = raiseParameter
                    });
                }
                catch
                {
                }
            }
            //
            return("");
        }
Пример #32
0
        /// <summary>
        ///
        /// A MIG interface class automatically receives a call to this function
        /// for each request made to the webservice and that is addressed to its
        /// driver namespace (domain). A driver request has the form:
        /// http://<server_addr>/<notimplauthkey>/<interface_domain>/<nodeid>/<command>[<other_slash_separated_parameters>]
        /// eg. http://192.168.1.8/api/HomeAutomation.ExampleDriver/G73/Control.On
        /// (tells ExampleDriver to turn on the module with address G73)
        ///
        /// the parameter "request" of this function will contain only the relevant
        /// part of the whole http request:
        /// <nodeid>/<command>[<other_slash_separated_parameters>]
        /// eg.: "G73/Control.Level/50"
        ///
        /// </summary>
        /// <returns>
        /// optional string reply to request (usually xml encoded reply)
        /// </returns>
        /// <param name='request'>
        /// a formatted string containging a valid request for this domain
        /// eg: "A8/Control.Level/75"
        /// </param>
        /// 
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            request.Response = ""; //default success value
            // this is an example set of commands:
            // for each received command
            // add the needed code to perform
            // the desired action on the <nodeid> device
            switch (request.Command)
            {
                case "Control.On":

                    break;
                case "Control.Off":

                    break;
                case "Control.Level":

                    break;
                case "Control.Bright":

                    break;
                case "Control.Dim":

                    break;
                case "Controll.AllLightsOn":

                    break;
                case "Control.AllUnitsOff":

                    break;
            }
            //
            return request.Response;
        }
Пример #33
0
        public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migcmd)
        {
            //SQLiteCommand dbcmd = _dbconnection.CreateCommand();
            switch (migcmd.command)
            {
            case "Global.CounterTotal":
                migcmd.response = JsonHelper.GetSimpleResponse(_hg.Statistics.GetTotalCounter(migcmd.GetOption(0), 3600).ToString("0.000", System.Globalization.CultureInfo.InvariantCulture));
                break;

            case "Global.TimeRange":
                StatisticsEntry totalrange = _hg.Statistics.GetStartDate();
                migcmd.response = "[{ StartTime : '" + ((totalrange.TimeStart.Ticks - 621355968000000000) / 10000D).ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + "', EndTime : '" + ((totalrange.TimeEnd.Ticks - 621355968000000000) / 10000D).ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + "' }]";
                break;

            case "Database.Reset":
                _hg.Statistics.DatabaseReset();
                break;

            case "Parameter.List":
                var pdomain  = "";
                var paddress = "";
                var pfilter  = migcmd.GetOption(0).Split(':');
                if (pfilter.Length == 2)
                {
                    pdomain  = pfilter[0];
                    paddress = pfilter[1];
                }
                migcmd.response = "[";
                foreach (string sp in _hg.Statistics.GetParametersList(pdomain, paddress))
                {
                    migcmd.response += "	'"+ sp + "',\n";
                }
                migcmd.response  = migcmd.response.TrimEnd(',', '\n');
                migcmd.response += "\n]";
                break;

            case "Parameter.Counter":
                var cdomain  = "";
                var caddress = "";
                var cfilter  = migcmd.GetOption(1).Split(':');
                if (cfilter.Length == 2)
                {
                    cdomain  = cfilter[0];
                    caddress = cfilter[1];
                }
                //
                migcmd.response  = "[";
                migcmd.response += "[ ";
                //
                List <StatisticsEntry> hoursaverage = new List <StatisticsEntry>();
                hoursaverage = _hg.Statistics.GetHourlyCounter(cdomain, caddress, migcmd.GetOption(0), 3600);;
                //
                for (int h = 0; h < 24; h++)
                {
                    StatisticsEntry firstentry = null;
                    if (hoursaverage != null && hoursaverage.Count > 0)
                    {
                        firstentry = hoursaverage.Find(se => se.TimeStart.ToLocalTime().Hour == h);
                    }
                    //
                    if (firstentry != null)
                    {
                        double sum = 0;
                        sum = (double)(hoursaverage.FindAll(se => se.TimeStart.ToLocalTime().Hour == h).Sum(se => se.Value));
                        // date is normalized to the current date, time info is preserved from original data entry
                        DateTime d = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + h.ToString("00") + ":00:00");
                        migcmd.response += "[" + ((d.Ticks - 621355968000000000) / 10000D).ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + "," + sum.ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + "],";
                    }
                    else
                    {
                        DateTime d = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + h.ToString("00") + ":00:00");
                        migcmd.response += "[" + ((d.Ticks - 621355968000000000) / 10000D).ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + ",0.000],";
                    }
                }
                migcmd.response  = migcmd.response.TrimEnd(',');
                migcmd.response += " ]";
                migcmd.response += "]";
                break;

            case "Parameter.StatsHour":
                var domain  = "";
                var address = "";
                var filter  = migcmd.GetOption(1).Split(':');
                if (filter.Length == 2)
                {
                    domain  = filter[0];
                    address = filter[1];
                }
                //
                migcmd.response = "[";
                //
                List <StatisticsEntry>[] hoursaverages = new List <StatisticsEntry> [5];
                hoursaverages[0] = _hg.Statistics.GetHourlyStats(domain, address, migcmd.GetOption(0), "Min");
                hoursaverages[1] = _hg.Statistics.GetHourlyStats(domain, address, migcmd.GetOption(0), "Max");
                hoursaverages[2] = _hg.Statistics.GetHourlyStats(domain, address, migcmd.GetOption(0), "Avg");
                hoursaverages[3] = _hg.Statistics.GetHourlyStats24(domain, address, migcmd.GetOption(0), "Avg");
                if (migcmd.GetOption(0) == Properties.METER_WATTS)
                {
                    hoursaverages[4] = _hg.Statistics.GetTodayDetail(domain, address, migcmd.GetOption(0), "Sum");
                }
                else
                {
                    hoursaverages[4] = _hg.Statistics.GetTodayDetail(domain, address, migcmd.GetOption(0), "Avg");
                }
                //
                for (int x = 0; x < 4; x++)
                {
                    migcmd.response += "[ ";
                    for (int h = 0; h < 24; h++)
                    {
                        StatisticsEntry firstentry = null;
                        if (hoursaverages[x] != null && hoursaverages[x].Count > 0)
                        {
                            if (migcmd.GetOption(0) == Properties.METER_WATTS)
                            {
                                firstentry = hoursaverages[x].Find(se => se.TimeStart.ToLocalTime().Hour == h && se.Value > 0);
                            }
                            else
                            {
                                firstentry = hoursaverages[x].Find(se => se.TimeStart.ToLocalTime().Hour == h);
                            }
                        }
                        //
                        if (firstentry != null)
                        {
                            double sum = 0;
                            switch (x)
                            {
                            case 0:
                                if (migcmd.GetOption(0) == Properties.METER_WATTS)
                                {
                                    sum = (double)(hoursaverages[x].FindAll(se => se.TimeStart.ToLocalTime().Hour == h && se.Value > 0).Min(se => se.Value));
                                }
                                else
                                {
                                    sum = (double)(hoursaverages[x].FindAll(se => se.TimeStart.ToLocalTime().Hour == h).Min(se => se.Value));
                                }
                                break;

                            case 1:
                                sum = (double)(hoursaverages[x].FindAll(se => se.TimeStart.ToLocalTime().Hour == h).Max(se => se.Value));
                                break;

                            case 2:
                                if (migcmd.GetOption(0) == Properties.METER_WATTS)
                                {
                                    sum = (double)(hoursaverages[x].FindAll(se => se.TimeStart.ToLocalTime().Hour == h && se.Value > 0).Average(se => se.Value));
                                }
                                else
                                {
                                    sum = (double)(hoursaverages[x].FindAll(se => se.TimeStart.ToLocalTime().Hour == h).Average(se => se.Value));
                                }
                                break;

                            case 3:
                                if (migcmd.GetOption(0) == Properties.METER_WATTS)
                                {
                                    sum = (double)(hoursaverages[x].FindAll(se => se.TimeStart.ToLocalTime().Hour == h && se.Value > 0).Average(se => se.Value));
                                }
                                else
                                {
                                    sum = (double)(hoursaverages[x].FindAll(se => se.TimeStart.ToLocalTime().Hour == h).Average(se => se.Value));
                                }
                                break;
                            }
                            // date is normalized to the current date, time info is preserved from original data entry
                            DateTime d = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + h.ToString("00") + ":00:00");
                            migcmd.response += "[" + ((d.Ticks - 621355968000000000) / 10000D).ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + "," + sum.ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + "],";
                        }
                        else
                        {
                            DateTime d = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + h.ToString("00") + ":00:00");
                            migcmd.response += "[" + ((d.Ticks - 621355968000000000) / 10000D).ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + ",0.000],";
                        }
                    }
                    migcmd.response  = migcmd.response.TrimEnd(',');
                    migcmd.response += " ],";
                }
                //
                migcmd.response += "[ ";
                foreach (StatisticsEntry se in hoursaverages[4])
                {
                    DateTime d = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + se.TimeStart.ToLocalTime().ToString("HH:mm:ss.ffffff"));
                    migcmd.response += "[" + ((d.Ticks - 621355968000000000) / 10000D).ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + "," + se.Value.ToString("0.000", System.Globalization.CultureInfo.InvariantCulture) + "],";
                }
                migcmd.response  = migcmd.response.TrimEnd(',');
                migcmd.response += " ]";
                //
                migcmd.response += "]";
                break;
            }
        }
Пример #34
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string response = "[{ ResponseValue : 'OK' }]";

            string nodeId  = request.NodeId;
            var    command = (Command)request.Command;
            string option  = request.GetOption(0);

            // Parse house/unit
            var houseCode = XTenLib.Utility.HouseCodeFromString(nodeId);
            var unitCode  = XTenLib.Utility.UnitCodeFromString(nodeId);

            // Modules control
            if (command == Command.PARAMETER_STATUS)
            {
                x10lib.StatusRequest(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_ON)
            {
                x10lib.UnitOn(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_OFF)
            {
                x10lib.UnitOff(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_BRIGHT)
            {
                x10lib.Bright(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_DIM)
            {
                x10lib.Dim(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_LEVEL_ADJUST)
            {
                int dimvalue = int.Parse(option);
                //x10lib.Modules[nodeId].Level = ((double)dimvalue/100D);
                InterfacePropertyChangedAction(new InterfacePropertyChangedAction()
                {
                    Domain     = this.Domain,
                    SourceId   = nodeId,
                    SourceType = "X10 Module",
                    Path       = "Status.Level",
                    Value      = x10lib.Modules[nodeId].Level
                });
                throw(new NotImplementedException("X10 CONTROL_LEVEL_ADJUST Not Implemented"));
            }
            else if (command == Command.CONTROL_LEVEL)
            {
                int dimvalue = int.Parse(option) - (int)(x10lib.Modules[nodeId].Level * 100.0);
                if (dimvalue > 0)
                {
                    x10lib.Bright(houseCode, unitCode, dimvalue);
                }
                else if (dimvalue < 0)
                {
                    x10lib.Dim(houseCode, unitCode, -dimvalue);
                }
            }
            else if (command == Command.CONTROL_TOGGLE)
            {
                string huc = XTenLib.Utility.HouseUnitCodeFromEnum(houseCode, unitCode);
                if (x10lib.Modules[huc].Level == 0)
                {
                    x10lib.UnitOn(houseCode, unitCode);
                }
                else
                {
                    x10lib.UnitOff(houseCode, unitCode);
                }
            }
            else if (command == Command.CONTROL_ALLLIGHTSON)
            {
                x10lib.AllLightsOn(houseCode);
            }
            else if (command == Command.CONTROL_ALLLIGHTSOFF)
            {
                x10lib.AllUnitsOff(houseCode);
            }
            //
            return(response);
        }
Пример #35
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     return "";
 }
Пример #36
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            if (DEBUG_API) Console.WriteLine("Weeco4mGPIO Command : " + request.Command);

            var command = (Command)request.Command;
            string returnvalue = "";
            //
            if (command == Command.CONTROL_ON)
            {
                if (DEBUG_API) Console.WriteLine("Weeco4mGPIO Command.CONTROL_ON ");

                this.OutputPin(request.NodeId, "1");
                if (IsRegister(request.NodeId)) RegPins[ request.NodeId ] = "1";
                else GpioPins[ request.NodeId ] = true;
                if (InterfacePropertyChangedAction != null)
                {
                    try
                    {
                        InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                            Domain = this.Domain,
                            SourceId = request.NodeId,
                            SourceType = "Weeco-4M GPIO",
                            Path = ModuleParameters.MODPAR_STATUS_LEVEL,
                            Value = 1
                        });
                    }
                    catch
                    {
                    }
                }
            }
            else if (command == Command.CONTROL_OFF)
            {
                if (DEBUG_API) Console.WriteLine("Weeco4mGPIO Command.CONTROL_OFF ");

                this.OutputPin(request.NodeId, "0");
                if (IsRegister(request.NodeId)) RegPins[ request.NodeId ] = "0";
                else GpioPins[ request.NodeId ] = false;

                if (InterfacePropertyChangedAction != null)
                {
                    try
                    {
                        InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                            Domain = this.Domain,
                            SourceId = request.NodeId,
                            SourceType = "Weeco-4M GPIO",
                            Path = ModuleParameters.MODPAR_STATUS_LEVEL,
                            Value = 0
                        });
                    }
                    catch
                    {
                    }
                }
            }
            else if (command == Command.PARAMETER_STATUS)
            {
                if (DEBUG_API) Console.WriteLine("Weeco4mGPIO Command.PARAMETER_STATUS ");
                if (!IsRegister(request.NodeId)) GpioPins[ request.NodeId ] = this.InputPin(request.NodeId).CompareTo("0") == 0 ? false : true;
                else RegPins[ request.NodeId ] = this.InputPin(request.NodeId);
            }
            else if (command == Command.CONTROL_RESET)
            {
                this.CleanUpAllPins();
                foreach (KeyValuePair<string, bool> kv in GpioPins)
                {
                    GpioPins[ kv.Key ] = false;
                }
                foreach (KeyValuePair<string, string> kv in RegPins)
                {
                    RegPins[ kv.Key ] = "0";
                }
            }

            return returnvalue;
        }
Пример #37
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string returnvalue      = "";
            bool   raisepropchanged = false;
            string parampath        = "Status.Level";
            string raiseparam       = "";
            //
            string  nodeid  = request.nodeid;
            Command command = (Command)request.command;

            ////----------------------
            try
            {
                if (command == Command.CONTROLLER_DISCOVERY)
                {
                    _controller.Discovery();
                }


                //--------------////---------------------- DEPRECATE THESE  ----------------------------
                //else if (command == Command.CONTROLLER_AUTOREPORTSET)
                //{
                //    _controller.AutoReportSet((byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                //}
                //else
                if (command == Command.BASIC_REPORT || command.ToString() == "Meter.Get") // TODO .. FIX: this is not basic report, it's a meter get
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.RequestMeterReport();
                }
                else if (command == Command.MULTILEVEL_REPORT) // TODO this one call for having SwitchMultiLevel and SensorMultiLevel reports
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.RequestMultiLevelReport();
                }
                //--------------////--------------------------------------------------------------------


                else if (command == Command.CONTROLLER_NODEADD)
                {
                    _lastnodeadded = 0;
                    byte addcid = _controller.BeginNodeAdd();
                    for (int i = 0; i < 20; i++)
                    {
                        if (_lastnodeadded > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    _controller.StopNodeAdd();
                    //
                    returnvalue = _lastnodeadded.ToString();
                }
                else if (command == Command.CONTROLLER_NODEREMOVE)
                {
                    _lastnoderemoved = 0;
                    byte remcid = _controller.BeginNodeRemove();
                    for (int i = 0; i < 20; i++)
                    {
                        if (_lastnoderemoved > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    _controller.StopNodeRemove();
                    //
                    returnvalue = _lastnoderemoved.ToString();
                }
                ////----------------------
                else if (command == Command.BASIC_SET)
                {
                    raisepropchanged = true;
                    double raiseval = double.Parse(request.GetOption(0)) / 100;
                    if (raiseval > 1)
                    {
                        raiseval = 1;
                    }
                    raiseparam = raiseval.ToString(System.Globalization.CultureInfo.InvariantCulture);
                    //
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.Basic_Set((byte)int.Parse(request.GetOption(0)));
                }
                else if (command == Command.BASIC_GET)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.Basic_Get();
                }
                ////-----------------------
                else if (command == Command.MULTIINSTANCE_GETCOUNT)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    //
                    switch (request.GetOption(0))
                    {
                    case "Switch.Binary":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SWITCH_BINARY);
                        break;

                    case "Switch.MultiLevel":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SWITCH_MULTILEVEL);
                        break;

                    case "Sensor.Binary":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SENSOR_BINARY);
                        break;

                    case "Sensor.MultiLevel":
                        node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SENSOR_MULTILEVEL);
                        break;
                    }
                }
                else if (command == Command.MULTIINSTANCE_GET)
                {
                    ZWaveNode node     = _controller.GetDevice((byte)int.Parse(nodeid));
                    byte      instance = (byte)int.Parse(request.GetOption(1)); // parameter index
                    //
                    switch (request.GetOption(0))
                    {
                    case "Switch.Binary":
                        node.MultiInstance_SwitchBinaryGet(instance);
                        break;

                    case "Switch.MultiLevel":
                        node.MultiInstance_SwitchMultiLevelGet(instance);
                        break;

                    case "Sensor.Binary":
                        node.MultiInstance_SensorBinaryGet(instance);
                        break;

                    case "Sensor.MultiLevel":
                        node.MultiInstance_SensorMultiLevelGet(instance);
                        break;
                    }
                }
                else if (command == Command.MULTIINSTANCE_SET)
                {
                    ZWaveNode node     = _controller.GetDevice((byte)int.Parse(nodeid));
                    byte      instance = (byte)int.Parse(request.GetOption(1)); // parameter index
                    int       value    = int.Parse(request.GetOption(2));
                    //
                    //raisepropchanged = true;
                    //parampath += "." + instance; // Status.Level.<instance>
                    //
                    switch (request.GetOption(0))
                    {
                    case "Switch.Binary":
                        node.MultiInstance_SwitchBinarySet(instance, value);
                        //raiseparam = (double.Parse(request.GetOption(2)) / 255).ToString();
                        break;

                    case "Switch.MultiLevel":
                        node.MultiInstance_SwitchMultiLevelSet(instance, value);
                        //raiseparam = (double.Parse(request.GetOption(2)) / 100).ToString(); // TODO: should it be 99 ?
                        break;
                    }
                }
                else if (command == Command.NODEINFO_GET)
                {
                    ZWaveController.GetNodeInformationFrame((byte)int.Parse(nodeid));
                }
                ////-----------------------
                else if (command == Command.BATTERY_GET)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.Battery_Get();
                }
                ////-----------------------
                else if (command == Command.ASSOCIATION_SET)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.Association_Set((byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                }
                else if (command == Command.ASSOCIATION_GET)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.Association_Get((byte)int.Parse(request.GetOption(0))); // groupid
                }
                else if (command == Command.ASSOCIATION_REMOVE)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.Association_Remove((byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1))); // groupid
                }
                ////-----------------------
                else if (command == Command.MANUFACTURERSPECIFIC_GET)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.ManufacturerSpecific_Get();
                }
                ////------------------
                else if (command == Command.CONFIG_PARAMETERSET)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    //byte[] value = new byte[] { (byte)int.Parse(option1) };//BitConverter.GetBytes(Int16.Parse(option1));
                    //Array.Reverse(value);
                    node.ConfigParameterSet((byte)int.Parse(request.GetOption(0)), int.Parse(request.GetOption(1)));
                }
                else if (command == Command.CONFIG_PARAMETERGET)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.ConfigParameterGet((byte)int.Parse(request.GetOption(0)));
                }
                ////------------------
                else if (command == Command.WAKEUP_GET)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.WakeUpGetInterval();
                }
                else if (command == Command.WAKEUP_SET)
                {
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    node.WakeUpSetInterval(uint.Parse(request.GetOption(0)));
                }
                ////------------------
                else if (command == Command.CONTROL_ON)
                {
                    raisepropchanged = true;
                    raiseparam       = "1";
                    //
                    // Basic.Set 0xFF
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).On();
                }
                else if (command == Command.CONTROL_OFF)
                {
                    raisepropchanged = true;
                    raiseparam       = "0";
                    //
                    // Basic.Set 0x00
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).Off();
                }
                else if (command == Command.CONTROL_LEVEL)
                {
                    raisepropchanged = true;
                    raiseparam       = (double.Parse(request.GetOption(0)) / 100).ToString();
                    //
                    // Basic.Set <level>
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Dimmer)node.DeviceHandler).Level = int.Parse(request.GetOption(0));
                }
                else if (command == Command.CONTROL_TOGGLE)
                {
                    raisepropchanged = true;
                    //
                    ZWaveNode node = _controller.GetDevice((byte)int.Parse(nodeid));
                    if (((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).Level == 0)
                    {
                        raiseparam = "1";
                        // Basic.Set 0xFF
                        ((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).On();
                    }
                    else
                    {
                        raiseparam = "0";
                        // Basic.Set 0x00
                        ((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).Off();
                    }
                }
            }
            catch
            {
                if (raiseparam != "")
                {
                    raisepropchanged = true;
                }
            }
            //
            if (raisepropchanged && InterfacePropertyChangedAction != null)
            {
                try
                {
                    //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction()
                    {
                        Domain = this.Domain, SourceId = nodeid, SourceType = "ZWave Node", Path = parampath, Value = raiseparam
                    });
                }
                catch
                {
                }
            }
            //
            return(returnvalue);
        }
Пример #38
0
        public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migCommand)
        {
            switch (migCommand.Command)
            {
            case "Interfaces.List":
                migCommand.Response = "[ ";
                foreach (var kv in homegenie.Interfaces)
                {
                    var migInterface = kv.Value;
                    var ifaceConfig  = homegenie.SystemConfiguration.MIGService.GetInterface(migInterface.Domain);
                    if (ifaceConfig == null || !ifaceConfig.IsEnabled)
                    {
                        continue;
                    }
                    migCommand.Response += "{ \"Domain\" : \"" + migInterface.Domain + "\", \"IsConnected\" : \"" + migInterface.IsConnected + "\" },";
                }
                if (homegenie.UpdateChecker != null && homegenie.UpdateChecker.IsUpdateAvailable)
                {
                    migCommand.Response += "{ \"Domain\" : \"HomeGenie.UpdateChecker\", \"IsConnected\" : \"True\" }";
                    migCommand.Response += " ]";
                }
                else
                {
                    migCommand.Response = migCommand.Response.Substring(0, migCommand.Response.Length - 1) + " ]";
                }
                //
                break;

            //TODO: should this be moved somewhere to MIG?
            case "Interfaces.Configure":
                switch (migCommand.GetOption(0))
                {
                case "Hardware.SerialPorts":
                    if (Environment.OSVersion.Platform == PlatformID.Unix)
                    {
                        var serialPorts = System.IO.Ports.SerialPort.GetPortNames();
                        var portList    = new List <string>();
                        for (int p = serialPorts.Length - 1; p >= 0; p--)
                        {
                            if (serialPorts[p].Contains("/ttyS") || serialPorts[p].Contains("/ttyUSB"))
                            {
                                portList.Add(serialPorts[p]);
                            }
                        }
                        if (Raspberry.Board.Current.IsRaspberryPi && !portList.Contains("/dev/ttyAMA0"))
                        {
                            portList.Add("/dev/ttyAMA0");
                        }
                        migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portList));
                    }
                    else
                    {
                        var portNames = System.IO.Ports.SerialPort.GetPortNames();
                        migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portNames));
                    }
                    break;
                }
                break;

            case "System.Configure":
                if (migCommand.GetOption(0) == "Service.Restart")
                {
                    Program.Quit(true);
                    migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                }
                else if (migCommand.GetOption(0) == "UpdateManager.UpdatesList")
                {
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.UpdateChecker.RemoteUpdates);
                }
                else if (migCommand.GetOption(0) == "UpdateManager.Check")
                {
                    homegenie.UpdateChecker.Check();
                    migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                }
                else if (migCommand.GetOption(0) == "UpdateManager.DownloadUpdate")
                {
                    var  resultMessage = "ERROR";
                    bool success       = homegenie.UpdateChecker.DownloadUpdateFiles();
                    if (success)
                    {
                        if (homegenie.UpdateChecker.IsRestartRequired)
                        {
                            resultMessage = "RESTART";
                        }
                        else
                        {
                            resultMessage = "OK";
                        }
                    }
                    migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage);
                }
                else if (migCommand.GetOption(0) == "UpdateManager.InstallUpdate") //UpdateManager.InstallProgramsCommit")
                {
                    string resultMessage = "OK";
                    if (!homegenie.UpdateChecker.InstallFiles())
                    {
                        resultMessage = "ERROR";
                    }
                    else
                    {
                        if (homegenie.UpdateChecker.IsRestartRequired)
                        {
                            resultMessage = "RESTART";
                            Utility.RunAsyncTask(() =>
                            {
                                Thread.Sleep(2000);
                                Program.Quit(true);
                            });
                        }
                        else
                        {
                            homegenie.LoadConfiguration();
                            homegenie.MigService.ClearWebCache();
                            homegenie.UpdateChecker.Check();
                        }
                    }
                    migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage);
                }
                else if (migCommand.GetOption(0) == "HttpService.SetWebCacheEnabled")
                {
                    if (migCommand.GetOption(1) == "1")
                    {
                        homegenie.MigService.IsWebCacheEnabled = true;
                        homegenie.SystemConfiguration.MIGService.EnableWebCache = "true";
                    }
                    else
                    {
                        homegenie.MigService.IsWebCacheEnabled = false;
                        homegenie.SystemConfiguration.MIGService.EnableWebCache = "false";
                    }
                    homegenie.SystemConfiguration.Update();
                    migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                }
                else if (migCommand.GetOption(0) == "HttpService.GetWebCacheEnabled")
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.MigService.IsWebCacheEnabled ? "1" : "0");
                }
                else if (migCommand.GetOption(0) == "HttpService.GetPort")
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.SystemConfiguration.HomeGenie.ServicePort.ToString());
                }
                else if (migCommand.GetOption(0) == "HttpService.SetPort")
                {
                    try
                    {
                        homegenie.SystemConfiguration.HomeGenie.ServicePort = int.Parse(migCommand.GetOption(1));
                        homegenie.SystemConfiguration.Update();
                    }
                    catch
                    {
                    }
                }
                else if (migCommand.GetOption(0) == "SystemLogging.DownloadCsv")
                {
                    string csvlog  = "";
                    string logpath = Path.Combine("log", "homegenie.log");
                    if (migCommand.GetOption(1) == "1")
                    {
                        logpath = Path.Combine("log", "homegenie.log.bak");
                    }
                    if (File.Exists(logpath))
                    {
                        using (var fs = new FileStream(logpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            using (var sr = new StreamReader(fs, Encoding.Default)) {
                                csvlog = sr.ReadToEnd();
                            }
                    }
                    (request.Context as HttpListenerContext).Response.AddHeader(
                        "Content-Disposition",
                        "attachment;filename=homegenie_log_" + migCommand.GetOption(1) + ".csv"
                        );
                    migCommand.Response = csvlog;
                }
                else if (migCommand.GetOption(0) == "SystemLogging.Enable")
                {
                    SystemLogger.Instance.OpenLog();
                    homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "true";
                    homegenie.SystemConfiguration.Update();
                }
                else if (migCommand.GetOption(0) == "SystemLogging.Disable")
                {
                    SystemLogger.Instance.CloseLog();
                    homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "false";
                    homegenie.SystemConfiguration.Update();
                }
                else if (migCommand.GetOption(0) == "SystemLogging.IsEnabled")
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.EnableLogFile.ToLower().Equals("true") ? "1" : "0"));
                }
                else if (migCommand.GetOption(0) == "Security.SetPassword")
                {
                    // password only for now, with fixed user login 'admin'
                    string pass = migCommand.GetOption(1) == "" ? "" : MIG.Utility.Encryption.SHA1.GenerateHashString(migCommand.GetOption(1));
                    homegenie.MigService.SetWebServicePassword(pass);
                    homegenie.SystemConfiguration.HomeGenie.UserPassword = pass;
                    // regenerate encrypted files
                    homegenie.SystemConfiguration.Update();
                    homegenie.UpdateModulesDatabase();
                }
                else if (migCommand.GetOption(0) == "Security.ClearPassword")
                {
                    homegenie.MigService.SetWebServicePassword("");
                    homegenie.SystemConfiguration.HomeGenie.UserPassword = "";
                    // regenerate encrypted files
                    homegenie.SystemConfiguration.Update();
                    homegenie.UpdateModulesDatabase();
                }
                else if (migCommand.GetOption(0) == "Security.HasPassword")
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.UserPassword != "" ? "1" : "0"));
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationRestore")
                {
                    // file uploaded by user
                    string archivename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                      "tmp",
                                                      "homegenie_restore_config.zip");
                    if (!Directory.Exists("tmp"))
                    {
                        Directory.CreateDirectory("tmp");
                    }
                    try
                    {
                        var downloadedMessageInfo = new DirectoryInfo("tmp");
                        foreach (var file in downloadedMessageInfo.GetFiles())
                        {
                            file.Delete();
                        }
                        foreach (DirectoryInfo directory in downloadedMessageInfo.GetDirectories())
                        {
                            directory.Delete(true);
                        }
                    }
                    catch
                    {
                    }
                    //
                    try
                    {
                        var    encoding = (request.Context as HttpListenerContext).Request.ContentEncoding;
                        string boundary = MIG.Gateways.WebServiceUtility.GetBoundary((request.Context as HttpListenerContext).Request.ContentType);
                        MIG.Gateways.WebServiceUtility.SaveFile(encoding,
                                                                boundary,
                                                                request.InputStream,
                                                                archivename);
                        homegenie.UnarchiveConfiguration(archivename,
                                                         Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                                      "tmp"));
                        File.Delete(archivename);
                    }
                    catch
                    {
                    }
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS1")
                {
                    var serializer = new XmlSerializer(typeof(List <ProgramBlock>));
                    var reader     = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                                   "tmp",
                                                                   "programs.xml"));
                    var newProgramsData = (List <ProgramBlock>)serializer.Deserialize(reader);
                    reader.Close();
                    var newProgramList = new List <ProgramBlock>();
                    foreach (ProgramBlock program in newProgramsData)
                    {
                        if (program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START)
                        {
                            ProgramBlock p = new ProgramBlock();
                            p.Address     = program.Address;
                            p.Name        = program.Name;
                            p.Description = program.Description;
                            newProgramList.Add(p);
                        }
                    }
                    newProgramList.Sort(delegate(ProgramBlock p1, ProgramBlock p2)
                    {
                        string c1 = p1.Address.ToString();
                        string c2 = p2.Address.ToString();
                        return(c1.CompareTo(c2));
                    });
                    migCommand.Response = JsonConvert.SerializeObject(newProgramList);
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS2")
                {
                    string selectedPrograms = migCommand.GetOption(1);
                    var    serializer       = new XmlSerializer(typeof(List <ProgramBlock>));
                    var    reader           = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                                            "tmp",
                                                                            "programs.xml"));
                    var newProgramsData = (List <ProgramBlock>)serializer.Deserialize(reader);
                    reader.Close();
                    foreach (var program in newProgramsData)
                    {
                        var currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == program.Address);
                        // Only restore user space programs
                        if (selectedPrograms.Contains("," + program.Address.ToString() + ",") && program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START)
                        {
                            if (currentProgram == null)
                            {
                                var newPid = ((currentProgram != null && currentProgram.Address == program.Address) ? homegenie.ProgramEngine.GeneratePid() : program.Address);
                                try
                                {
                                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                           "tmp",
                                                           "programs",
                                                           program.Address + ".dll"),
                                              Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                           "programs",
                                                           newPid + ".dll"),
                                              true);
                                }
                                catch
                                {
                                }
                                program.Address = newPid;
                                homegenie.ProgramEngine.ProgramAdd(program);
                            }
                            else if (currentProgram != null)
                            {
                                homegenie.ProgramEngine.ProgramRemove(currentProgram);
                                try
                                {
                                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                           "tmp",
                                                           "programs",
                                                           program.Address + ".dll"),
                                              Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                           "programs",
                                                           program.Address + ".dll"),
                                              true);
                                }
                                catch
                                {
                                }
                                homegenie.ProgramEngine.ProgramAdd(program);
                            }
                        }
                        else if (currentProgram != null && program.Address < ProgramEngine.USER_SPACE_PROGRAMS_START)
                        {
                            // Only restore Enabled/Disabled status of system programs
                            currentProgram.IsEnabled = program.IsEnabled;
                        }
                    }
                    //
                    homegenie.UpdateProgramsDatabase();
                    //
                    serializer = new XmlSerializer(typeof(List <Group>));
                    reader     = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                               "tmp",
                                                               "automationgroups.xml"));
                    var automationGroups = (List <Group>)serializer.Deserialize(reader);
                    reader.Close();
                    //
                    foreach (var automationGroup in automationGroups)
                    {
                        if (homegenie.AutomationGroups.Find(g => g.Name == automationGroup.Name) == null)
                        {
                            homegenie.AutomationGroups.Add(automationGroup);
                        }
                    }
                    //
                    homegenie.UpdateGroupsDatabase("Automation");
                    //
                    //File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "automationgroups.xml"), "./automationgroups.xml", true);
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "groups.xml"),
                              Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                           "groups.xml"),
                              true);
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "lircconfig.xml"),
                              Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                           "lircconfig.xml"),
                              true);
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "modules.xml"),
                              Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                           "modules.xml"),
                              true);
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "systemconfig.xml"),
                              Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                           "systemconfig.xml"),
                              true);
                    //
                    homegenie.LoadConfiguration();
                    //
                    // regenerate encrypted files
                    homegenie.UpdateModulesDatabase();
                    homegenie.SystemConfiguration.Update();
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationReset")
                {
                    homegenie.RestoreFactorySettings();
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationBackup")
                {
                    homegenie.BackupCurrentSettings();
                    (request.Context as HttpListenerContext).Response.Redirect("/hg/html/homegenie_backup_config.zip");
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationLoad")
                {
                    homegenie.LoadConfiguration();
                }
                break;

            case "Modules.Get":
                try
                {
                    var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1));
                    migCommand.Response = Utility.Module2Json(module, false);
                }
                catch (Exception ex)
                {
                    migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace;
                }
                break;

            case "Modules.List":
                try
                {
                    homegenie.modules_Sort();
                    migCommand.Response = homegenie.GetJsonSerializedModules(migCommand.GetOption(0).ToLower() == "short");
                }
                catch (Exception ex)
                {
                    migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace;
                }
                break;

            case "Modules.RoutingReset":
                try
                {
                    for (int m = 0; m < homegenie.Modules.Count; m++)
                    {
                        homegenie.Modules[m].RoutingNode = "";
                    }
                    migCommand.Response = "OK";
                }
                catch (Exception ex)
                {
                    migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace;
                }
                break;

            case "Modules.Save":
                string body       = new StreamReader(request.InputStream).ReadToEnd();
                var    newModules = JsonConvert.DeserializeObject(body) as JArray;
                for (int i = 0; i < newModules.Count; i++)
                {
                    try
                    {
                        var module = homegenie.Modules.Find(m => m.Address == newModules[i]["Address"].ToString() && m.Domain == newModules[i]["Domain"].ToString());
                        module.Name = newModules[i]["Name"].ToString();
                        //
                        try
                        {
                            module.DeviceType = (MIG.ModuleTypes)Enum.Parse(typeof(MIG.ModuleTypes),
                                                                            newModules[i]["DeviceType"].ToString(),
                                                                            true);
                        }
                        catch
                        {
                            // TODO: check what's wrong here...
                        }
                        //
                        var moduleProperties = newModules[i]["Properties"] as JArray;
                        for (int p = 0; p < moduleProperties.Count; p++)
                        {
                            string          propertyName  = moduleProperties[p]["Name"].ToString();
                            string          propertyValue = moduleProperties[p]["Value"].ToString();
                            ModuleParameter parameter     = null;
                            parameter = module.Properties.Find(delegate(ModuleParameter mp)
                            {
                                return(mp.Name == propertyName);
                            });
                            //
                            if (propertyName == ModuleParameters.MODPAR_VIRTUALMETER_WATTS)
                            {
                                try
                                {
                                    propertyValue = double.Parse(propertyValue.Replace(",", "."),
                                                                 System.Globalization.CultureInfo.InvariantCulture).ToString();
                                }
                                catch
                                {
                                    propertyValue = "0";
                                }
                            }
                            //
                            if (parameter == null)
                            {
                                module.Properties.Add(new ModuleParameter()
                                {
                                    Name  = propertyName,
                                    Value = propertyValue
                                });
                            }
                            else //if (true)
                            {
                                if (moduleProperties[p]["NeedsUpdate"] != null && moduleProperties[p]["NeedsUpdate"].ToString() == "true")
                                {
                                    parameter.Value = propertyValue;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //TODO: notify exception?
                    }
                }
                homegenie.UpdateModulesDatabase();//write modules
                break;

            case "Modules.Update":
                string streamContent = new StreamReader(request.InputStream).ReadToEnd();
                var    newModule     = JsonConvert.DeserializeObject <Module>(streamContent);
                var    currentModule = homegenie.Modules.Find(p => p.Domain == newModule.Domain && p.Address == newModule.Address);
                //
                if (currentModule == null)
                {
                    homegenie.Modules.Add(newModule);
                }
                else
                {
                    currentModule.Name        = newModule.Name;
                    currentModule.Description = newModule.Description;
                    currentModule.DeviceType  = newModule.DeviceType;
                    //cm.Properties = mod.Properties;

                    foreach (var newParameter in newModule.Properties)
                    {
                        var currentParameter = currentModule.Properties.Find(mp => mp.Name == newParameter.Name);
                        if (currentParameter == null)
                        {
                            currentModule.Properties.Add(newParameter);
                        }
                        else if (newParameter.NeedsUpdate)
                        {
                            currentParameter.Value = newParameter.Value;
                        }
                    }
                    // look for deleted properties
                    var deletedParameters = new List <ModuleParameter>();
                    foreach (var parameter in currentModule.Properties)
                    {
                        var currentParameter = newModule.Properties.Find(mp => mp.Name == parameter.Name);
                        if (currentParameter == null)
                        {
                            deletedParameters.Add(parameter);
                        }
                    }
                    foreach (var parameter in deletedParameters)
                    {
                        currentModule.Properties.Remove(parameter);
                    }
                    deletedParameters.Clear();
                }
                //
                homegenie.UpdateModulesDatabase();
                break;

            case "Modules.Delete":
                var deletedModule = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1));
                if (deletedModule != null)
                {
                    homegenie.Modules.Remove(deletedModule);
                }
                migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                //
                homegenie.UpdateModulesDatabase();
                break;

            case "Groups.ModulesList":
                var theGroup = homegenie.Groups.Find(z => z.Name.ToLower() == migCommand.GetOption(0).Trim().ToLower());
                if (theGroup != null)
                {
                    string jsonmodules = "[";
                    for (int m = 0; m < theGroup.Modules.Count; m++)
                    {
                        var groupModule = homegenie.Modules.Find(mm => mm.Domain == theGroup.Modules[m].Domain && mm.Address == theGroup.Modules[m].Address);
                        if (groupModule != null)
                        {
                            jsonmodules += Utility.Module2Json(groupModule, false) + ",\n";
                        }
                    }
                    jsonmodules         = jsonmodules.TrimEnd(',', '\n');
                    jsonmodules        += "]";
                    migCommand.Response = jsonmodules;
                }
                break;

            case "Groups.List":
                try
                {
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0)));
                }
                catch (Exception ex)
                {
                    migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace;
                }
                break;

            case "Groups.Rename":
                string oldName      = migCommand.GetOption(1);
                string newName      = new StreamReader(request.InputStream).ReadToEnd();
                var    currentGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == oldName);
                var    newGroup     = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == newName);
                // ensure that the new group name is not already defined
                if (newGroup == null && currentGroup != null)
                {
                    currentGroup.Name = newName;
                    homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));
                    //cmd.response = JsonHelper.GetSimpleResponse("OK");
                }
                else
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("New name already in use.");
                }

                /*
                 * try
                 * {
                 *  cmd.response = JsonConvert.SerializeObject(cmd.option.ToLower() == "automation" ? _automationgroups : _controlgroups);
                 * }
                 * catch (Exception ex)
                 * {
                 *  cmd.response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace;
                 * }
                 */
                break;

            case "Groups.Sort":
                using (var reader = new StreamReader(request.InputStream))
                {
                    var      newGroupList     = new List <Group>();
                    string[] newPositionOrder = reader.ReadToEnd().Split(new[] { ';' },
                                                                         StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < newPositionOrder.Length; i++)
                    {
                        newGroupList.Add(homegenie.GetGroups(migCommand.GetOption(0))[int.Parse(newPositionOrder[i])]);
                    }
                    homegenie.GetGroups(migCommand.GetOption(0)).Clear();
                    homegenie.GetGroups(migCommand.GetOption(0)).RemoveAll(g => true);
                    homegenie.GetGroups(migCommand.GetOption(0)).AddRange(newGroupList);
                    homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));
                }
                //
                try
                {
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0)));
                }
                catch (Exception ex)
                {
                    migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace;
                }
                break;

            case "Groups.SortModules":
                using (var reader = new StreamReader(request.InputStream))
                {
                    string groupName = migCommand.GetOption(1);
                    Group  sortGroup = null;
                    try
                    {
                        sortGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == groupName);
                    }
                    catch
                    {
                    }
                    //
                    if (sortGroup != null)
                    {
                        var      newModulesReference = new List <ModuleReference>();
                        string[] newPositionOrder    = reader.ReadToEnd().Split(new[] { ';' },
                                                                                StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < newPositionOrder.Length; i++)
                        {
                            newModulesReference.Add(sortGroup.Modules[int.Parse(newPositionOrder[i])]);
                        }
                        sortGroup.Modules.Clear();
                        sortGroup.Modules = newModulesReference;
                        homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));
                    }
                }

                try
                {
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0)));
                }
                catch (Exception ex)
                {
                    migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace;
                }
                break;

            case "Groups.Add":
                string newGroupName = new StreamReader(request.InputStream).ReadToEnd();
                homegenie.GetGroups(migCommand.GetOption(0)).Add(new Group()
                {
                    Name = newGroupName
                });
                homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups
                break;

            case "Groups.Delete":
                string deletedGroupName = new StreamReader(request.InputStream).ReadToEnd();
                Group  deletedGroup     = null;
                try
                {
                    deletedGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == deletedGroupName);
                }
                catch
                {
                }
                //
                if (deletedGroup != null)
                {
                    homegenie.GetGroups(migCommand.GetOption(0)).Remove(deletedGroup);
                    homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups
                    if (migCommand.GetOption(0).ToLower() == "automation")
                    {
                        var groupPrograms = homegenie.ProgramEngine.Programs.FindAll(p => p.Group.ToLower() == deletedGroup.Name.ToLower());
                        if (groupPrograms != null)
                        {
                            // delete group association from programs
                            foreach (ProgramBlock program in groupPrograms)
                            {
                                program.Group = "";
                            }
                        }
                    }
                }
                break;

            case "Groups.Save":
                string jsonGroups = new StreamReader(request.InputStream).ReadToEnd();
                var    newGroups  = JsonConvert.DeserializeObject <List <Group> >(jsonGroups);
                for (int i = 0; i < newGroups.Count; i++)
                {
                    try
                    {
                        var group = homegenie.Groups.Find(z => z.Name == newGroups[i].Name);
                        group.Modules.Clear();
                        group.Modules = newGroups[i].Modules;
                    }
                    catch
                    {
                    }
                }
                homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups
                break;
            }
        }
Пример #39
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string returnValue = "";
            bool raiseEvent = false;
            string eventParameter = "Status.Level";
            string eventValue = "";

            string nodeId = request.NodeId;
            Commands command;
            Enum.TryParse<Commands>(request.Command.Replace(".", "_"), out command);
            ZWaveNode node = null;

            byte nodeNumber = 0;
            if (byte.TryParse(nodeId, out nodeNumber))
            {
                if (nodeNumber > 0)
                    node = controller.GetNode(nodeNumber);
                lock (eventLock)
                {
                    switch (command)
                    {

                    case Commands.Controller_Discovery:
                        controller.Discovery();
                        break;

                    case Commands.Controller_SoftReset:
                        controller.SoftReset();
                        break;

                    case Commands.Controller_HardReset:
                        controller.HardReset();
                        controller.Discovery();
                        break;

                    case Commands.Controller_NodeNeighborUpdate:
                        controller.RequestNeighborsUpdateOptions(nodeNumber).Wait();
                        controller.RequestNeighborsUpdate(nodeNumber).Wait();
                        controller.GetNeighborsRoutingInfo(nodeNumber).Wait();
                        returnValue = GetResponseValue(EventPath_RoutingInfo);
                        break;

                    case Commands.Controller_NodeAdd:
                        lastAddedNode = 0;
                        controller.BeginNodeAdd();
                        for (int i = 0; i < 20; i++)
                        {
                            if (lastAddedNode > 0)
                            {
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        controller.StopNodeAdd();
                        returnValue = lastAddedNode.ToString();
                        break;

                    case Commands.Controller_NodeRemove:
                        lastRemovedNode = 0;
                        controller.BeginNodeRemove();
                        for (int i = 0; i < 20; i++)
                        {
                            if (lastRemovedNode > 0)
                            {
                                break;
                            }
                            Thread.Sleep(500);
                        }
                        controller.StopNodeRemove();
                        returnValue = lastRemovedNode.ToString();
                        break;

                    case Commands.Basic_Set:
                        {
                            raiseEvent = true;
                            var level = int.Parse(request.GetOption(0));
                            eventValue = level.ToString(CultureInfo.InvariantCulture);
                            Basic.Set(node, (byte)level);
                        }
                        break;

                    case Commands.Basic_Get:
                        Basic.Get(node);
                        returnValue = GetResponseValue(EventPath_Basic);
                        break;

                    case Commands.MultiInstance_GetCount:
                        switch (request.GetOption(0))
                        {
                        case "Switch.Binary":
                            MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SwitchBinary);
                            break;
                        case "Switch.MultiLevel":
                            MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SwitchMultilevel);
                            break;
                        case "Sensor.Binary":
                            MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SensorBinary);
                            break;
                        case "Sensor.MultiLevel":
                            MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SensorMultilevel);
                            break;
                        }
                        returnValue = GetResponseValue(EventPath_MultiInstance + "." + request.GetOption(0) + ".Count");
                        break;

                    case Commands.MultiInstance_Get:
                        {
                            byte instance = (byte)int.Parse(request.GetOption(1));
                            switch (request.GetOption(0))
                            {
                            case "Switch.Binary":
                                MultiInstance.SwitchBinaryGet(node, instance);
                                break;
                            case "Switch.MultiLevel":
                                MultiInstance.SwitchMultiLevelGet(node, instance);
                                break;
                            case "Sensor.Binary":
                                MultiInstance.SensorBinaryGet(node, instance);
                                break;
                            case "Sensor.MultiLevel":
                                MultiInstance.SensorMultiLevelGet(node, instance);
                                break;
                            }
                            returnValue = GetResponseValue(EventPath_MultiInstance + "." + request.GetOption(0) + "." + instance);
                        }
                        break;

                    case Commands.MultiInstance_Set:
                        {
                            byte instance = (byte)int.Parse(request.GetOption(1));
                            int value = int.Parse(request.GetOption(2));
                            //
                            //raisepropchanged = true;
                            //parampath += "." + instance; // Status.Level.<instance>
                            //
                            switch (request.GetOption(0))
                            {
                            case "Switch.Binary":
                                MultiInstance.SwitchBinarySet(node, instance, value);
                            //raiseparam = (double.Parse(request.GetOption(2)) / 255).ToString();
                                break;
                            case "Switch.MultiLevel":
                                MultiInstance.SwitchMultiLevelSet(node, instance, value);
                            //raiseparam = (double.Parse(request.GetOption(2)) / 100).ToString(); // TODO: should it be 99 ?
                                break;
                            }
                        }
                        break;

                    case Commands.SensorBinary_Get:
                        SensorBinary.Get(node);
                        break;

                    case Commands.SensorMultiLevel_Get:
                        SensorMultilevel.Get(node);
                        break;

                    case Commands.Meter_Get:
                    // see ZWaveLib Sensor.cs for EnergyMeterScale options
                        int scaleType = 0;
                        int.TryParse(request.GetOption(0), out scaleType);
                        Meter.Get(node, (byte)(scaleType << 0x03));
                        break;

                    case Commands.Meter_SupportedGet:
                        Meter.GetSupported(node);
                        break;

                    case Commands.Meter_Reset:
                        Meter.Reset(node);
                        break;

                    case Commands.NodeInfo_Get:
                        controller.GetNodeInformationFrame(nodeNumber);
                        break;

                    case Commands.Battery_Get:
                        Battery.Get(node);
                        returnValue = GetResponseValue(EventPath_Battery);
                        break;

                    case Commands.Association_Set:
                        Association.Set(node, (byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                        break;

                    case Commands.Association_Get:
                        byte group = (byte)int.Parse(request.GetOption(0));
                        Association.Get(node, group);
                        returnValue = GetResponseValue(EventPath_Associations + "." + group);
                        break;

                    case Commands.Association_Remove:
                        Association.Remove(node, (byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                        break;

                    case Commands.ManufacturerSpecific_Get:
                        ManufacturerSpecific.Get(node);
                        returnValue = GetResponseValue(EventPath_ManufacturerSpecific);
                        break;

                    case Commands.Config_ParameterSet:
                        Configuration.Set(node, (byte)int.Parse(request.GetOption(0)), int.Parse(request.GetOption(1)));
                        break;

                    case Commands.Config_ParameterGet:
                        byte position = (byte)int.Parse(request.GetOption(0));
                        Configuration.Get(node, position);
                        returnValue = GetResponseValue(EventPath_ConfigVariables + "." + position);
                        break;

                    case Commands.WakeUp_Get:
                        WakeUp.Get(node);
                        returnValue = GetResponseValue(EventPath_WakeUpInterval);
                        break;

                    case Commands.WakeUp_Set:
                        WakeUp.Set(node, uint.Parse(request.GetOption(0)));
                        break;

                    case Commands.Control_On:
                        raiseEvent = true;
                        eventValue = "1";
                        Basic.Set(node, 0xFF);
                        SetNodeLevel(node, 0xFF);
                        break;

                    case Commands.Control_Off:
                        raiseEvent = true;
                        eventValue = "0";
                        Basic.Set(node, 0x00);
                        SetNodeLevel(node, 0x00);
                        break;

                    case Commands.Control_Level:
                        {
                            raiseEvent = true;
                            var level = int.Parse(request.GetOption(0));
                            eventValue = Math.Round(level / 100D, 2).ToString(CultureInfo.InvariantCulture);
                            // the max value should be obtained from node parameters specifications,
                            // here we assume that the commonly used interval is [0-99] for most multilevel switches
                            if (level >= 100)
                                level = 99;
                            if (node.SupportCommandClass(CommandClass.SwitchMultilevel))
                                SwitchMultilevel.Set(node, (byte)level);
                            else
                                Basic.Set(node, (byte)level);
                            SetNodeLevel(node, (byte)level);
                        }
                        break;

                    case Commands.Control_Toggle:
                        raiseEvent = true;
                        if (GetNodeLevel(node) == 0)
                        {
                            eventValue = "1";
                            Basic.Set(node, 0xFF);
                            SetNodeLevel(node, 0xFF);
                        }
                        else
                        {
                            eventValue = "0";
                            Basic.Set(node, 0x00);
                            SetNodeLevel(node, 0x00);
                        }
                        break;

                    case Commands.Thermostat_ModeGet:
                        ThermostatMode.Get(node);
                        break;

                    case Commands.Thermostat_ModeSet:
                        {
                            ThermostatMode.Value mode = (ThermostatMode.Value)Enum.Parse(typeof(ThermostatMode.Value), request.GetOption(0));
                            //
                            raiseEvent = true;
                            eventParameter = "Thermostat.Mode";
                            eventValue = request.GetOption(0);
                            //
                            ThermostatMode.Set(node, mode);
                        }
                        break;

                    case Commands.Thermostat_SetPointGet:
                        {
                            ThermostatSetPoint.Value mode = (ThermostatSetPoint.Value)Enum.Parse(typeof(ThermostatSetPoint.Value), request.GetOption(0));
                            ThermostatSetPoint.Get(node, mode);
                        }
                        break;

                    case Commands.Thermostat_SetPointSet:
                        {
                            ThermostatSetPoint.Value mode = (ThermostatSetPoint.Value)Enum.Parse(typeof(ThermostatSetPoint.Value), request.GetOption(0));
                            double temperature = double.Parse(request.GetOption(1).Replace(',', '.'), CultureInfo.InvariantCulture);
                            //
                            raiseEvent = true;
                            eventParameter = "Thermostat.SetPoint." + request.GetOption(0);
                            eventValue = temperature.ToString(CultureInfo.InvariantCulture);
                            //
                            ThermostatSetPoint.Set(node, mode, temperature);
                        }
                        break;

                    case Commands.Thermostat_FanModeGet:
                        ThermostatFanMode.Get(node);
                        break;

                    case Commands.Thermostat_FanModeSet:
                        {
                            ThermostatFanMode.Value mode = (ThermostatFanMode.Value)Enum.Parse(typeof(ThermostatFanMode.Value), request.GetOption(0));
                            //
                            raiseEvent = true;
                            eventParameter = "Thermostat.FanMode";
                            eventValue = request.GetOption(0);
                            //
                            ThermostatFanMode.Set(node, mode);
                        }
                        break;

                    case Commands.Thermostat_FanStateGet:
                        ThermostatFanState.Get(node);
                        break;

                    case Commands.Thermostat_OperatingStateGet:
                        ThermostatOperatingState.GetOperatingState(node);
                        break;

                    case Commands.UserCode_Set:
                        byte userId = byte.Parse(request.GetOption(0));
                        byte userIdStatus = byte.Parse(request.GetOption(1));
                        byte[] tagCode = ZWaveLib.Utility.HexStringToByteArray(request.GetOption(2));
                        UserCode.Set(node, new ZWaveLib.Values.UserCodeValue(userId, userIdStatus, tagCode));
                        break;

                    case Commands.DoorLock_Get:
                        DoorLock.Get(node);
                        returnValue = GetResponseValue(EventPath_DoorLock);
                        break;

                    case Commands.DoorLock_Set:
                        {
                            DoorLock.Value mode = (DoorLock.Value)Enum.Parse(typeof(DoorLock.Value), request.GetOption(0));
                            DoorLock.Set(node, mode);
                        }
                        break;
                    }
                }
            }

            if (raiseEvent && InterfacePropertyChangedAction != null)
            {
                //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                    Domain = this.Domain,
                    SourceId = nodeId,
                    SourceType = "ZWave Node",
                    Path = eventParameter,
                    Value = eventValue
                });
            }
            //
            return returnValue;
        }
Пример #40
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string returnvalue      = "";
            bool   raisepropchanged = false;
            string parampath        = "Status.Unhandled";
            string raiseparam       = "";
            //
            UPnPDevice device = _upnpDeviceGet(request.nodeid);

            //////////////////// Commands: SwitchPower, Dimming
            if (request.command == Command.CONTROL_ON || request.command == Command.CONTROL_OFF)
            {
                bool           cmdval   = (request.command == Command.CONTROL_ON ? true : false);
                UPnPArgument   newvalue = new UPnPArgument("newTargetValue", cmdval);
                UPnPArgument[] args     = new UPnPArgument[] {
                    newvalue
                };
                _upnpDeviceServiceInvoke(device, "SwitchPower", "SetTarget", args);
                //
                raisepropchanged = true;
                parampath        = "Status.Level";
                raiseparam       = (cmdval ? "1" : "0");
            }
            else if (request.command == Command.CONTROL_LEVEL)
            {
                UPnPArgument   newvalue = new UPnPArgument("NewLoadLevelTarget", (byte)uint.Parse(request.GetOption(0)));
                UPnPArgument[] args     = new UPnPArgument[] {
                    newvalue
                };
                _upnpDeviceServiceInvoke(device, "Dimming", "SetLoadLevelTarget", args);
                //
                raisepropchanged = true;
                parampath        = "Status.Level";
                raiseparam       = (double.Parse(request.GetOption(0)) / 100d).ToString(System.Globalization.CultureInfo.InvariantCulture);
            }
            else if (request.command == Command.CONTROL_TOGGLE)
            {
            }
            //////////////////// Commands: Browse, AVTransport
            else if (request.command == Command.AVMEDIA_GETURI)
            {
                string devid = request.nodeid;
                string objid = request.GetOption(0);
                //
                UPnPArgument objectid     = new UPnPArgument("ObjectID", objid);
                UPnPArgument flags        = new UPnPArgument("BrowseFlag", "BrowseMetadata");
                UPnPArgument filter       = new UPnPArgument("Filter", "upnp:album,upnp:artist,upnp:genre,upnp:title,res@size,res@duration,res@bitrate,res@sampleFrequency,res@bitsPerSample,res@nrAudioChannels,res@protocolInfo,res@protection,res@importUri");
                UPnPArgument startindex   = new UPnPArgument("StartingIndex", (uint)0);
                UPnPArgument reqcount     = new UPnPArgument("RequestedCount", (uint)1);
                UPnPArgument sortcriteria = new UPnPArgument("SortCriteria", "");
                //
                UPnPArgument result       = new UPnPArgument("Result", "");
                UPnPArgument numreturned  = new UPnPArgument("NumberReturned", "");
                UPnPArgument totalmatches = new UPnPArgument("TotalMatches", "");
                UPnPArgument updateid     = new UPnPArgument("UpdateID", "");
                //
                _upnpDeviceServiceInvoke(device, "ContentDirectory", "Browse", new UPnPArgument[] {
                    objectid,
                    flags,
                    filter,
                    startindex,
                    reqcount,
                    sortcriteria,
                    result,
                    numreturned,
                    totalmatches,
                    updateid
                });
                //
                try
                {
                    string   ss   = result.DataValue.ToString();
                    XElement item = XDocument.Parse(ss, LoadOptions.SetBaseUri).Descendants().Where(ii => ii.Name.LocalName == "item").First();
                    //
                    foreach (XElement i in item.Elements())
                    {
                        XAttribute item_protocoluri = i.Attribute("protocolInfo");
                        if (item_protocoluri != null)
                        {
                            returnvalue = i.Value;
                            break;
                        }
                    }
                }
                catch { }
            }
            else if (request.command == Command.AVMEDIA_BROWSE)
            {
                string devid = request.nodeid;
                string objid = request.GetOption(0);
                //
                UPnPArgument objectid     = new UPnPArgument("ObjectID", objid);
                UPnPArgument flags        = new UPnPArgument("BrowseFlag", "BrowseDirectChildren");
                UPnPArgument filter       = new UPnPArgument("Filter", "upnp:album,upnp:artist,upnp:genre,upnp:title,res@size,res@duration,res@bitrate,res@sampleFrequency,res@bitsPerSample,res@nrAudioChannels,res@protocolInfo,res@protection,res@importUri");
                UPnPArgument startindex   = new UPnPArgument("StartingIndex", (uint)0);
                UPnPArgument reqcount     = new UPnPArgument("RequestedCount", (uint)0);
                UPnPArgument sortcriteria = new UPnPArgument("SortCriteria", "");
                //
                UPnPArgument result       = new UPnPArgument("Result", "");
                UPnPArgument numreturned  = new UPnPArgument("NumberReturned", "");
                UPnPArgument totalmatches = new UPnPArgument("TotalMatches", "");
                UPnPArgument updateid     = new UPnPArgument("UpdateID", "");
                //
                _upnpDeviceServiceInvoke(device, "ContentDirectory", "Browse", new UPnPArgument[] {
                    objectid,
                    flags,
                    filter,
                    startindex,
                    reqcount,
                    sortcriteria,
                    result,
                    numreturned,
                    totalmatches,
                    updateid
                });
                //
                try
                {
                    string ss = result.DataValue.ToString();
                    IEnumerable <XElement> root = XDocument.Parse(ss, LoadOptions.SetBaseUri).Elements();
                    //
                    string jsonres = "[";
                    foreach (XElement i in root.Elements())
                    {
                        string item_id    = i.Attribute("id").Value;
                        string item_title = i.Descendants().Where(n => n.Name.LocalName == "title").First().Value;
                        string item_class = i.Descendants().Where(n => n.Name.LocalName == "class").First().Value;
                        jsonres += "{ \"Id\" : \"" + item_id + "\", \"Title\" : \"" + item_title + "\", \"Class\" : \"" + item_class + "\" },\n";
                    }
                    jsonres = jsonres.TrimEnd(',', '\n') + "]";
                    //
                    returnvalue = jsonres;
                }
                catch { }
            }
            else if (request.command == Command.AVMEDIA_GETTRANSPORTINFO)
            {
                UPnPArgument   instanceid      = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument   transportstate  = new UPnPArgument("CurrentTransportState", "");
                UPnPArgument   transportstatus = new UPnPArgument("CurrentTransportStatus", "");
                UPnPArgument   currentspeed    = new UPnPArgument("CurrentSpeed", "");
                UPnPArgument[] args            = new UPnPArgument[] {
                    instanceid,
                    transportstate,
                    transportstatus,
                    currentspeed
                };
                _upnpDeviceServiceInvoke(device, "AVTransport", "GetTransportInfo", args);
                //
                string jsonres = "[{ ";
                jsonres += "\"CurrentTransportState\" : \"" + transportstate.DataValue + "\", ";
                jsonres += "\"CurrentTransportStatus\" : \"" + transportstatus.DataValue + "\", ";
                jsonres += "\"CurrentSpeed\" : \"" + currentspeed.DataValue + "\"";
                jsonres += " }]";
                //
                returnvalue = jsonres;
            }
            else if (request.command == Command.AVMEDIA_GETMEDIAINFO)
            {
                UPnPArgument   instanceid         = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument   nrtracks           = new UPnPArgument("NrTracks", (uint)0);
                UPnPArgument   mediaduration      = new UPnPArgument("MediaDuration", "");
                UPnPArgument   currenturi         = new UPnPArgument("CurrentURI", "");
                UPnPArgument   currenturimetadata = new UPnPArgument("CurrentURIMetaData", "");
                UPnPArgument   nexturi            = new UPnPArgument("NextURI", "");
                UPnPArgument   nexturimetadata    = new UPnPArgument("NextURIMetaData", "");
                UPnPArgument   playmedium         = new UPnPArgument("PlayMedium", "");
                UPnPArgument   recordmedium       = new UPnPArgument("RecordMedium", "");
                UPnPArgument   writestatus        = new UPnPArgument("WriteStatus", "");
                UPnPArgument[] args = new UPnPArgument[] {
                    instanceid,
                    nrtracks,
                    mediaduration,
                    currenturi,
                    currenturimetadata,
                    nexturi,
                    nexturimetadata,
                    playmedium,
                    recordmedium,
                    writestatus
                };
                _upnpDeviceServiceInvoke(device, "AVTransport", "GetMediaInfo", args);
                //
                string jsonres = "[{ ";
                jsonres += "\"NrTracks\" : \"" + nrtracks.DataValue + "\", ";
                jsonres += "\"MediaDuration\" : \"" + mediaduration.DataValue + "\", ";
                jsonres += "\"CurrentURI\" : \"" + currenturi.DataValue + "\", ";
                jsonres += "\"CurrentURIMetaData\" : \"" + currenturimetadata.DataValue + "\", ";
                jsonres += "\"NextURI\" : \"" + nexturi.DataValue + "\", ";
                jsonres += "\"NextURIMetaData\" : \"" + nexturimetadata.DataValue + "\", ";
                jsonres += "\"PlayMedium\" : \"" + playmedium.DataValue + "\", ";
                jsonres += "\"RecordMedium\" : \"" + recordmedium.DataValue + "\", ";
                jsonres += "\"WriteStatus\" : \"" + writestatus.DataValue + "\"";
                jsonres += " }]";
                //
                returnvalue = jsonres;
            }
            else if (request.command == Command.AVMEDIA_GETPOSITIONINFO)
            {
                UPnPArgument   instanceid    = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument   currenttrack  = new UPnPArgument("Track", (uint)0);
                UPnPArgument   trackduration = new UPnPArgument("TrackDuration", "");
                UPnPArgument   trackmetadata = new UPnPArgument("TrackMetaData", "");
                UPnPArgument   trackuri      = new UPnPArgument("TrackURI", "");
                UPnPArgument   reltime       = new UPnPArgument("RelTime", "");
                UPnPArgument   abstime       = new UPnPArgument("AbsTime", "");
                UPnPArgument   relcount      = new UPnPArgument("RelCount", (uint)0);
                UPnPArgument   abscount      = new UPnPArgument("AbsCount", (uint)0);
                UPnPArgument[] args          = new UPnPArgument[] {
                    instanceid,
                    currenttrack,
                    trackduration,
                    trackmetadata,
                    trackuri,
                    reltime,
                    abstime,
                    relcount,
                    abscount
                };
                _upnpDeviceServiceInvoke(device, "AVTransport", "GetPositionInfo", args);
                //
                string jsonres = "[{";
                jsonres += "\"Track\" : \"" + currenttrack.DataValue + "\",";
                jsonres += "\"TrackDuration\" : \"" + trackduration.DataValue + "\",";
                jsonres += "\"TrackMetaData\" : \"" + trackmetadata.DataValue + "\",";
                jsonres += "\"TrackURI\" : \"" + trackuri.DataValue + "\",";
                jsonres += "\"RelTime\" : \"" + reltime.DataValue + "\",";
                jsonres += "\"AbsTime\" : \"" + abstime.DataValue + "\",";
                jsonres += "\"RelCount\" : \"" + relcount.DataValue + "\",";
                jsonres += "\"AbsCount\" : \"" + abscount.DataValue + "\"";
                jsonres += "}]";
                //
                returnvalue = jsonres;
            }
            else if (request.command == Command.AVMEDIA_SETURI)
            {
                UPnPArgument   instanceid  = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument   currenturi  = new UPnPArgument("CurrentURI", request.GetOption(0));
                UPnPArgument   urimetadata = new UPnPArgument("CurrentURIMetaData", "");
                UPnPArgument[] args        = new UPnPArgument[] {
                    instanceid,
                    currenturi,
                    urimetadata
                };
                _upnpDeviceServiceInvoke(device, "AVTransport", "SetAVTransportURI", args);
            }
            else if (request.command == Command.AVMEDIA_PLAY)
            {
                UPnPArgument   instanceid = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument   speed      = new UPnPArgument("Speed", "1");
                UPnPArgument[] args       = new UPnPArgument[] {
                    instanceid,
                    speed
                };
                _upnpDeviceServiceInvoke(device, "AVTransport", "Play", args);
            }
            else if (request.command == Command.AVMEDIA_PAUSE)
            {
                UPnPArgument   instanceid = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument[] args       = new UPnPArgument[] {
                    instanceid
                };
                _upnpDeviceServiceInvoke(device, "AVTransport", "Pause", args);
            }
            else if (request.command == Command.AVMEDIA_STOP)
            {
                UPnPArgument   instanceid = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument[] args       = new UPnPArgument[] {
                    instanceid
                };
                _upnpDeviceServiceInvoke(device, "AVTransport", "Stop", args);
            }
            else if (request.command == Command.AVMEDIA_PREVIOUS)
            {
                UPnPArgument   instanceid = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument[] args       = new UPnPArgument[] {
                    instanceid
                };
                _upnpDeviceServiceInvoke(device, "AVTransport", "Previous", args);
            }
            else if (request.command == Command.AVMEDIA_NEXT)
            {
                UPnPArgument   instanceid = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument[] args       = new UPnPArgument[] {
                    instanceid
                };
                _upnpDeviceServiceInvoke(device, "AVTransport", "Next", args);
            }
            else if (request.command == Command.AVMEDIA_SETNEXT)
            {
            }
            else if (request.command == Command.AVMEDIA_GETMUTE)
            {
                UPnPArgument   instanceid  = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument   channel     = new UPnPArgument("Channel", "Master");
                UPnPArgument   currentmute = new UPnPArgument("CurrentMute", "");
                UPnPArgument[] args        = new UPnPArgument[] {
                    instanceid,
                    channel,
                    currentmute
                };
                _upnpDeviceServiceInvoke(device, "RenderingControl", "GetMute", args);
                returnvalue = currentmute.DataValue.ToString();
            }
            else if (request.command == Command.AVMEDIA_SETMUTE)
            {
                UPnPArgument   instanceid = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument   channel    = new UPnPArgument("Channel", "Master");
                UPnPArgument   mute       = new UPnPArgument("DesiredMute", request.GetOption(0) == "1" ? true : false);
                UPnPArgument[] args       = new UPnPArgument[] {
                    instanceid,
                    channel,
                    mute
                };
                _upnpDeviceServiceInvoke(device, "RenderingControl", "SetMute", args);
            }
            else if (request.command == Command.AVMEDIA_GETVOLUME)
            {
                UPnPArgument   instanceid    = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument   channel       = new UPnPArgument("Channel", "Master");
                UPnPArgument   currentvolume = new UPnPArgument("CurrentVolume", "");
                UPnPArgument[] args          = new UPnPArgument[] {
                    instanceid,
                    channel,
                    currentvolume
                };
                _upnpDeviceServiceInvoke(device, "RenderingControl", "GetVolume", args);
                returnvalue = currentvolume.DataValue.ToString();
            }
            else if (request.command == Command.AVMEDIA_SETVOLUME)
            {
                UPnPArgument   instanceid = new UPnPArgument("InstanceID", (uint)0);
                UPnPArgument   channel    = new UPnPArgument("Channel", "Master");
                UPnPArgument   volume     = new UPnPArgument("DesiredVolume", UInt16.Parse(request.GetOption(0)));
                UPnPArgument[] args       = new UPnPArgument[] {
                    instanceid,
                    channel,
                    volume
                };
                _upnpDeviceServiceInvoke(device, "RenderingControl", "SetVolume", args);
            }


            // signal event
            if (raisepropchanged && InterfacePropertyChangedAction != null)
            {
                try
                {
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction()
                    {
                        Domain = this.Domain, SourceId = device.UniqueDeviceName, SourceType = "UPnP " + (device != null ? device.StandardDeviceType : "device"), Path = parampath, Value = raiseparam
                    });
                }
                catch { }
            }


            return(returnvalue);
        }
Пример #41
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     string returnValue = "";
     bool raiseEvent = false;
     string eventParameter = "Status.Level";
     string eventValue = "";
     //
     string nodeId = request.NodeId;
     Command command = (Command)request.Command;
     ////----------------------
     ///
     int n = 0;
     if (int.TryParse(nodeId, out n))
     lock(syncLock)
     try
     {
         byte nodeNumber = (byte)n;
         if (command == Command.CONTROLLER_DISCOVERY)
         {
             controller.Discovery();
         }
         else if (command == Command.CONTROLLER_SOFTRESET)
         {
             controller.SoftReset();
         }
         else if (command == Command.CONTROLLER_HARDRESET)
         {
             controller.HardReset();
             Thread.Sleep(500);
             controller.Discovery();
         }
         else if (command == Command.CONTROLLER_NODEADD)
         {
             lastAddedNode = 0;
             /*byte addedId = */ controller.BeginNodeAdd();
             for (int i = 0; i < 20; i++)
             {
                 if (lastAddedNode > 0)
                 {
                     break;
                 }
                 Thread.Sleep(500);
             }
             controller.StopNodeAdd();
             //
             returnValue = lastAddedNode.ToString();
         }
         else if (command == Command.CONTROLLER_NODEREMOVE)
         {
             lastRemovedNode = 0;
             /*byte remcid = */ controller.BeginNodeRemove();
             for (int i = 0; i < 20; i++)
             {
                 if (lastRemovedNode > 0)
                 {
                     break;
                 }
                 Thread.Sleep(500);
             }
             controller.StopNodeRemove();
             //
             returnValue = lastRemovedNode.ToString();
         }
         ////----------------------
         else if (command == Command.BASIC_SET)
         {
             raiseEvent = true;
             //raiseValue = Math.Round(double.Parse(request.GetOption(0)) / 99D, 2);
             //if (raiseValue >= 0.99) raiseValue = 1;
             var level = int.Parse(request.GetOption(0));
             eventValue = level.ToString(CultureInfo.InvariantCulture);
             //
             var node = controller.GetDevice(nodeNumber);
             Basic.Set(node, (byte)level);
         }
         else if (command == Command.BASIC_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             Basic.Get(node);
         }
         ////-----------------------
         else if (command == Command.MULTIINSTANCE_GETCOUNT)
         {
             var node = controller.GetDevice(nodeNumber);
             //
             switch (request.GetOption(0))
             {
             case "Switch.Binary":
                 MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SwitchBinary);
                 break;
             case "Switch.MultiLevel":
                 MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SwitchMultilevel);
                 break;
             case "Sensor.Binary":
                 MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SensorBinary);
                 break;
             case "Sensor.MultiLevel":
                 MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SensorMultilevel);
                 break;
             }
         }
         else if (command == Command.MULTIINSTANCE_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
             //
             switch (request.GetOption(0))
             {
             case "Switch.Binary":
                 MultiInstance.SwitchBinaryGet(node, instance);
                 break;
             case "Switch.MultiLevel":
                 MultiInstance.SwitchMultiLevelGet(node, instance);
                 break;
             case "Sensor.Binary":
                 MultiInstance.SensorBinaryGet(node, instance);
                 break;
             case "Sensor.MultiLevel":
                 MultiInstance.SensorMultiLevelGet(node, instance);
                 break;
             }
         }
         else if (command == Command.MULTIINSTANCE_SET)
         {
             var node = controller.GetDevice(nodeNumber);
             byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
             int value = int.Parse(request.GetOption(2));
             //
             //raisepropchanged = true;
             //parampath += "." + instance; // Status.Level.<instance>
             //
             switch (request.GetOption(0))
             {
             case "Switch.Binary":
                 MultiInstance.SwitchBinarySet(node, instance, value);
                     //raiseparam = (double.Parse(request.GetOption(2)) / 255).ToString();
                 break;
             case "Switch.MultiLevel":
                 MultiInstance.SwitchMultiLevelSet(node, instance, value);
                     //raiseparam = (double.Parse(request.GetOption(2)) / 100).ToString(); // TODO: should it be 99 ?
                 break;
             }
         }
         else if (command == Command.SENSORBINARY_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             SensorBinary.Get(node);
         }
         else if (command == Command.SENSORMULTILEVEL_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             SensorMultilevel.Get(node);
         }
         else if (command == Command.METER_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             // see ZWaveLib Sensor.cs for EnergyMeterScale options
             int scaleType = 0; int.TryParse(request.GetOption(0), out scaleType);
             Meter.Get(node, (byte)(scaleType << 0x03));
         }
         else if (command == Command.METER_SUPPORTEDGET)
         {
             var node = controller.GetDevice(nodeNumber);
             Meter.GetSupported(node);
         }
         else if (command == Command.METER_RESET)
         {
             var node = controller.GetDevice(nodeNumber);
             Meter.Reset(node);
         }
         else if (command == Command.NODEINFO_GET)
         {
             controller.GetNodeInformationFrame(nodeNumber);
         }
         ////-----------------------
         else if (command == Command.BATTERY_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             Battery.Get(node);
         }
         ////-----------------------
         else if (command == Command.ASSOCIATION_SET)
         {
             var node = controller.GetDevice(nodeNumber);
             Association.Set(node, (byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
         }
         else if (command == Command.ASSOCIATION_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             Association.Get(node, (byte)int.Parse(request.GetOption(0))); // groupid
         }
         else if (command == Command.ASSOCIATION_REMOVE)
         {
             var node = controller.GetDevice(nodeNumber);
             Association.Remove(node, (byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1))); // groupid
         }
         ////-----------------------
         else if (command == Command.MANUFACTURERSPECIFIC_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             ManufacturerSpecific.Get(node);
         }
         ////------------------
         else if (command == Command.CONFIG_PARAMETERSET)
         {
             var node = controller.GetDevice(nodeNumber);
             //byte[] value = new byte[] { (byte)int.Parse(option1) };//BitConverter.GetBytes(Int16.Parse(option1));
             //Array.Reverse(value);
             Configuration.Set(node, (byte)int.Parse(request.GetOption(0)), int.Parse(request.GetOption(1)));
         }
         else if (command == Command.CONFIG_PARAMETERGET)
         {
             var node = controller.GetDevice(nodeNumber);
             Configuration.Get(node, (byte)int.Parse(request.GetOption(0)));
         }
         ////------------------
         else if (command == Command.WAKEUP_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             WakeUp.Get(node);
         }
         else if (command == Command.WAKEUP_SET)
         {
             var node = controller.GetDevice(nodeNumber);
             WakeUp.Set(node, uint.Parse(request.GetOption(0)));
         }
         ////------------------
         else if (command == Command.CONTROL_ON)
         {
             raiseEvent = true;
             eventValue = "1";
             var node = controller.GetDevice(nodeNumber);
             Basic.Set(node, 0xFF);
             SetNodeLevel(node, 0xFF);
         }
         else if (command == Command.CONTROL_OFF)
         {
             raiseEvent = true;
             eventValue = "0";
             var node = controller.GetDevice(nodeNumber);
             Basic.Set(node, 0x00);
             SetNodeLevel(node, 0x00);
         }
         else if (command == Command.CONTROL_LEVEL)
         {
             raiseEvent = true;
             var level = int.Parse(request.GetOption(0));
             eventValue = Math.Round(level / 100D, 2).ToString(CultureInfo.InvariantCulture);
             // the max value should be obtained from node parameters specifications,
             // here we assume that the commonly used interval is [0-99] for most multilevel switches
             if (level >= 100) level = 99;
             var node = controller.GetDevice(nodeNumber);
             if(node.SupportCommandClass(CommandClass.SwitchMultilevel))
                 SwitchMultilevel.Set(node, (byte)level);
             else
                 Basic.Set(node, (byte)level);
             SetNodeLevel(node, (byte)level);
         }
         else if (command == Command.CONTROL_TOGGLE)
         {
             raiseEvent = true;
             var node = controller.GetDevice(nodeNumber);
             if (GetNodeLevel(node) == 0)
             {
                 eventValue = "1";
                 Basic.Set(node, 0xFF);
                 SetNodeLevel(node, 0xFF);
             }
             else
             {
                 eventValue = "0";
                 Basic.Set(node, 0x00);
                 SetNodeLevel(node, 0x00);
             }
         }
         else if (command == Command.THERMOSTAT_MODEGET)
         {
             var node = controller.GetDevice(nodeNumber);
             ThermostatMode.Get(node);
         }
         else if (command == Command.THERMOSTAT_MODESET)
         {
             var node = controller.GetDevice(nodeNumber);
             ThermostatMode.Value mode = (ThermostatMode.Value)Enum.Parse(typeof(ThermostatMode.Value), request.GetOption(0));
             //
             raiseEvent = true;
             eventParameter = "Thermostat.Mode";
             eventValue = request.GetOption(0);
             //
             ThermostatMode.Set(node, mode);
         }
         else if (command == Command.THERMOSTAT_SETPOINTGET)
         {
             var node = controller.GetDevice(nodeNumber);
             ThermostatSetPoint.Value mode = (ThermostatSetPoint.Value)Enum.Parse(typeof(ThermostatSetPoint.Value), request.GetOption(0));
             ThermostatSetPoint.Get(node, mode);
         }
         else if (command == Command.THERMOSTAT_SETPOINTSET)
         {
             var node = controller.GetDevice(nodeNumber);
             ThermostatSetPoint.Value mode = (ThermostatSetPoint.Value)Enum.Parse(typeof(ThermostatSetPoint.Value), request.GetOption(0));
             double temperature = double.Parse(request.GetOption(1).Replace(',', '.'), CultureInfo.InvariantCulture);
             //
             raiseEvent = true;
             eventParameter = "Thermostat.SetPoint." + request.GetOption(0);
             eventValue = temperature.ToString(CultureInfo.InvariantCulture);
             //
             ThermostatSetPoint.Set(node, mode, temperature);
         }
         else if (command == Command.THERMOSTAT_FANMODEGET)
         {
             var node = controller.GetDevice(nodeNumber);
             ThermostatFanMode.Get(node);
         }
         else if (command == Command.THERMOSTAT_FANMODESET)
         {
             var node = controller.GetDevice(nodeNumber);
             ThermostatFanMode.Value mode = (ThermostatFanMode.Value)Enum.Parse(typeof(ThermostatFanMode.Value), request.GetOption(0));
             //
             raiseEvent = true;
             eventParameter = "Thermostat.FanMode";
             eventValue = request.GetOption(0);
             //
             ThermostatFanMode.Set(node, mode);
         }
         else if (command == Command.THERMOSTAT_FANSTATEGET)
         {
             var node = controller.GetDevice(nodeNumber);
             ThermostatFanState.Get(node);
         }
         else if (command == Command.THERMOSTAT_OPERATINGSTATE_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             ThermostatOperatingState.GetOperatingState(node);
         }
         else if(command==Command.USERCODE_SET)
         {
             var node = controller.GetDevice(nodeNumber);
             byte userId = byte.Parse(request.GetOption(0));
             byte userIdStatus = byte.Parse(request.GetOption(1));
             byte[] tagCode = ZWaveLib.Utility.HexStringToByteArray(request.GetOption(2));
             UserCode.Set(node, new ZWaveLib.Values.UserCodeValue(userId, userIdStatus, tagCode));
         }
         else if (command == Command.DOORLOCK_SET)
         {
             var node = controller.GetDevice(nodeNumber);
             DoorLock.Value mode = (DoorLock.Value)Enum.Parse(typeof(DoorLock.Value), request.GetOption(0));
             DoorLock.Set(node, mode);
         }
         else if (command == Command.DOORLOCK_GET)
         {
             var node = controller.GetDevice(nodeNumber);
             DoorLock.Get(node);
         }
     }
     catch (Exception e)
     {
         if (eventValue != "") raiseEvent = true;
         Console.WriteLine("ZWave Interface Exception: " + e.Message + "\n" + e.StackTrace);
     }
     //
     if (raiseEvent && InterfacePropertyChangedAction != null)
     {
         try
         {
             //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
             InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                 Domain = this.Domain,
                 SourceId = nodeId,
                 SourceType = "ZWave Node",
                 Path = eventParameter,
                 Value = eventValue
             });
         }
         catch
         {
         }
     }
     //
     return returnValue;
 }
Пример #42
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     return("");
 }
Пример #43
0
        public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migCommand)
        {
            switch (migCommand.Command)
            {
            case "Interfaces.List":
                migCommand.Response = "[ ";
                foreach (var kv in homegenie.Interfaces)
                {
                    var migInterface = kv.Value;
                    var ifaceConfig  = homegenie.SystemConfiguration.MIGService.GetInterface(migInterface.Domain);
                    if (ifaceConfig == null || !ifaceConfig.IsEnabled)
                    {
                        continue;
                    }
                    migCommand.Response += "{ \"Domain\" : \"" + migInterface.Domain + "\", \"IsConnected\" : \"" + migInterface.IsConnected + "\" },";
                }
                if (homegenie.UpdateChecker != null && homegenie.UpdateChecker.IsUpdateAvailable)
                {
                    migCommand.Response += "{ \"Domain\" : \"" + Domains.HomeGenie_UpdateChecker + "\", \"IsConnected\" : \"True\" }";
                    migCommand.Response += " ]";
                }
                else
                {
                    migCommand.Response = migCommand.Response.Substring(0, migCommand.Response.Length - 1) + " ]";
                }
                //
                break;

            //TODO: should this be moved somewhere to MIG?
            case "Interfaces.Configure":
                switch (migCommand.GetOption(0))
                {
                case "Hardware.SerialPorts":
                    if (Environment.OSVersion.Platform == PlatformID.Unix)
                    {
                        var serialPorts = System.IO.Ports.SerialPort.GetPortNames();
                        var portList    = new List <string>();
                        for (int p = serialPorts.Length - 1; p >= 0; p--)
                        {
                            if (serialPorts[p].Contains("/ttyS") || serialPorts[p].Contains("/ttyUSB"))
                            {
                                portList.Add(serialPorts[p]);
                            }
                        }
                        if (Raspberry.Board.Current.IsRaspberryPi)
                        {
                            if (!portList.Contains("/dev/ttyAMA0"))
                            {
                                portList.Add("/dev/ttyAMA0"); // RaZberry
                            }
                            if (!portList.Contains("/dev/ttyACM0"))
                            {
                                portList.Add("/dev/ttyACM0"); // ZME_UZB1
                            }
                        }
                        migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portList));
                    }
                    else
                    {
                        var portNames = System.IO.Ports.SerialPort.GetPortNames();
                        migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portNames));
                    }
                    break;
                }
                break;

            case "System.Configure":
                if (migCommand.GetOption(0) == "Service.Restart")
                {
                    Program.Quit(true);
                    migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                }
                else if (migCommand.GetOption(0) == "UpdateManager.UpdatesList")
                {
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.UpdateChecker.RemoteUpdates);
                }
                else if (migCommand.GetOption(0) == "UpdateManager.Check")
                {
                    homegenie.UpdateChecker.Check();
                    migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                }
                else if (migCommand.GetOption(0) == "UpdateManager.DownloadUpdate")
                {
                    var  resultMessage = "ERROR";
                    bool success       = homegenie.UpdateChecker.DownloadUpdateFiles();
                    if (success)
                    {
                        if (homegenie.UpdateChecker.IsRestartRequired)
                        {
                            resultMessage = "RESTART";
                        }
                        else
                        {
                            resultMessage = "OK";
                        }
                    }
                    migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage);
                }
                else if (migCommand.GetOption(0) == "UpdateManager.InstallUpdate") //UpdateManager.InstallProgramsCommit")
                {
                    string resultMessage = "OK";
                    if (!homegenie.UpdateChecker.InstallFiles())
                    {
                        resultMessage = "ERROR";
                    }
                    else
                    {
                        if (homegenie.UpdateChecker.IsRestartRequired)
                        {
                            resultMessage = "RESTART";
                            Utility.RunAsyncTask(() =>
                            {
                                Thread.Sleep(2000);
                                Program.Quit(true);
                            });
                        }
                        else
                        {
                            homegenie.LoadConfiguration();
                            homegenie.MigService.ClearWebCache();
                            homegenie.UpdateChecker.Check();
                        }
                    }
                    migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage);
                }
                else if (migCommand.GetOption(0) == "HttpService.SetWebCacheEnabled")
                {
                    if (migCommand.GetOption(1) == "1")
                    {
                        homegenie.MigService.IsWebCacheEnabled = true;
                        homegenie.SystemConfiguration.MIGService.EnableWebCache = "true";
                    }
                    else
                    {
                        homegenie.MigService.IsWebCacheEnabled = false;
                        homegenie.SystemConfiguration.MIGService.EnableWebCache = "false";
                    }
                    homegenie.SystemConfiguration.Update();
                    migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                }
                else if (migCommand.GetOption(0) == "HttpService.GetWebCacheEnabled")
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.MigService.IsWebCacheEnabled ? "1" : "0");
                }
                else if (migCommand.GetOption(0) == "HttpService.GetPort")
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.SystemConfiguration.HomeGenie.ServicePort.ToString());
                }
                else if (migCommand.GetOption(0) == "HttpService.SetPort")
                {
                    try
                    {
                        homegenie.SystemConfiguration.HomeGenie.ServicePort = int.Parse(migCommand.GetOption(1));
                        homegenie.SystemConfiguration.Update();
                    }
                    catch
                    {
                    }
                }
                else if (migCommand.GetOption(0) == "Statistics.GetStatisticsDatabaseMaximumSize")
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes.ToString());
                }
                else if (migCommand.GetOption(0) == "Statistics.SetStatisticsDatabaseMaximumSize")
                {
                    try
                    {
                        homegenie.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes = int.Parse(migCommand.GetOption(1));
                        homegenie.SystemConfiguration.Update();
                    }
                    catch
                    {
                    }
                }
                else if (migCommand.GetOption(0) == "SystemLogging.DownloadCsv")
                {
                    string csvlog  = "";
                    string logpath = Path.Combine("log", "homegenie.log");
                    if (migCommand.GetOption(1) == "1")
                    {
                        logpath = Path.Combine("log", "homegenie.log.bak");
                    }
                    if (File.Exists(logpath))
                    {
                        using (var fs = new FileStream(logpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            using (var sr = new StreamReader(fs, Encoding.Default))
                            {
                                csvlog = sr.ReadToEnd();
                            }
                    }
                    (request.Context as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment;filename=homegenie_log_" + migCommand.GetOption(1) + ".csv");
                    migCommand.Response = csvlog;
                }
                else if (migCommand.GetOption(0) == "SystemLogging.Enable")
                {
                    SystemLogger.Instance.OpenLog();
                    homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "true";
                    homegenie.SystemConfiguration.Update();
                }
                else if (migCommand.GetOption(0) == "SystemLogging.Disable")
                {
                    SystemLogger.Instance.CloseLog();
                    homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "false";
                    homegenie.SystemConfiguration.Update();
                }
                else if (migCommand.GetOption(0) == "SystemLogging.IsEnabled")
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.EnableLogFile.ToLower().Equals("true") ? "1" : "0"));
                }
                else if (migCommand.GetOption(0) == "Security.SetPassword")
                {
                    // password only for now, with fixed user login 'admin'
                    string pass = migCommand.GetOption(1) == "" ? "" : MIG.Utility.Encryption.SHA1.GenerateHashString(migCommand.GetOption(1));
                    homegenie.MigService.SetWebServicePassword(pass);
                    homegenie.SystemConfiguration.HomeGenie.UserPassword = pass;
                    // regenerate encrypted files
                    homegenie.SystemConfiguration.Update();
                    homegenie.UpdateModulesDatabase();
                }
                else if (migCommand.GetOption(0) == "Security.ClearPassword")
                {
                    homegenie.MigService.SetWebServicePassword("");
                    homegenie.SystemConfiguration.HomeGenie.UserPassword = "";
                    // regenerate encrypted files
                    homegenie.SystemConfiguration.Update();
                    homegenie.UpdateModulesDatabase();
                }
                else if (migCommand.GetOption(0) == "Security.HasPassword")
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.UserPassword != "" ? "1" : "0"));
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationRestore")
                {
                    // file uploaded by user
                    string archivename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "homegenie_restore_config.zip");
                    if (!Directory.Exists("tmp"))
                    {
                        Directory.CreateDirectory("tmp");
                    }
                    try
                    {
                        var downloadedMessageInfo = new DirectoryInfo("tmp");
                        foreach (var file in downloadedMessageInfo.GetFiles())
                        {
                            file.Delete();
                        }
                        foreach (DirectoryInfo directory in downloadedMessageInfo.GetDirectories())
                        {
                            directory.Delete(true);
                        }
                    }
                    catch
                    {
                    }
                    //
                    try
                    {
                        var    encoding = (request.Context as HttpListenerContext).Request.ContentEncoding;
                        string boundary = MIG.Gateways.WebServiceUtility.GetBoundary((request.Context as HttpListenerContext).Request.ContentType);
                        MIG.Gateways.WebServiceUtility.SaveFile(encoding, boundary, request.InputStream, archivename);
                        Utility.UncompressZip(archivename, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp"));
                        File.Delete(archivename);
                    }
                    catch
                    {
                    }
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS1")
                {
                    var serializer      = new XmlSerializer(typeof(List <ProgramBlock>));
                    var reader          = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs.xml"));
                    var newProgramsData = (List <ProgramBlock>)serializer.Deserialize(reader);
                    reader.Close();
                    var newProgramList = new List <ProgramBlock>();
                    foreach (ProgramBlock program in newProgramsData)
                    {
                        if (program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START)
                        {
                            ProgramBlock p = new ProgramBlock();
                            p.Address     = program.Address;
                            p.Name        = program.Name;
                            p.Description = program.Description;
                            newProgramList.Add(p);
                        }
                    }
                    newProgramList.Sort(delegate(ProgramBlock p1, ProgramBlock p2)
                    {
                        string c1 = p1.Address.ToString();
                        string c2 = p2.Address.ToString();
                        return(c1.CompareTo(c2));
                    });
                    migCommand.Response = JsonConvert.SerializeObject(newProgramList);
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS2")
                {
                    var serializer       = new XmlSerializer(typeof(List <Group>));
                    var reader           = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "automationgroups.xml"));
                    var automationGroups = (List <Group>)serializer.Deserialize(reader);
                    reader.Close();
                    //
                    foreach (var automationGroup in automationGroups)
                    {
                        if (homegenie.AutomationGroups.Find(g => g.Name == automationGroup.Name) == null)
                        {
                            homegenie.AutomationGroups.Add(automationGroup);
                        }
                    }
                    //
                    homegenie.UpdateGroupsDatabase("Automation");
                    //
                    //File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "automationgroups.xml"), "./automationgroups.xml", true);
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "groups.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "groups.xml"), true);
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "lircconfig.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lircconfig.xml"), true);
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "modules.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules.xml"), true);
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "scheduler.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "scheduler.xml"), true);
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "systemconfig.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml"), true);
                    //
                    homegenie.LoadConfiguration();
                    //
                    // Restore automation programs
                    string selectedPrograms = migCommand.GetOption(1);
                    serializer = new XmlSerializer(typeof(List <ProgramBlock>));
                    reader     = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs.xml"));
                    var newProgramsData = (List <ProgramBlock>)serializer.Deserialize(reader);
                    reader.Close();
                    foreach (var program in newProgramsData)
                    {
                        var currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == program.Address);
                        program.IsRunning = false;
                        // Only restore user space programs
                        if (selectedPrograms.Contains("," + program.Address.ToString() + ",") && program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START)
                        {
                            int oldPid = program.Address;
                            if (currentProgram == null)
                            {
                                var newPid = ((currentProgram != null && currentProgram.Address == program.Address) ? homegenie.ProgramEngine.GeneratePid() : program.Address);
                                try
                                {
                                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", newPid + ".dll"), true);
                                }
                                catch
                                {
                                }
                                program.Address = newPid;
                                homegenie.ProgramEngine.ProgramAdd(program);
                            }
                            else if (currentProgram != null)
                            {
                                homegenie.ProgramEngine.ProgramRemove(currentProgram);
                                try
                                {
                                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", program.Address + ".dll"), true);
                                }
                                catch
                                {
                                }
                                homegenie.ProgramEngine.ProgramAdd(program);
                            }
                            // Restore Arduino program folder ...
                            // TODO: this is untested yet...
                            if (program.Type.ToLower() == "arduino")
                            {
                                string sourceFolder  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs", "arduino", oldPid.ToString());
                                string arduinoFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", "arduino", program.Address.ToString());
                                if (Directory.Exists(arduinoFolder))
                                {
                                    Directory.Delete(arduinoFolder, true);
                                }
                                Directory.CreateDirectory(arduinoFolder);
                                foreach (string newPath in Directory.GetFiles(sourceFolder))
                                {
                                    File.Copy(newPath, newPath.Replace(sourceFolder, arduinoFolder), true);
                                }
                            }
                        }
                        else if (currentProgram != null && program.Address < ProgramEngine.USER_SPACE_PROGRAMS_START)
                        {
                            // Only restore Enabled/Disabled status of system programs
                            currentProgram.IsEnabled = program.IsEnabled;
                        }
                    }
                    //
                    homegenie.UpdateProgramsDatabase();
                    //
                    // regenerate encrypted files
                    homegenie.UpdateModulesDatabase();
                    homegenie.SystemConfiguration.Update();
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationReset")
                {
                    homegenie.RestoreFactorySettings();
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationBackup")
                {
                    homegenie.BackupCurrentSettings();
                    (request.Context as HttpListenerContext).Response.Redirect("/hg/html/homegenie_backup_config.zip");
                }
                else if (migCommand.GetOption(0) == "System.ConfigurationLoad")
                {
                    homegenie.LoadConfiguration();
                }
                break;

            case "Modules.Get":
                try
                {
                    var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1));
                    migCommand.Response = Utility.Module2Json(module, false);
                }
                catch (Exception ex)
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace);
                }
                break;

            case "Modules.List":
                try
                {
                    homegenie.modules_Sort();
                    migCommand.Response = homegenie.GetJsonSerializedModules(migCommand.GetOption(0).ToLower() == "short");
                }
                catch (Exception ex)
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace);
                }
                break;

            case "Modules.RoutingReset":
                try
                {
                    for (int m = 0; m < homegenie.Modules.Count; m++)
                    {
                        homegenie.Modules[m].RoutingNode = "";
                    }
                    migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                }
                catch (Exception ex)
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace);
                }
                break;

            case "Modules.Save":
                string body       = new StreamReader(request.InputStream).ReadToEnd();
                var    newModules = JsonConvert.DeserializeObject(body) as JArray;
                for (int i = 0; i < newModules.Count; i++)
                {
                    try
                    {
                        var module = homegenie.Modules.Find(m => m.Address == newModules[i]["Address"].ToString() && m.Domain == newModules[i]["Domain"].ToString());
                        module.Name = newModules[i]["Name"].ToString();
                        //
                        try
                        {
                            module.DeviceType = (MIG.ModuleTypes)Enum.Parse(typeof(MIG.ModuleTypes), newModules[i]["DeviceType"].ToString(), true);
                        }
                        catch
                        {
                            // TODO: check what's wrong here...
                        }
                        //
                        var moduleProperties = newModules[i]["Properties"] as JArray;
                        for (int p = 0; p < moduleProperties.Count; p++)
                        {
                            string          propertyName  = moduleProperties[p]["Name"].ToString();
                            string          propertyValue = moduleProperties[p]["Value"].ToString();
                            ModuleParameter parameter     = null;
                            parameter = module.Properties.Find(delegate(ModuleParameter mp)
                            {
                                return(mp.Name == propertyName);
                            });
                            //
                            if (propertyName == ModuleParameters.MODPAR_VIRTUALMETER_WATTS)
                            {
                                try
                                {
                                    propertyValue = double.Parse(propertyValue.Replace(",", "."), System.Globalization.CultureInfo.InvariantCulture).ToString();
                                }
                                catch
                                {
                                    propertyValue = "0";
                                }
                            }
                            //
                            if (parameter == null)
                            {
                                module.Properties.Add(new ModuleParameter()
                                {
                                    Name  = propertyName,
                                    Value = propertyValue
                                });
                            }
                            else
                            {
                                if (moduleProperties[p]["NeedsUpdate"] != null && moduleProperties[p]["NeedsUpdate"].ToString() == "true")
                                {
                                    parameter.Value = propertyValue;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //TODO: notify exception?
                    }
                }
                homegenie.UpdateModulesDatabase();//write modules
                break;

            case "Modules.Update":
                string streamContent = new StreamReader(request.InputStream).ReadToEnd();
                var    newModule     = JsonConvert.DeserializeObject <Module>(streamContent);
                var    currentModule = homegenie.Modules.Find(p => p.Domain == newModule.Domain && p.Address == newModule.Address);
                //
                if (currentModule == null)
                {
                    homegenie.Modules.Add(newModule);
                }
                else
                {
                    currentModule.Name        = newModule.Name;
                    currentModule.Description = newModule.Description;
                    currentModule.DeviceType  = newModule.DeviceType;
                    foreach (var newParameter in newModule.Properties)
                    {
                        var currentParameter = currentModule.Properties.Find(mp => mp.Name == newParameter.Name);
                        if (currentParameter == null)
                        {
                            currentModule.Properties.Add(newParameter);
                        }
                        else if (newParameter.NeedsUpdate)
                        {
                            currentParameter.Value = newParameter.Value;
                        }
                    }
                    // look for deleted properties
                    var deletedParameters = new List <ModuleParameter>();
                    foreach (var parameter in currentModule.Properties)
                    {
                        var currentParameter = newModule.Properties.Find(mp => mp.Name == parameter.Name);
                        if (currentParameter == null)
                        {
                            deletedParameters.Add(parameter);
                        }
                    }
                    foreach (var parameter in deletedParameters)
                    {
                        currentModule.Properties.Remove(parameter);
                    }
                    deletedParameters.Clear();
                }
                //
                homegenie.UpdateModulesDatabase();
                break;

            case "Modules.Delete":
                var deletedModule = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1));
                if (deletedModule != null)
                {
                    homegenie.Modules.Remove(deletedModule);
                }
                migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                //
                homegenie.UpdateModulesDatabase();
                break;

            case "Groups.ModulesList":
                var theGroup = homegenie.Groups.Find(z => z.Name.ToLower() == migCommand.GetOption(0).Trim().ToLower());
                if (theGroup != null)
                {
                    string jsonmodules = "[";
                    for (int m = 0; m < theGroup.Modules.Count; m++)
                    {
                        var groupModule = homegenie.Modules.Find(mm => mm.Domain == theGroup.Modules[m].Domain && mm.Address == theGroup.Modules[m].Address);
                        if (groupModule != null)
                        {
                            jsonmodules += Utility.Module2Json(groupModule, false) + ",\n";
                        }
                    }
                    jsonmodules         = jsonmodules.TrimEnd(',', '\n');
                    jsonmodules        += "]";
                    migCommand.Response = jsonmodules;
                }
                break;

            case "Groups.List":
                try
                {
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0)));
                }
                catch (Exception ex)
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace);
                }
                break;

            case "Groups.Rename":
                string oldName      = migCommand.GetOption(1);
                string newName      = new StreamReader(request.InputStream).ReadToEnd();
                var    currentGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == oldName);
                var    newGroup     = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == newName);
                // ensure that the new group name is not already defined
                if (newGroup == null && currentGroup != null)
                {
                    currentGroup.Name = newName;
                    homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));
                    //cmd.response = JsonHelper.GetSimpleResponse("OK");
                }
                else
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("New name already in use.");
                }
                break;

            case "Groups.Sort":
                using (var reader = new StreamReader(request.InputStream))
                {
                    var      newGroupList     = new List <Group>();
                    string[] newPositionOrder = reader.ReadToEnd().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < newPositionOrder.Length; i++)
                    {
                        newGroupList.Add(homegenie.GetGroups(migCommand.GetOption(0))[int.Parse(newPositionOrder[i])]);
                    }
                    homegenie.GetGroups(migCommand.GetOption(0)).Clear();
                    homegenie.GetGroups(migCommand.GetOption(0)).RemoveAll(g => true);
                    homegenie.GetGroups(migCommand.GetOption(0)).AddRange(newGroupList);
                    homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));
                }
                //
                try
                {
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0)));
                }
                catch (Exception ex)
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace);
                }
                break;

            case "Groups.SortModules":
                using (var reader = new StreamReader(request.InputStream))
                {
                    string groupName = migCommand.GetOption(1);
                    Group  sortGroup = null;
                    try
                    {
                        sortGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == groupName);
                    }
                    catch
                    {
                    }
                    //
                    if (sortGroup != null)
                    {
                        var      newModulesReference = new List <ModuleReference>();
                        string[] newPositionOrder    = reader.ReadToEnd().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < newPositionOrder.Length; i++)
                        {
                            newModulesReference.Add(sortGroup.Modules[int.Parse(newPositionOrder[i])]);
                        }
                        sortGroup.Modules.Clear();
                        sortGroup.Modules = newModulesReference;
                        homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));
                    }
                }

                try
                {
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0)));
                }
                catch (Exception ex)
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace);
                }
                break;

            case "Groups.Add":
                string newGroupName = new StreamReader(request.InputStream).ReadToEnd();
                homegenie.GetGroups(migCommand.GetOption(0)).Add(new Group()
                {
                    Name = newGroupName
                });
                homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups
                break;

            case "Groups.Delete":
                string deletedGroupName = new StreamReader(request.InputStream).ReadToEnd();
                Group  deletedGroup     = null;
                try
                {
                    deletedGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == deletedGroupName);
                }
                catch
                {
                }
                //
                if (deletedGroup != null)
                {
                    homegenie.GetGroups(migCommand.GetOption(0)).Remove(deletedGroup);
                    homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups
                    if (migCommand.GetOption(0).ToLower() == "automation")
                    {
                        var groupPrograms = homegenie.ProgramEngine.Programs.FindAll(p => p.Group.ToLower() == deletedGroup.Name.ToLower());
                        if (groupPrograms != null)
                        {
                            // delete group association from programs
                            foreach (ProgramBlock program in groupPrograms)
                            {
                                program.Group = "";
                            }
                        }
                    }
                }
                break;

            case "Groups.Save":
                string jsonGroups = new StreamReader(request.InputStream).ReadToEnd();
                var    newGroups  = JsonConvert.DeserializeObject <List <Group> >(jsonGroups);
                for (int i = 0; i < newGroups.Count; i++)
                {
                    try
                    {
                        var group = homegenie.Groups.Find(z => z.Name == newGroups[i].Name);
                        group.Modules.Clear();
                        group.Modules = newGroups[i].Modules;
                    }
                    catch
                    {
                    }
                }
                homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups
                break;

            case "Widgets.List":
                List <string> widgetsList = new List <string>();
                var           groups      = Directory.GetDirectories(widgetBasePath);
                for (int d = 0; d < groups.Length; d++)
                {
                    var categories = Directory.GetDirectories(groups[d]);
                    for (int c = 0; c < categories.Length; c++)
                    {
                        var widgets  = Directory.GetFiles(categories[c], "*.js");
                        var group    = groups[d].Replace(widgetBasePath, "").Substring(1);
                        var category = categories[c].Replace(groups[d], "").Substring(1);
                        for (int w = 0; w < widgets.Length; w++)
                        {
                            widgetsList.Add(group + "/" + category + "/" + Path.GetFileNameWithoutExtension(widgets[w]));
                        }
                    }
                }
                migCommand.Response = JsonConvert.SerializeObject(widgetsList);
                break;

            case "Widgets.Add":
            {
                string   response    = "ERROR";
                string   widgetPath  = migCommand.GetOption(0);  // eg. homegenie/generic/dimmer
                string[] widgetParts = widgetPath.Split('/');
                widgetParts[0] = new String(widgetParts[0].Where(Char.IsLetter).ToArray()).ToLower();
                widgetParts[1] = new String(widgetParts[1].Where(Char.IsLetter).ToArray()).ToLower();
                widgetParts[2] = new String(widgetParts[2].Where(Char.IsLetter).ToArray()).ToLower();
                if (!String.IsNullOrWhiteSpace(widgetParts[0]) && !String.IsNullOrWhiteSpace(widgetParts[1]) && !String.IsNullOrWhiteSpace(widgetParts[2]))
                {
                    string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]);
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    // copy widget template into the new widget
                    var htmlFile = Path.Combine(filePath, widgetParts[2] + ".html");
                    var jsFile   = Path.Combine(filePath, widgetParts[2] + ".js");
                    if (!File.Exists(htmlFile) && !File.Exists(jsFile))
                    {
                        File.Copy(Path.Combine(widgetBasePath, "template.html"), htmlFile);
                        File.Copy(Path.Combine(widgetBasePath, "template.js"), jsFile);
                        response = "OK";
                    }
                }
                migCommand.Response = JsonHelper.GetSimpleResponse(response);
            }
            break;

            case "Widgets.Save":
            {
                string   response    = "ERROR";
                string   widgetData  = new StreamReader(request.InputStream).ReadToEnd();
                string   fileType    = migCommand.GetOption(0);
                string   widgetPath  = migCommand.GetOption(1);  // eg. homegenie/generic/dimmer
                string[] widgetParts = widgetPath.Split('/');
                string   filePath    = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                switch (fileType)
                {
                // html/javascript source
                case "html":
                case "js":
                    using (TextWriter widgetWriter = new StreamWriter(Path.Combine(filePath, widgetParts[2] + "." + fileType)))
                    {
                        widgetWriter.Write(widgetData);
                    }
                    response = "OK";
                    break;

                // style sheet file
                case "css":
                    break;

                // locale file
                case "json":
                    break;

                // image file
                case "jpg":
                case "png":
                case "gif":
                    break;
                }
                migCommand.Response = JsonHelper.GetSimpleResponse(response);
            }
            break;

            case "Widgets.Delete":
            {
                string   response    = "ERROR";
                string   widgetPath  = migCommand.GetOption(0);  // eg. homegenie/generic/dimmer
                string[] widgetParts = widgetPath.Split('/');
                string   filePath    = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1], widgetParts[2] + ".");
                if (File.Exists(filePath + "html"))
                {
                    File.Delete(filePath + "html");
                    response = "OK";
                }
                if (File.Exists(filePath + "js"))
                {
                    File.Delete(filePath + "js");
                    response = "OK";
                }
                migCommand.Response = JsonHelper.GetSimpleResponse(response);
            }
            break;

            case "Widgets.Export":
            {
                string   widgetPath   = migCommand.GetOption(0); // eg. homegenie/generic/dimmer
                string[] widgetParts  = widgetPath.Split('/');
                string   widgetBundle = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "export", widgetPath.Replace('/', '_') + ".zip");
                if (File.Exists(widgetBundle))
                {
                    File.Delete(widgetBundle);
                }
                else if (!Directory.Exists(Path.GetDirectoryName(widgetBundle)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(widgetBundle));
                }
                string inputPath    = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]);
                string outputPath   = Path.Combine(widgetParts[0], widgetParts[1]);
                string infoFilePath = Path.Combine(inputPath, "widget.info");
                File.WriteAllText(infoFilePath, "HomeGenie exported widget.");
                Utility.AddFileToZip(widgetBundle, infoFilePath, "widget.info");
                Utility.AddFileToZip(widgetBundle, Path.Combine(inputPath, widgetParts[2] + ".html"), Path.Combine(outputPath, widgetParts[2] + ".html"));
                Utility.AddFileToZip(widgetBundle, Path.Combine(inputPath, widgetParts[2] + ".js"), Path.Combine(outputPath, widgetParts[2] + ".js"));
                //
                byte[] bundleData = File.ReadAllBytes(widgetBundle);
                (request.Context as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment; filename=\"" + widgetPath.Replace('/', '_') + ".zip\"");
                (request.Context as HttpListenerContext).Response.OutputStream.Write(bundleData, 0, bundleData.Length);
            }
            break;

            case "Widgets.Import":
            {
                var    encoding    = (request.Context as HttpListenerContext).Request.ContentEncoding;
                string boundary    = MIG.Gateways.WebServiceUtility.GetBoundary((request.Context as HttpListenerContext).Request.ContentType);
                string archiveFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "import_widget.zip");
                string importPath  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "import");
                if (Directory.Exists(importPath))
                {
                    Directory.Delete(importPath, true);
                }
                MIG.Gateways.WebServiceUtility.SaveFile(encoding, boundary, request.InputStream, archiveFile);
                // TODO: should extract to temporary folder and look for widget.info data file before copying anything
                List <string> extractedFiles = Utility.UncompressZip(archiveFile, importPath);
                if (File.Exists(Path.Combine(importPath, "widget.info")))
                {
                    foreach (string f in extractedFiles)
                    {
                        if (f.EndsWith(".html") || f.EndsWith(".js"))
                        {
                            string destFolder = Path.Combine(widgetBasePath, Path.GetDirectoryName(f));
                            if (!Directory.Exists(destFolder))
                            {
                                Directory.CreateDirectory(destFolder);
                            }
                            File.Copy(Path.Combine(importPath, f), Path.Combine(widgetBasePath, f), true);
                        }
                    }
                    //migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                }
                else
                {
                    //migCommand.Response = JsonHelper.GetSimpleResponse("ERROR");
                }
            }
            break;

            case "Widgets.Parse":
            {
                string widgetData = new StreamReader(request.InputStream).ReadToEnd();
                var    parser     = new JavaScriptParser();
                try
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                    parser.Parse(widgetData);
                }
                catch (Jint.Parser.ParserException e)
                {
                    migCommand.Response = JsonHelper.GetSimpleResponse("ERROR (" + e.LineNumber + "," + e.Column + "): " + e.Description);
                }
            }
            break;
            }
        }
Пример #44
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string returnValue = "";
            bool raisePropertyChanged = false;
            string parameterPath = "Status.Level";
            string raiseParameter = "";
            //
            string nodeId = request.NodeId;
            Command command = (Command)request.Command;
            ////----------------------
            try
            {
                if (command == Command.CONTROLLER_DISCOVERY)
                {
                    controller.Discovery();
                }

                //--------------////---------------------- DEPRECATE THESE  ----------------------------
                //else if (command == Command.CONTROLLER_AUTOREPORTSET)
                //{
                //    _controller.AutoReportSet((byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                //}
                //else
                if (command == Command.BASIC_REPORT || command.ToString() == "Meter.Get") // TODO .. FIX: this is not basic report, it's a meter get
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.RequestMeterReport();
                }
                else if (command == Command.MULTILEVEL_REPORT) // TODO this one call for having SwitchMultiLevel and SensorMultiLevel reports
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.RequestMultiLevelReport();
                }
                //--------------////--------------------------------------------------------------------

                else if (command == Command.CONTROLLER_NODEADD)
                {
                    lastAddedNode = 0;
                    byte addedId = controller.BeginNodeAdd();
                    for (int i = 0; i < 20; i++)
                    {
                        if (lastAddedNode > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    controller.StopNodeAdd();
                    //
                    returnValue = lastAddedNode.ToString();
                }
                else if (command == Command.CONTROLLER_NODEREMOVE)
                {
                    lastRemovedNode = 0;
                    byte remcid = controller.BeginNodeRemove();
                    for (int i = 0; i < 20; i++)
                    {
                        if (lastRemovedNode > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    controller.StopNodeRemove();
                    //
                    returnValue = lastRemovedNode.ToString();
                }
                ////----------------------
                else if (command == Command.BASIC_SET)
                {
                    raisePropertyChanged = true;
                    double raiseValue = double.Parse(request.GetOption(0)) / 100;
                    if (raiseValue > 1) raiseValue = 1;
                    raiseParameter = raiseValue.ToString(System.Globalization.CultureInfo.InvariantCulture);
                    //
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Basic_Set((byte)int.Parse(request.GetOption(0)));
                }
                else if (command == Command.BASIC_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Basic_Get();
                }
                ////-----------------------
                else if (command == Command.MULTIINSTANCE_GETCOUNT)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    //
                    switch (request.GetOption(0))
                    {
                        case "Switch.Binary":
                            node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SWITCH_BINARY);
                            break;
                        case "Switch.MultiLevel":
                            node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SWITCH_MULTILEVEL);
                            break;
                        case "Sensor.Binary":
                            node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SENSOR_BINARY);
                            break;
                        case "Sensor.MultiLevel":
                            node.MultiInstance_GetCount((byte)ZWaveLib.CommandClass.COMMAND_CLASS_SENSOR_MULTILEVEL);
                            break;
                    }
                }
                else if (command == Command.MULTIINSTANCE_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
                    //
                    switch (request.GetOption(0))
                    {
                        case "Switch.Binary":
                            node.MultiInstance_SwitchBinaryGet(instance);
                            break;
                        case "Switch.MultiLevel":
                            node.MultiInstance_SwitchMultiLevelGet(instance);
                            break;
                        case "Sensor.Binary":
                            node.MultiInstance_SensorBinaryGet(instance);
                            break;
                        case "Sensor.MultiLevel":
                            node.MultiInstance_SensorMultiLevelGet(instance);
                            break;
                    }
                }
                else if (command == Command.MULTIINSTANCE_SET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    byte instance = (byte)int.Parse(request.GetOption(1)); // parameter index
                    int value = int.Parse(request.GetOption(2));
                    //
                    //raisepropchanged = true;
                    //parampath += "." + instance; // Status.Level.<instance>
                    //
                    switch (request.GetOption(0))
                    {
                        case "Switch.Binary":
                            node.MultiInstance_SwitchBinarySet(instance, value);
                            //raiseparam = (double.Parse(request.GetOption(2)) / 255).ToString();
                            break;
                        case "Switch.MultiLevel":
                            node.MultiInstance_SwitchMultiLevelSet(instance, value);
                            //raiseparam = (double.Parse(request.GetOption(2)) / 100).ToString(); // TODO: should it be 99 ?
                            break;
                    }
                }
                else if (command == Command.NODEINFO_GET)
                {
                    ZWaveController.GetNodeInformationFrame((byte)int.Parse(nodeId));
                }
                ////-----------------------
                else if (command == Command.BATTERY_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Battery_Get();
                }
                ////-----------------------
                else if (command == Command.ASSOCIATION_SET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Association_Set((byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                }
                else if (command == Command.ASSOCIATION_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Association_Get((byte)int.Parse(request.GetOption(0))); // groupid
                }
                else if (command == Command.ASSOCIATION_REMOVE)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.Association_Remove((byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1))); // groupid
                }
                ////-----------------------
                else if (command == Command.MANUFACTURERSPECIFIC_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.ManufacturerSpecific_Get();
                }
                ////------------------
                else if (command == Command.CONFIG_PARAMETERSET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    //byte[] value = new byte[] { (byte)int.Parse(option1) };//BitConverter.GetBytes(Int16.Parse(option1));
                    //Array.Reverse(value);
                    node.ConfigParameterSet((byte)int.Parse(request.GetOption(0)), int.Parse(request.GetOption(1)));
                }
                else if (command == Command.CONFIG_PARAMETERGET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.ConfigParameterGet((byte)int.Parse(request.GetOption(0)));
                }
                ////------------------
                else if (command == Command.WAKEUP_GET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.WakeUpGetInterval();
                }
                else if (command == Command.WAKEUP_SET)
                {
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    node.WakeUpSetInterval(uint.Parse(request.GetOption(0)));
                }
                ////------------------
                else if (command == Command.CONTROL_ON)
                {
                    raisePropertyChanged = true;
                    raiseParameter = "1";
                    //
                    // Basic.Set 0xFF
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).On();
                }
                else if (command == Command.CONTROL_OFF)
                {
                    raisePropertyChanged = true;
                    raiseParameter = "0";
                    //
                    // Basic.Set 0x00
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).Off();
                }
                else if (command == Command.CONTROL_LEVEL)
                {
                    raisePropertyChanged = true;
                    raiseParameter = (double.Parse(request.GetOption(0)) / 100).ToString();
                    //
                    // Basic.Set <level>
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Dimmer)node.DeviceHandler).Level = int.Parse(request.GetOption(0));
                }
                else if (command == Command.CONTROL_TOGGLE)
                {
                    raisePropertyChanged = true;
                    //
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    if (((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).Level == 0)
                    {
                        raiseParameter = "1";
                        // Basic.Set 0xFF
                        ((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).On();
                    }
                    else
                    {
                        raiseParameter = "0";
                        // Basic.Set 0x00
                        ((ZWaveLib.Devices.ProductHandlers.Generic.Switch)node.DeviceHandler).Off();
                    }
                }
                else if (command == Command.THERM_MODE)
                {
                    raisePropertyChanged = true;
                    raiseParameter = (double.Parse(request.GetOption(0)) / 100).ToString();
                    //
                    // Basic.Set <level>
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    int mode = int.Parse(request.GetOption(0));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermModeSet(mode);
                }
                else if (command == Command.THERM_TEMP)
                {
                    raisePropertyChanged = true;
                    raiseParameter = (double.Parse(request.GetOption(0)) / 100).ToString();
                    //
                    // Basic.Set <level>
                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    int mode = int.Parse(request.GetOption(0));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermTempSet(mode);
                }
                else if (command == Command.THERM_GET_MODE)
                {
                    raisePropertyChanged = true;

                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermModeGet();
                }
                else if (command == Command.THERM_GET_FAN_MODE)
                {
                    raisePropertyChanged = true;

                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermFanModeGet();
                }
                else if (command == Command.THERM_GET_FAN_STATE)
                {
                    raisePropertyChanged = true;

                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermFanStateGet();
                }
                else if (command == Command.THERM_GET_SET_POINT)
                {
                    raisePropertyChanged = true;

                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermSetpointGet();
                }
                else if (command == Command.THERM_SET_FAN_MODE)
                {
                    raisePropertyChanged = true;

                    var node = controller.GetDevice((byte)int.Parse(nodeId));
                    int mode = int.Parse(request.GetOption(0));
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermFanModeSet(mode);
                }
                else if (command == Command.THERM_GET_ALL)
                {
                    raisePropertyChanged = true;

                    var node = controller.GetDevice((byte)int.Parse(nodeId));

                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermSetpointGet();
                    Thread.Sleep(200);
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermFanStateGet();
                    Thread.Sleep(200);
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermFanModeGet();
                    Thread.Sleep(200);
                    ((ZWaveLib.Devices.ProductHandlers.Generic.Thermostat)node.DeviceHandler).thermModeGet();
                    Thread.Sleep(200);
                    node.RequestMultiLevelReport();
                }

            }
            catch
            {
                if (raiseParameter != "") raisePropertyChanged = true;
            }
            //
            if (raisePropertyChanged && InterfacePropertyChangedAction != null)
            {
                try
                {
                    //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction() { Domain = this.Domain, SourceId = nodeId, SourceType = "ZWave Node", Path = parameterPath, Value = raiseParameter });
                }
                catch
                {
                }
            }
            //
            return returnValue;
        }
Пример #45
0
 public object InterfaceControl(MIGInterfaceCommand request)
 {
     request.Response = ""; //default success value
     //
     if (request.Command == Command.REMOTES_SEARCH)
     {
         request.Response = JsonConvert.SerializeObject(
             SearchRemotes(request.GetOption(0)),
             Formatting.Indented
         );
     }
     else if (request.Command == Command.REMOTES_ADD)
     {
         var remote = remotesData.Find(r => r.Manufacturer.ToLower() == request.GetOption(0).ToLower() && r.Model.ToLower() == request.GetOption(1).ToLower());
         if (remote != null && remotesConfig.Find(r => r.Model.ToLower() == remote.Model.ToLower() && r.Manufacturer.ToLower() == remote.Manufacturer.ToLower()) == null)
         {
             var webClient = new WebClient();
             string config = webClient.DownloadString("http://lirc.sourceforge.net/remotes/" + remote.Manufacturer + "/" + remote.Model);
             remote.Configuration = GetBytes(config);
             remotesConfig.Add(remote);
             SaveConfig();
         }
     }
     else if (request.Command == Command.REMOTES_REMOVE)
     {
         var remote = remotesConfig.Find(r => r.Manufacturer.ToLower() == request.GetOption(0).ToLower() && r.Model.ToLower() == request.GetOption(1).ToLower());
         if (remote != null)
         {
             remotesConfig.Remove(remote);
             SaveConfig();
         }
     }
     else if (request.Command == Command.REMOTES_LIST)
     {
         request.Response = JsonConvert.SerializeObject(remotesConfig, Formatting.Indented);
     }
     else if (request.Command == Command.CONTROL_IRSEND)
     {
         string commands = "";
         int c = 0;
         while (request.GetOption(c) != "")
         {
             var options = request.GetOption(c).Split('/');
             foreach (string o in options)
             {
                 commands += "\"" + o + "\" ";
             }
             c++;
         }
         ShellCommand("irsend", "SEND_ONCE " + commands);
     }
     //
     return request.Response;
 }
Пример #46
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string response = "[{ ResponseValue : 'OK' }]";

            string nodeId  = request.NodeId;
            var    command = (Command)request.Command;
            string option  = request.GetOption(0);

            // Parse house/unit
            var houseCode = XTenLib.Utility.HouseCodeFromString(nodeId);
            var unitCode  = XTenLib.Utility.UnitCodeFromString(nodeId);

            // Modules control
            if (command == Command.PARAMETER_STATUS)
            {
                x10lib.StatusRequest(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_ON)
            {
                x10lib.LightOn(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_OFF)
            {
                x10lib.LightOff(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_BRIGHT)
            {
                x10lib.Bright(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_DIM)
            {
                x10lib.Dim(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_LEVEL)
            {
                int dimvalue = int.Parse(option) - (int)(x10lib.ModulesStatus[nodeId].Level * 100.0);
                if (dimvalue > 0)
                {
                    x10lib.Bright(houseCode, unitCode, dimvalue);
                }
                else if (dimvalue < 0)
                {
                    x10lib.Dim(houseCode, unitCode, -dimvalue);
                }
            }
            else if (command == Command.CONTROL_TOGGLE)
            {
                string huc = XTenLib.Utility.HouseUnitCodeFromEnum(houseCode, unitCode);
                if (x10lib.ModulesStatus[huc].Level == 0)
                {
                    x10lib.LightOn(houseCode, unitCode);
                }
                else
                {
                    x10lib.LightOff(houseCode, unitCode);
                }
            }
            else if (command == Command.CONTROL_ALLLIGHTSON)
            {
                x10lib.AllLightsOn(houseCode);
            }
            else if (command == Command.CONTROL_ALLLIGHTSOFF)
            {
                x10lib.AllUnitsOff(houseCode);
            }//
            return(response);
        }
Пример #47
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string returnValue = "";
            bool raisePropertyChanged = false;
            string parameterPath = "Status.Unhandled";
            string raiseParameter = "";
            //
            var device = GetUpnpDevice(request.NodeId);

            //////////////////// Commands: SwitchPower, Dimming
            if (request.Command == Command.CONTROL_ON || request.Command == Command.CONTROL_OFF)
            {
                bool commandValue = (request.Command == Command.CONTROL_ON ? true : false);
                var newValue = new UPnPArgument("newTargetValue", commandValue);
                var args = new UPnPArgument[] {
                    newValue
                };
                InvokeUpnpDeviceService(device, "SwitchPower", "SetTarget", args);
                //
                raisePropertyChanged = true;
                parameterPath = "Status.Level";
                raiseParameter = (commandValue ? "1" : "0");
            }
            else if (request.Command == Command.CONTROL_LEVEL)
            {
                var newvalue = new UPnPArgument("NewLoadLevelTarget", (byte)uint.Parse(request.GetOption(0)));
                var args = new UPnPArgument[] {
                    newvalue
                };
                InvokeUpnpDeviceService(device, "Dimming", "SetLoadLevelTarget", args);
                //
                raisePropertyChanged = true;
                parameterPath = "Status.Level";
                raiseParameter = (double.Parse(request.GetOption(0)) / 100d).ToString(System.Globalization.CultureInfo.InvariantCulture);
            }
            else if (request.Command == Command.CONTROL_TOGGLE)
            {
            }
            //////////////////// Commands: Browse, AVTransport
            else if (request.Command == Command.AVMEDIA_GETURI)
            {
                string deviceId = request.NodeId;
                string id = request.GetOption(0);
                //
                var objectId = new UPnPArgument("ObjectID", id);
                var flags = new UPnPArgument("BrowseFlag", "BrowseMetadata");
                var filter = new UPnPArgument(
                                 "Filter",
                                 "upnp:album,upnp:artist,upnp:genre,upnp:title,res@size,res@duration,res@bitrate,res@sampleFrequency,res@bitsPerSample,res@nrAudioChannels,res@protocolInfo,res@protection,res@importUri"
                             );
                var startIndex = new UPnPArgument("StartingIndex", (uint)0);
                var requestedCount = new UPnPArgument("RequestedCount", (uint)1);
                var sortCriteria = new UPnPArgument("SortCriteria", "");
                //
                var result = new UPnPArgument("Result", "");
                var returnedNumber = new UPnPArgument("NumberReturned", "");
                var totalMatches = new UPnPArgument("TotalMatches", "");
                var updateId = new UPnPArgument("UpdateID", "");
                //
                InvokeUpnpDeviceService(device, "ContentDirectory", "Browse", new UPnPArgument[] {
                    objectId,
                    flags,
                    filter,
                    startIndex,
                    requestedCount,
                    sortCriteria,
                    result,
                    returnedNumber,
                    totalMatches,
                    updateId
                });
                //
                try
                {
                    string ss = result.DataValue.ToString();
                    var item = XDocument.Parse(ss, LoadOptions.SetBaseUri).Descendants().Where(ii => ii.Name.LocalName == "item").First();
                    //
                    foreach (var i in item.Elements())
                    {
                        var protocolUri = i.Attribute("protocolInfo");
                        if (protocolUri != null)
                        {
                            returnValue = i.Value;
                            break;
                        }
                    }
                }
                catch
                {
                }

            }
            else if (request.Command == Command.AVMEDIA_BROWSE)
            {
                string deviceId = request.NodeId;
                string id = request.GetOption(0);
                //
                var objectId = new UPnPArgument("ObjectID", id);
                var flags = new UPnPArgument("BrowseFlag", "BrowseDirectChildren");
                var filter = new UPnPArgument(
                                 "Filter",
                                 "upnp:album,upnp:artist,upnp:genre,upnp:title,res@size,res@duration,res@bitrate,res@sampleFrequency,res@bitsPerSample,res@nrAudioChannels,res@protocolInfo,res@protection,res@importUri"
                             );
                var startIndex = new UPnPArgument("StartingIndex", (uint)0);
                var requestedCount = new UPnPArgument("RequestedCount", (uint)0);
                var sortCriteria = new UPnPArgument("SortCriteria", "");
                //
                var result = new UPnPArgument("Result", "");
                var returnedNumber = new UPnPArgument("NumberReturned", "");
                var totalMatches = new UPnPArgument("TotalMatches", "");
                var updateId = new UPnPArgument("UpdateID", "");
                //
                InvokeUpnpDeviceService(device, "ContentDirectory", "Browse", new UPnPArgument[] {
                    objectId,
                    flags,
                    filter,
                    startIndex,
                    requestedCount,
                    sortCriteria,
                    result,
                    returnedNumber,
                    totalMatches,
                    updateId
                });
                //
                try
                {
                    string ss = result.DataValue.ToString();
                    var root = XDocument.Parse(ss, LoadOptions.SetBaseUri).Elements();
                    //
                    string jsonres = "[";
                    foreach (var i in root.Elements())
                    {
                        string itemId = i.Attribute("id").Value;
                        string itemTitle = i.Descendants().Where(n => n.Name.LocalName == "title").First().Value;
                        string itemClass = i.Descendants().Where(n => n.Name.LocalName == "class").First().Value;
                        jsonres += "{ \"Id\" : \"" + itemId + "\", \"Title\" : \"" + itemTitle.Replace("\"", "\\\"") + "\", \"Class\" : \"" + itemClass + "\" },\n";
                    }
                    jsonres = jsonres.TrimEnd(',', '\n') + "]";
                    //
                    returnValue = jsonres;
                }
                catch
                {
                }

            }
            else if (request.Command == Command.AVMEDIA_GETTRANSPORTINFO)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var transportState = new UPnPArgument("CurrentTransportState", "");
                var transportStatus = new UPnPArgument("CurrentTransportStatus", "");
                var currentSpeed = new UPnPArgument("CurrentSpeed", "");
                var args = new UPnPArgument[] {
                    instanceId,
                    transportState,
                    transportStatus,
                    currentSpeed
                };
                InvokeUpnpDeviceService(device, "AVTransport", "GetTransportInfo", args);
                //
                string jsonres = "[{ ";
                jsonres += "\"CurrentTransportState\" : \"" + transportState.DataValue + "\", ";
                jsonres += "\"CurrentTransportStatus\" : \"" + transportStatus.DataValue + "\", ";
                jsonres += "\"CurrentSpeed\" : \"" + currentSpeed.DataValue + "\"";
                jsonres += " }]";
                //
                returnValue = jsonres;
            }
            else if (request.Command == Command.AVMEDIA_GETMEDIAINFO)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var nrTracks = new UPnPArgument("NrTracks", (uint)0);
                var mediaDuration = new UPnPArgument("MediaDuration", "");
                var currentUri = new UPnPArgument("CurrentURI", "");
                var currentUriMetadata = new UPnPArgument("CurrentURIMetaData", "");
                var nextUri = new UPnPArgument("NextURI", "");
                var nextUriMetadata = new UPnPArgument("NextURIMetaData", "");
                var playMedium = new UPnPArgument("PlayMedium", "");
                var recordMedium = new UPnPArgument("RecordMedium", "");
                var writeStatus = new UPnPArgument("WriteStatus", "");
                var args = new UPnPArgument[] {
                    instanceId,
                    nrTracks,
                    mediaDuration,
                    currentUri,
                    currentUriMetadata,
                    nextUri,
                    nextUriMetadata,
                    playMedium,
                    recordMedium,
                    writeStatus
                };
                InvokeUpnpDeviceService(device, "AVTransport", "GetMediaInfo", args);
                //
                string jsonres = "[{ ";
                jsonres += "\"NrTracks\" : \"" + nrTracks.DataValue + "\", ";
                jsonres += "\"MediaDuration\" : \"" + mediaDuration.DataValue + "\", ";
                jsonres += "\"CurrentURI\" : \"" + currentUri.DataValue + "\", ";
                jsonres += "\"CurrentURIMetaData\" : \"" + currentUriMetadata.DataValue.ToString().Replace("\"", "\\\"") + "\", ";
                jsonres += "\"NextURI\" : \"" + nextUri.DataValue + "\", ";
                jsonres += "\"NextURIMetaData\" : \"" + nextUriMetadata.DataValue.ToString().Replace("\"", "\\\"") + "\", ";
                jsonres += "\"PlayMedium\" : \"" + playMedium.DataValue + "\", ";
                jsonres += "\"RecordMedium\" : \"" + recordMedium.DataValue + "\", ";
                jsonres += "\"WriteStatus\" : \"" + writeStatus.DataValue + "\"";
                jsonres += " }]";
                //
                returnValue = jsonres;
            }
            else if (request.Command == Command.AVMEDIA_GETPOSITIONINFO)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var currentTrack = new UPnPArgument("Track", (uint)0);
                var trackDuration = new UPnPArgument("TrackDuration", "");
                var trackMetadata = new UPnPArgument("TrackMetaData", "");
                var trackUri = new UPnPArgument("TrackURI", "");
                var relativeTime = new UPnPArgument("RelTime", "");
                var absoluteTime = new UPnPArgument("AbsTime", "");
                var relativeCount = new UPnPArgument("RelCount", (uint)0);
                var absoluteCount = new UPnPArgument("AbsCount", (uint)0);
                var args = new UPnPArgument[] {
                    instanceId,
                    currentTrack,
                    trackDuration,
                    trackMetadata,
                    trackUri,
                    relativeTime,
                    absoluteTime,
                    relativeCount,
                    absoluteCount
                };
                InvokeUpnpDeviceService(device, "AVTransport", "GetPositionInfo", args);
                //
                string jsonres = "[{";
                jsonres += "\"Track\" : \"" + currentTrack.DataValue + "\",";
                jsonres += "\"TrackDuration\" : \"" + trackDuration.DataValue + "\",";
                jsonres += "\"TrackMetaData\" : \"" + trackMetadata.DataValue.ToString().Replace("\"", "\\\"") + "\",";
                jsonres += "\"TrackURI\" : \"" + trackUri.DataValue + "\",";
                jsonres += "\"RelTime\" : \"" + relativeTime.DataValue + "\",";
                jsonres += "\"AbsTime\" : \"" + absoluteTime.DataValue + "\",";
                jsonres += "\"RelCount\" : \"" + relativeCount.DataValue + "\",";
                jsonres += "\"AbsCount\" : \"" + absoluteCount.DataValue + "\"";
                jsonres += "}]";
                //
                returnValue = jsonres;
            }
            else if (request.Command == Command.AVMEDIA_SETURI)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var currentUri = new UPnPArgument("CurrentURI", request.GetOption(0));
                var uriMetadata = new UPnPArgument("CurrentURIMetaData", "");
                var args = new UPnPArgument[] {
                    instanceId,
                    currentUri,
                    uriMetadata
                };
                InvokeUpnpDeviceService(device, "AVTransport", "SetAVTransportURI", args);
            }
            else if (request.Command == Command.AVMEDIA_PLAY)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var speed = new UPnPArgument("Speed", "1");
                var args = new UPnPArgument[] {
                    instanceId,
                    speed
                };
                InvokeUpnpDeviceService(device, "AVTransport", "Play", args);
            }
            else if (request.Command == Command.AVMEDIA_PAUSE)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var args = new UPnPArgument[] {
                    instanceId
                };
                InvokeUpnpDeviceService(device, "AVTransport", "Pause", args);
            }
            else if (request.Command == Command.AVMEDIA_STOP)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var args = new UPnPArgument[] {
                    instanceId
                };
                InvokeUpnpDeviceService(device, "AVTransport", "Stop", args);
            }
            else if (request.Command == Command.AVMEDIA_PREVIOUS)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var args = new UPnPArgument[] {
                    instanceId
                };
                InvokeUpnpDeviceService(device, "AVTransport", "Previous", args);
            }
            else if (request.Command == Command.AVMEDIA_NEXT)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var args = new UPnPArgument[] {
                    instanceId
                };
                InvokeUpnpDeviceService(device, "AVTransport", "Next", args);
            }
            else if (request.Command == Command.AVMEDIA_SETNEXT)
            {
            }
            else if (request.Command == Command.AVMEDIA_GETMUTE)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var channel = new UPnPArgument("Channel", "Master");
                var currentMute = new UPnPArgument("CurrentMute", "");
                var args = new UPnPArgument[] {
                    instanceId,
                    channel,
                    currentMute
                };
                InvokeUpnpDeviceService(device, "RenderingControl", "GetMute", args);
                returnValue = currentMute.DataValue.ToString();
            }
            else if (request.Command == Command.AVMEDIA_SETMUTE)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var channel = new UPnPArgument("Channel", "Master");
                var mute = new UPnPArgument("DesiredMute", request.GetOption(0) == "1" ? true : false);
                var args = new UPnPArgument[] {
                    instanceId,
                    channel,
                    mute
                };
                InvokeUpnpDeviceService(device, "RenderingControl", "SetMute", args);
            }
            else if (request.Command == Command.AVMEDIA_GETVOLUME)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var channel = new UPnPArgument("Channel", "Master");
                var currentVolume = new UPnPArgument("CurrentVolume", "");
                var args = new UPnPArgument[] {
                    instanceId,
                    channel,
                    currentVolume
                };
                InvokeUpnpDeviceService(device, "RenderingControl", "GetVolume", args);
                returnValue = currentVolume.DataValue.ToString();
            }
            else if (request.Command == Command.AVMEDIA_SETVOLUME)
            {
                var instanceId = new UPnPArgument("InstanceID", (uint)0);
                var channel = new UPnPArgument("Channel", "Master");
                var volume = new UPnPArgument("DesiredVolume", UInt16.Parse(request.GetOption(0)));
                var args = new UPnPArgument[] {
                    instanceId,
                    channel,
                    volume
                };
                InvokeUpnpDeviceService(device, "RenderingControl", "SetVolume", args);
            }

            // signal event
            if (raisePropertyChanged && InterfacePropertyChangedAction != null)
            {
                try
                {
                    InterfacePropertyChangedAction(new InterfacePropertyChangedAction() {
                        Domain = this.Domain,
                        SourceId = device.UniqueDeviceName,
                        SourceType = "UPnP " + (device != null ? device.StandardDeviceType : "device"),
                        Path = parameterPath,
                        Value = raiseParameter
                    });
                }
                catch
                {
                }
            }

            return returnValue;
        }
Пример #48
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string nodeId = request.NodeId;
            var command = (Command)request.Command;
            string option = request.GetOption(0);

            //process command
            #region X10HAL-commands compatibility !!! <-- DEPRECATE THIS

            if (nodeId.ToUpper() == "STATUS")
            {
                var tmpDataItems = new List<X10Module>(x10lib.ModulesStatus.Count);
                foreach (string key in x10lib.ModulesStatus.Keys)
                {
                    tmpDataItems.Add(x10lib.ModulesStatus[key]);
                }

                var serializer = new XmlSerializer(typeof(List<X10Module>));
                var writer = new StringWriter();
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                serializer.Serialize(writer, tmpDataItems, ns);

                var sb = new StringBuilder();
                sb.Append(writer.ToString());
                //byte[] b = Encoding.UTF8.GetBytes(sb.ToString());
                //response.ContentLength64 = b.Length;
                //response.OutputStream.Write(b, 0, b.Length);
                return sb.ToString();
            }
            else if (nodeId.ToUpper() == "CONFIG")
            {
                string configPath = @"C:\Program Files\ActiveHome Pro\HAL.ahx";
                string config = "";
                //
                try
                {
                    config = System.IO.File.ReadAllText(configPath);
                    //
                    if (config.IndexOf("&amp;") <= 0)
                    {
                        config = config.Replace("&", "&amp;");
                    }
                    //
                    var sb = new StringBuilder();
                    sb.Append(config);
                    return sb.ToString();
                }
                catch (Exception e)
                {
                }
            }

            #endregion

            var houseCode = XTenLib.Utility.HouseCodeFromString(nodeId);
            var unitCode = XTenLib.Utility.UnitCodeFromString(nodeId);
            if (command == Command.PARAMETER_STATUS)
            {
                x10lib.StatusRequest(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_ON)
            {
                x10lib.LightOn(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_OFF)
            {
                x10lib.LightOff(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_BRIGHT)
            {
                x10lib.Bright(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_DIM)
            {
                x10lib.Dim(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_LEVEL)
            {
                int dimvalue = int.Parse(option) - (int)(x10lib.ModulesStatus[nodeId].Level * 100.0);
                if (dimvalue > 0)
                {
                    x10lib.Bright(houseCode, unitCode, dimvalue);
                }
                else if (dimvalue < 0)
                {
                    x10lib.Dim(houseCode, unitCode, -dimvalue);
                }
            }
            else if (command == Command.CONTROL_TOGGLE)
            {
                string huc = XTenLib.Utility.HouseUnitCodeFromEnum(houseCode, unitCode);
                if (x10lib.ModulesStatus[huc].Level == 0)
                {
                    x10lib.LightOn(houseCode, unitCode);
                }
                else
                {
                    x10lib.LightOff(houseCode, unitCode);
                }
            }
            else if (command == Command.CONTROL_ALLLIGHTSON)
            {
                x10lib.AllLightsOn(houseCode);
            }
            else if (command == Command.CONTROL_ALLLIGHTSOFF)
            {
                x10lib.AllUnitsOff(houseCode);
            }//
            return "";
        }
Пример #49
0
        public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migCommand)
        {
            string       streamContent = "";
            ProgramBlock currentProgram;
            ProgramBlock newProgram;
            string       sketchFile = "", sketchFolder = "";

            //
            homegenie.ExecuteAutomationRequest(migCommand);
            if (migCommand.Command.StartsWith("Macro."))
            {
                switch (migCommand.Command)
                {
                case "Macro.Record":
                    homegenie.ProgramEngine.MacroRecorder.RecordingEnable();
                    break;

                case "Macro.Save":
                    newProgram          = homegenie.ProgramEngine.MacroRecorder.SaveMacro(migCommand.GetOption(1));
                    migCommand.Response = newProgram.Address.ToString();
                    break;

                case "Macro.Discard":
                    homegenie.ProgramEngine.MacroRecorder.RecordingDisable();
                    break;

                case "Macro.SetDelay":
                    switch (migCommand.GetOption(0).ToLower())
                    {
                    case "none":
                        homegenie.ProgramEngine.MacroRecorder.DelayType = MacroDelayType.None;
                        break;

                    case "mimic":
                        homegenie.ProgramEngine.MacroRecorder.DelayType = MacroDelayType.Mimic;
                        break;

                    case "fixed":
                        double secs = double.Parse(
                            migCommand.GetOption(1),
                            System.Globalization.CultureInfo.InvariantCulture
                            );
                        homegenie.ProgramEngine.MacroRecorder.DelayType    = MacroDelayType.Fixed;
                        homegenie.ProgramEngine.MacroRecorder.DelaySeconds = secs;
                        break;
                    }
                    break;

                case "Macro.GetDelay":
                    migCommand.Response = "[{ DelayType : '" + homegenie.ProgramEngine.MacroRecorder.DelayType + "', DelayOptions : '" + homegenie.ProgramEngine.MacroRecorder.DelaySeconds + "' }]";
                    break;
                }
            }
            else if (migCommand.Command.StartsWith("Scheduling."))
            {
                switch (migCommand.Command)
                {
                case "Scheduling.Add":
                case "Scheduling.Update":
                    var item = homegenie.ProgramEngine.SchedulerService.AddOrUpdate(
                        migCommand.GetOption(0),
                        migCommand.GetOption(1).Replace(
                            "|",
                            "/"
                            )
                        );
                    item.ProgramId = migCommand.GetOption(2);
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Delete":
                    homegenie.ProgramEngine.SchedulerService.Remove(migCommand.GetOption(0));
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Enable":
                    homegenie.ProgramEngine.SchedulerService.Enable(migCommand.GetOption(0));
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Disable":
                    homegenie.ProgramEngine.SchedulerService.Disable(migCommand.GetOption(0));
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Get":
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.ProgramEngine.SchedulerService.Get(migCommand.GetOption(0)));
                    break;

                case "Scheduling.List":
                    homegenie.ProgramEngine.SchedulerService.Items.Sort((SchedulerItem s1, SchedulerItem s2) =>
                    {
                        return(s1.Name.CompareTo(s2.Name));
                    });
                    migCommand.Response = JsonConvert.SerializeObject(homegenie.ProgramEngine.SchedulerService.Items);
                    break;
                }
            }
            else if (migCommand.Command.StartsWith("Programs."))
            {
                if (migCommand.Command != "Programs.Import")
                {
                    streamContent = new StreamReader(request.InputStream).ReadToEnd();
                }
                //
                switch (migCommand.Command)
                {
                case "Programs.Import":
                    string archiveName = "homegenie_program_import.hgx";
                    if (File.Exists(archiveName))
                    {
                        File.Delete(archiveName);
                    }
                    //
                    var    encoding = (request.Context as HttpListenerContext).Request.ContentEncoding;
                    string boundary = MIG.Gateways.WebServiceUtility.GetBoundary((request.Context as HttpListenerContext).Request.ContentType);
                    MIG.Gateways.WebServiceUtility.SaveFile(encoding, boundary, request.InputStream, archiveName);
                    //
                    int    newPid    = homegenie.ProgramEngine.GeneratePid();
                    var    reader    = new StreamReader(archiveName);
                    char[] signature = new char[2];
                    reader.Read(signature, 0, 2);
                    reader.Close();
                    if (signature[0] == 'P' && signature[1] == 'K')
                    {
                        // Read and uncompress zip file content (arduino program bundle)
                        string zipFileName = archiveName.Replace(".hgx", ".zip");
                        if (File.Exists(zipFileName))
                        {
                            File.Delete(zipFileName);
                        }
                        File.Move(archiveName, zipFileName);
                        string destFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "import");
                        if (Directory.Exists(destFolder))
                        {
                            Directory.Delete(destFolder, true);
                        }
                        Utility.UncompressZip(zipFileName, destFolder);
                        string bundleFolder = Path.Combine("programs", "arduino", newPid.ToString());
                        if (Directory.Exists(bundleFolder))
                        {
                            Directory.Delete(bundleFolder, true);
                        }
                        if (!Directory.Exists(Path.Combine("programs", "arduino")))
                        {
                            Directory.CreateDirectory(Path.Combine("programs", "arduino"));
                        }
                        Directory.Move(Path.Combine(destFolder, "src"), bundleFolder);
                        reader = new StreamReader(Path.Combine(destFolder, "program.hgx"));
                    }
                    else
                    {
                        reader = new StreamReader(archiveName);
                    }
                    var serializer = new XmlSerializer(typeof(ProgramBlock));
                    newProgram = (ProgramBlock)serializer.Deserialize(reader);
                    reader.Close();
                    //
                    newProgram.Address = newPid;
                    newProgram.Group   = migCommand.GetOption(0);
                    homegenie.ProgramEngine.ProgramAdd(newProgram);
                    //
                    newProgram.IsEnabled    = false;
                    newProgram.ScriptErrors = "";
                    newProgram.AppAssembly  = null;
                    //
                    if (newProgram.Type.ToLower() != "arduino")
                    {
                        homegenie.ProgramEngine.CompileScript(newProgram);
                    }
                    //
                    homegenie.UpdateProgramsDatabase();
                    //migCommand.response = JsonHelper.GetSimpleResponse(programblock.Address);
                    migCommand.Response = newProgram.Address.ToString();
                    break;

                case "Programs.Export":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    string filename = currentProgram.Address + "-" + currentProgram.Name.Replace(" ", "_");
                    //
                    var writerSettings = new System.Xml.XmlWriterSettings();
                    writerSettings.Indent = true;
                    var programSerializer = new System.Xml.Serialization.XmlSerializer(typeof(ProgramBlock));
                    var builder           = new StringBuilder();
                    var writer            = System.Xml.XmlWriter.Create(builder, writerSettings);
                    programSerializer.Serialize(writer, currentProgram);
                    writer.Close();
                    //
                    if (currentProgram.Type.ToLower() == "arduino")
                    {
                        string arduinoBundle = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                            Utility.GetTmpFolder(),
                                                            "export",
                                                            filename + ".zip");
                        if (File.Exists(arduinoBundle))
                        {
                            File.Delete(arduinoBundle);
                        }
                        else if (!Directory.Exists(Path.GetDirectoryName(arduinoBundle)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(arduinoBundle));
                        }
                        string mainProgramFile = Path.Combine(Path.GetDirectoryName(arduinoBundle), "program.hgx");
                        File.WriteAllText(
                            mainProgramFile,
                            builder.ToString()
                            );
                        Utility.AddFileToZip(arduinoBundle, mainProgramFile, "program.hgx");
                        sketchFolder = Path.Combine("programs", "arduino", currentProgram.Address.ToString());
                        foreach (string f in Directory.GetFiles(sketchFolder))
                        {
                            if (!Path.GetFileName(f).StartsWith("sketch_"))
                            {
                                Utility.AddFileToZip(
                                    arduinoBundle,
                                    Path.Combine(sketchFolder, Path.GetFileName(f)),
                                    Path.Combine(
                                        "src",
                                        Path.GetFileName(f)
                                        )
                                    );
                            }
                        }
                        //
                        byte[] bundleData = File.ReadAllBytes(arduinoBundle);
                        (request.Context as HttpListenerContext).Response.AddHeader(
                            "Content-Disposition",
                            "attachment; filename=\"" + filename + ".zip\""
                            );
                        (request.Context as HttpListenerContext).Response.OutputStream.Write(bundleData, 0, bundleData.Length);
                    }
                    else
                    {
                        (request.Context as HttpListenerContext).Response.AddHeader(
                            "Content-Disposition",
                            "attachment; filename=\"" + filename + ".hgx\""
                            );
                        migCommand.Response = builder.ToString();
                    }
                    break;

                case "Programs.List":
                    var programList = new List <ProgramBlock>(homegenie.ProgramEngine.Programs);
                    programList.Sort(delegate(ProgramBlock p1, ProgramBlock p2)
                    {
                        string c1 = p1.Name + " " + p1.Address;
                        string c2 = p2.Name + " " + p2.Address;
                        return(c1.CompareTo(c2));
                    });
                    migCommand.Response = JsonConvert.SerializeObject(programList);
                    break;

                case "Programs.Add":
                    newProgram = new ProgramBlock()
                    {
                        Group = migCommand.GetOption(0),
                        Name  = streamContent,
                        Type  = "Wizard"
                    };
                    newProgram.Address = homegenie.ProgramEngine.GeneratePid();
                    homegenie.ProgramEngine.ProgramAdd(newProgram);
                    homegenie.UpdateProgramsDatabase();
                    migCommand.Response = JsonHelper.GetSimpleResponse(newProgram.Address.ToString());
                    break;

                case "Programs.Delete":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        //TODO: remove groups associations as well
                        currentProgram.IsEnabled = false;
                        homegenie.ProgramEngine.ProgramRemove(currentProgram);
                        homegenie.UpdateProgramsDatabase();
                        // remove associated module entry
                        homegenie.Modules.RemoveAll(m => m.Domain == Domains.HomeAutomation_HomeGenie_Automation && m.Address == currentProgram.Address.ToString());
                        homegenie.UpdateModulesDatabase();
                    }
                    break;

                case "Programs.Compile":
                case "Programs.Update":
                    newProgram     = JsonConvert.DeserializeObject <ProgramBlock>(streamContent);
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == newProgram.Address);
                    //
                    if (currentProgram == null)
                    {
                        newProgram.Address = homegenie.ProgramEngine.GeneratePid();
                        homegenie.ProgramEngine.ProgramAdd(newProgram);
                    }
                    else
                    {
                        if (currentProgram.Type.ToLower() != newProgram.Type.ToLower())
                        {
                            currentProgram.AppAssembly = null; // dispose assembly and interrupt current task
                        }
                        currentProgram.Type            = newProgram.Type;
                        currentProgram.Group           = newProgram.Group;
                        currentProgram.Name            = newProgram.Name;
                        currentProgram.Description     = newProgram.Description;
                        currentProgram.IsEnabled       = newProgram.IsEnabled;
                        currentProgram.ScriptCondition = newProgram.ScriptCondition;
                        currentProgram.ScriptSource    = newProgram.ScriptSource;
                        currentProgram.Commands        = newProgram.Commands;
                        currentProgram.Conditions      = newProgram.Conditions;
                        currentProgram.ConditionType   = newProgram.ConditionType;
                        // reset last condition evaluation status
                        currentProgram.LastConditionEvaluationResult = false;
                    }
                    //
                    if (migCommand.Command == "Programs.Compile")
                    {
                        // reset previous error status
                        currentProgram.IsEnabled = false;
                        currentProgram.Stop();
                        currentProgram.ScriptErrors = "";
                        //
                        List <ProgramError> errors = homegenie.ProgramEngine.CompileScript(currentProgram);
                        //
                        currentProgram.IsEnabled    = newProgram.IsEnabled;
                        currentProgram.ScriptErrors = JsonConvert.SerializeObject(errors);
                        migCommand.Response         = currentProgram.ScriptErrors;
                    }
                    //
                    homegenie.UpdateProgramsDatabase();
                    //
                    homegenie.modules_RefreshPrograms();
                    homegenie.modules_RefreshVirtualModules();
                    homegenie.modules_Sort();
                    break;

                case "Programs.Arduino.FileLoad":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    sketchFile   = migCommand.GetOption(1);
                    if (sketchFile == "main")
                    {
                        // "main" is a special keyword to indicate the main program sketch file
                        sketchFile = ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0));
                    }
                    sketchFile          = Path.Combine(sketchFolder, Path.GetFileName(sketchFile));
                    migCommand.Response = JsonHelper.GetSimpleResponse(File.ReadAllText(sketchFile));
                    break;

                case "Programs.Arduino.FileSave":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    sketchFile   = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1)));
                    File.WriteAllText(sketchFile, streamContent);
                    break;

                case "Programs.Arduino.FileAdd":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    if (!Directory.Exists(sketchFolder))
                    {
                        Directory.CreateDirectory(sketchFolder);
                    }
                    sketchFile = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1)));
                    if (File.Exists(sketchFile))
                    {
                        migCommand.Response = JsonHelper.GetSimpleResponse("EXISTS");
                    }
                    else if (!ArduinoAppFactory.IsValidProjectFile(sketchFile))
                    {
                        migCommand.Response = JsonHelper.GetSimpleResponse("INVALID_NAME");
                    }
                    else
                    {
                        StreamWriter sw = File.CreateText(sketchFile);
                        sw.Close();
                        sw.Dispose();
                        sw = null;
                        migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                    }
                    break;

                case "Programs.Arduino.FileDelete":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    sketchFile   = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1)));
                    if (!File.Exists(sketchFile))
                    {
                        migCommand.Response = JsonHelper.GetSimpleResponse("NOT_FOUND");
                    }
                    else
                    {
                        File.Delete(sketchFile);
                        migCommand.Response = JsonHelper.GetSimpleResponse("OK");
                    }
                    break;

                case "Programs.Arduino.FileList":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    List <string> files = new List <string>();
                    foreach (string f in Directory.GetFiles(sketchFolder))
                    {
                        if (ArduinoAppFactory.IsValidProjectFile(f))
                        {
                            files.Add(Path.GetFileName(f));
                        }
                    }
                    migCommand.Response = JsonConvert.SerializeObject(files);
                    break;

                case "Programs.Run":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        // clear any runtime errors before running
                        currentProgram.ScriptErrors = "";
                        homegenie.ProgramEngine.RaiseProgramModuleEvent(
                            currentProgram,
                            Properties.RUNTIME_ERROR,
                            ""
                            );
                        ProgramRun(migCommand.GetOption(0), migCommand.GetOption(1));
                    }
                    break;

                case "Programs.Toggle":
                    currentProgram = ProgramToggle(migCommand.GetOption(0), migCommand.GetOption(1));
                    break;

                case "Programs.Break":
                    currentProgram = ProgramBreak(migCommand.GetOption(0));
                    break;

                case "Programs.Restart":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        currentProgram.IsEnabled = false;
                        try
                        {
                            currentProgram.Stop();
                        }
                        catch
                        {
                        }
                        currentProgram.IsEnabled = true;
                        homegenie.UpdateProgramsDatabase();
                    }
                    break;

                case "Programs.Enable":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        currentProgram.IsEnabled = true;
                        homegenie.UpdateProgramsDatabase();
                    }
                    break;

                case "Programs.Disable":
                    currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        currentProgram.IsEnabled = false;
                        try
                        {
                            currentProgram.Stop();
                        }
                        catch
                        {
                        }
                        homegenie.UpdateProgramsDatabase();
                    }
                    break;
                }
            }
        }
Пример #50
0
        public object InterfaceControl(MIGInterfaceCommand request)
        {
            string response = "[{ ResponseValue : 'OK' }]";

            string nodeId = request.NodeId;
            var command = (Command)request.Command;
            string option = request.GetOption(0);

            // Parse house/unit
            var houseCode = XTenLib.Utility.HouseCodeFromString(nodeId);
            var unitCode = XTenLib.Utility.UnitCodeFromString(nodeId);

            // Modules control
            if (command == Command.PARAMETER_STATUS)
            {
                x10lib.StatusRequest(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_ON)
            {
                x10lib.UnitOn(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_OFF)
            {
                x10lib.UnitOff(houseCode, unitCode);
            }
            else if (command == Command.CONTROL_BRIGHT)
            {
                x10lib.Bright(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_DIM)
            {
                x10lib.Dim(houseCode, unitCode, int.Parse(option));
            }
            else if (command == Command.CONTROL_LEVEL_ADJUST)
            {
                int dimvalue = int.Parse(option);
                //x10lib.Modules[nodeId].Level = ((double)dimvalue/100D);
                RaisePropertyChanged(this.Domain, nodeId, "X10 Module", ModuleParameters.MODPAR_STATUS_LEVEL, x10lib.Modules[nodeId].Level);
                throw(new NotImplementedException("X10 CONTROL_LEVEL_ADJUST Not Implemented"));
            }
            else if (command == Command.CONTROL_LEVEL)
            {
                int dimvalue = int.Parse(option) - (int)(x10lib.Modules[nodeId].Level * 100.0);
                if (dimvalue > 0)
                {
                    x10lib.Bright(houseCode, unitCode, dimvalue);
                }
                else if (dimvalue < 0)
                {
                    x10lib.Dim(houseCode, unitCode, -dimvalue);
                }
            }
            else if (command == Command.CONTROL_TOGGLE)
            {
                string huc = XTenLib.Utility.HouseUnitCodeFromEnum(houseCode, unitCode);
                if (x10lib.Modules[huc].Level == 0)
                {
                    x10lib.UnitOn(houseCode, unitCode);
                }
                else
                {
                    x10lib.UnitOff(houseCode, unitCode);
                }
            }
            else if (command == Command.CONTROL_ALLLIGHTSON)
            {
                x10lib.AllLightsOn(houseCode);
            }
            else if (command == Command.CONTROL_ALLLIGHTSOFF)
            {
                x10lib.AllUnitsOff(houseCode);
            }
            //
            return response;
        }