Exemplo n.º 1
0
        /*
         * public MIGServiceConfiguration.Interface GetInterface(string domain)
         * {
         *  MIGServiceConfiguration.Interface res = MIGService.Interfaces.Find(i => i.Domain == domain);
         *  return res;
         * }
         *
         * public MIGServiceConfiguration.Interface.Option GetInterfaceOption(string domain, string option)
         * {
         *  return GetInterfaceOptions(domain).Find(o => o.Name == option);
         * }
         *
         * public List<MIGServiceConfiguration.Interface.Option> GetInterfaceOptions(string domain)
         * {
         *  MIGServiceConfiguration.Interface mi = MIGService.Interfaces.Find(i => i.Domain == domain);
         *  return mi.Options;
         * }
         */

        public bool Update()
        {
            bool success = false;

            try
            {
                SystemConfiguration syscopy = (SystemConfiguration)this.Clone();
                foreach (ModuleParameter p in syscopy.HomeGenie.Settings)
                {
                    try
                    {
                        if (!String.IsNullOrEmpty(p.Value))
                        {
                            p.Value = StringCipher.Encrypt(p.Value, GetPassPhrase());
                        }
                        if (!String.IsNullOrEmpty(p.LastValue))
                        {
                            p.LastValue = StringCipher.Encrypt(
                                p.LastValue,
                                GetPassPhrase()
                                );
                        }
                    }
                    catch
                    {
                    }
                }


                string fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml");
                if (File.Exists(fname))
                {
                    File.Delete(fname);
                }
                System.Xml.XmlWriterSettings ws = new System.Xml.XmlWriterSettings();
                ws.Indent = true;
                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(syscopy.GetType());
                System.Xml.XmlWriter wri = System.Xml.XmlWriter.Create(fname, ws);
                x.Serialize(wri, syscopy);
                wri.Close();
                success = true;
            }
            catch (Exception)
            {
            }
            //
            if (OnUpdate != null)
            {
                OnUpdate(success);
            }
            //
            return(success);
        }
Exemplo n.º 2
0
 private void LoadSystemConfig()
 {
     if (systemConfiguration != null)
         systemConfiguration.OnUpdate -= systemConfiguration_OnUpdate;
     try
     {
         // load config
         var serializer = new XmlSerializer(typeof(SystemConfiguration));
         using (var reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml")))
         {
             systemConfiguration = (SystemConfiguration)serializer.Deserialize(reader);
             // setup logging
             if (!String.IsNullOrEmpty(systemConfiguration.HomeGenie.EnableLogFile) && systemConfiguration.HomeGenie.EnableLogFile.ToLower().Equals("true"))
             {
                 SystemLogger.Instance.OpenLog();
             }
             else
             {
                 SystemLogger.Instance.CloseLog();
             }
             // configure MIG
             migService.Configuration = systemConfiguration.MigService;
             // Set the password for decrypting settings values and later module parameters
             systemConfiguration.SetPassPhrase(GetPassPhrase());
             // decrypt config data
             foreach (var parameter in systemConfiguration.HomeGenie.Settings)
             {
                 try
                 {
                     if (!String.IsNullOrEmpty(parameter.Value)) parameter.Value = StringCipher.Decrypt(
                             parameter.Value,
                             GetPassPhrase()
                         );
                 }
                 catch
                 {
                 }
             }
         }
     }
     catch (Exception ex)
     {
         LogError(
             Domains.HomeAutomation_HomeGenie,
             "LoadSystemConfig()",
             ex.Message,
             "Exception.StackTrace",
             ex.StackTrace
         );
     }
     if (systemConfiguration != null)
         systemConfiguration.OnUpdate += systemConfiguration_OnUpdate;
 }
Exemplo n.º 3
0
        public HomeGenieService()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            // TODO: all the following initialization stuff should go async
            //
            // initialize logging
            SetupLogging();

            #region MIG Service initialization and startup

            //
            // initialize MIGService, interfaces (hw controllers drivers), webservice
            migService = new MIG.MIGService();
            migService.InterfaceModulesChanged += migService_InterfaceModulesChanged;
            migService.InterfacePropertyChanged += migService_InterfacePropertyChanged;
            migService.ServiceRequestPreProcess += migService_ServiceRequestPreProcess;
            migService.ServiceRequestPostProcess += migService_ServiceRequestPostProcess;
            //
            // load system configuration
            systemConfiguration = new SystemConfiguration();
            systemConfiguration.HomeGenie.ServiceHost = "+";
            systemConfiguration.HomeGenie.ServicePort = 8080;
            systemConfiguration.OnUpdate += systemConfiguration_OnUpdate;
            LoadSystemConfig();
            //
            // setup web service handlers
            wshConfig = new Handlers.Config(this);
            wshAutomation = new Handlers.Automation(this);
            wshInterconnection = new Handlers.Interconnection(this);
            wshStatistics = new Handlers.Statistics(this);
            wshLogging = new Handlers.Logging(this);
            //
            // Try to start WebGateway, if default HTTP port is busy, then it will try from 8080 to 8090
            bool serviceStarted = false;
            int bindAttempts = 0;
            string address = systemConfiguration.HomeGenie.ServiceHost;
            int port = systemConfiguration.HomeGenie.ServicePort;
            while (!serviceStarted && bindAttempts <= 10)
            {
                // TODO: this should be done like this _services.Gateways["WebService"].Configure(....)
                migService.ConfigureWebGateway(
                    address,
                    port,
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "html"),
                    "/hg/html",
                    systemConfiguration.HomeGenie.UserPassword
                );
                if (migService.StartGateways())
                {
                    serviceStarted = true;
                }
                else
                {
                    if (port < 8080) port = 8080;
                    else port++;
                    bindAttempts++;
                }
            }

            #endregion MIG Service initialization and startup

            //
            // If we successfully bound to port, then initialize the database.
            if (serviceStarted)
            {
                LogBroadcastEvent(
                    Domains.HomeAutomation_HomeGenie,
                    HOMEGENIE_MASTERNODE,
                    "HomeGenie service ready",
                    Properties.SYSTEMINFO_HTTPADDRESS,
                    systemConfiguration.HomeGenie.ServiceHost + ":" + port
                );
                InitializeSystem();
                // Update system configuration with the HTTP port the service succeed to bind on
                systemConfiguration.HomeGenie.ServicePort = port;
            }
            else
            {
                LogBroadcastEvent(
                    Domains.HomeAutomation_HomeGenie,
                    HOMEGENIE_MASTERNODE,
                    "HTTP binding failed.",
                    Properties.SYSTEMINFO_HTTPADDRESS,
                    systemConfiguration.HomeGenie.ServiceHost + ":" + systemConfiguration.HomeGenie.ServicePort
                );
                Program.Quit(false);
            }

            updateChecker = new UpdateChecker(this);
            updateChecker.ArchiveDownloadUpdate += (object sender, ArchiveDownloadEventArgs args) =>
            {
                LogBroadcastEvent(
                    Domains.HomeGenie_UpdateChecker,
                    HOMEGENIE_MASTERNODE,
                    "HomeGenie Update Checker",
                    Properties.INSTALLPROGRESS_MESSAGE,
                    "= " + args.Status + ": " + args.ReleaseInfo.DownloadUrl
                );
            };
            updateChecker.UpdateProgress += (object sender, UpdateProgressEventArgs args) =>
            {
                LogBroadcastEvent(
                    Domains.HomeGenie_UpdateChecker,
                    HOMEGENIE_MASTERNODE,
                    "HomeGenie Update Checker",
                    Properties.INSTALLPROGRESS_UPDATE,
                    args.Status.ToString()
                );
            };
            updateChecker.InstallProgressMessage += (object sender, string message) =>
            {
                LogBroadcastEvent(
                    Domains.HomeGenie_UpdateChecker,
                    HOMEGENIE_MASTERNODE,
                    "HomeGenie Update Checker",
                    Properties.INSTALLPROGRESS_MESSAGE,
                    message
                );
            };
            //
            statisticsLogger = new StatisticsLogger(this);
            statisticsLogger.Start();
            //
            // Setup local UPnP device
            SetupUpnp();
            //
            // it will check every 24 hours
            updateChecker.Start();
            //
            Start();
        }
Exemplo n.º 4
0
 private void LoadSystemConfig()
 {
     try
     {
         // load config
         var serializer = new XmlSerializer(typeof(SystemConfiguration));
         var reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml"));
         systemConfiguration = (SystemConfiguration)serializer.Deserialize(reader);
         if (!String.IsNullOrEmpty(systemConfiguration.HomeGenie.EnableLogFile) && systemConfiguration.HomeGenie.EnableLogFile.ToLower().Equals("true"))
         {
             SystemLogger.Instance.OpenLog();
         }
         else
         {
             SystemLogger.Instance.CloseLog();
         }
         // set the system password
         migService.SetWebServicePassword(systemConfiguration.HomeGenie.UserPassword);
         //
         foreach (var parameter in systemConfiguration.HomeGenie.Settings)
         {
             try
             {
                 if (!String.IsNullOrEmpty(parameter.Value)) parameter.Value = StringCipher.Decrypt(
                         parameter.Value,
                         systemConfiguration.GetPassPhrase()
                     );
             }
             catch
             {
             }
         }
         //
         reader.Close();
         //
         // configure MIG
         //
         migService.Configuration = systemConfiguration.MIGService;
     }
     catch (Exception ex)
     {
         HomeGenieService.LogEvent(
             Domains.HomeAutomation_HomeGenie,
             "LoadSystemConfig()",
             ex.Message,
             "Exception.StackTrace",
             ex.StackTrace
         );
     }
 }
Exemplo n.º 5
0
 private bool UpdateSystemConfig()
 {
     string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml");
     string configText = File.ReadAllText(Path.Combine(tempFolderPath, "systemconfig.xml"));
     if (configText.IndexOf("<ServicePort>") > 0)
     {
         configText = configText.Replace("SystemConfiguration", "SystemConfiguration_1_0");
         configText = configText.Replace("HomeGenieConfiguration", "HomeGenieConfiguration_1_0");
         // This is old configuration file from HG < 1.1
         SystemConfiguration_1_0 oldConfig;
         SystemConfiguration newConfig = new SystemConfiguration();
         try
         {
             // Load old config
             var serializerOld = new XmlSerializer(typeof(SystemConfiguration_1_0));
             using (var reader = new StringReader(configText))
                 oldConfig = (SystemConfiguration_1_0)serializerOld.Deserialize(reader);
             // Copy setting to the new config format
             newConfig.HomeGenie.Settings = oldConfig.HomeGenie.Settings;
             newConfig.HomeGenie.SystemName = oldConfig.HomeGenie.SystemName;
             newConfig.HomeGenie.Location = oldConfig.HomeGenie.Location;
             newConfig.HomeGenie.GUID = oldConfig.HomeGenie.GUID;
             newConfig.HomeGenie.EnableLogFile = oldConfig.HomeGenie.EnableLogFile;
             newConfig.HomeGenie.Statistics = new HomeGenieConfiguration.StatisticsConfiguration();
             newConfig.HomeGenie.Statistics.MaxDatabaseSizeMBytes = oldConfig.HomeGenie.Statistics.MaxDatabaseSizeMBytes;
             newConfig.HomeGenie.Statistics.StatisticsTimeResolutionSeconds = oldConfig.HomeGenie.Statistics.StatisticsTimeResolutionSeconds;
             newConfig.HomeGenie.Statistics.StatisticsUIRefreshSeconds = oldConfig.HomeGenie.Statistics.StatisticsUIRefreshSeconds;
             var webGateway = new Gateway() { Name = "WebServiceGateway", IsEnabled = true };
             webGateway.Options = new List<Option>();
             webGateway.Options.Add(new Option("BaseUrl", "/hg/html"));
             webGateway.Options.Add(new Option("HomePath", "html"));
             webGateway.Options.Add(new Option("Host", oldConfig.HomeGenie.ServiceHost));
             webGateway.Options.Add(new Option("Port", oldConfig.HomeGenie.ServicePort.ToString()));
             webGateway.Options.Add(new Option("Username", "admin"));
             webGateway.Options.Add(new Option("Password", oldConfig.HomeGenie.UserPassword));
             webGateway.Options.Add(new Option("HttpCacheIgnore.1", "^.*\\/pages\\/control\\/widgets\\/.*\\.(js|html)$"));
             webGateway.Options.Add(new Option("HttpCacheIgnore.2", "^.*\\/html\\/index.html"));
             webGateway.Options.Add(new Option("UrlAlias.1", "api/HomeAutomation.HomeGenie/Logging/RealTime.EventStream:events"));
             webGateway.Options.Add(new Option("UrlAlias.2", "hg/html/pages/control/widgets/homegenie/generic/images/socket_on.png:hg/html/pages/control/widgets/homegenie/generic/images/switch_on.png"));
             webGateway.Options.Add(new Option("UrlAlias.3", "hg/html/pages/control/widgets/homegenie/generic/images/socket_off.png:hg/html/pages/control/widgets/homegenie/generic/images/switch_off.png"));
             webGateway.Options.Add(new Option("UrlAlias.4", "hg/html/pages/control/widgets/homegenie/generic/images/siren.png:hg/html/pages/control/widgets/homegenie/generic/images/siren_on.png"));
             // TODO: EnableFileCaching value should be read from oldConfig.MIGService.EnableWebCache
             webGateway.Options.Add(new Option("EnableFileCaching", "false"));
             newConfig.MigService.Gateways.Add(webGateway);
             newConfig.MigService.Interfaces = oldConfig.MIGService.Interfaces;
             foreach(var iface in newConfig.MigService.Interfaces)
             {
                 if (iface.Domain == "HomeAutomation.ZWave")
                     iface.AssemblyName = "MIG.HomeAutomation.dll";
                 if (iface.Domain == "HomeAutomation.Insteon")
                     iface.AssemblyName = "MIG.HomeAutomation.dll";
                 if (iface.Domain == "HomeAutomation.X10")
                     iface.AssemblyName = "MIG.HomeAutomation.dll";
                 if (iface.Domain == "HomeAutomation.W800RF")
                     iface.AssemblyName = "MIG.HomeAutomation.dll";
                 if (iface.Domain == "Controllers.LircRemote")
                     iface.AssemblyName = "MIG.Controllers.dll";
                 if (iface.Domain == "Media.CameraInput")
                     iface.AssemblyName = "MIG.Media.dll";
                 if (iface.Domain == "Protocols.UPnP")
                     iface.AssemblyName = "MIG.Protocols.dll";
             }
             // Check for lircconfig.xml
             if (File.Exists(Path.Combine(tempFolderPath, "lircconfig.xml")))
             {
                 File.Copy(Path.Combine(tempFolderPath, "lircconfig.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lib", "mig", "lircconfig.xml"), true);
             }
             // Update configuration file
             if (File.Exists(configFile))
             {
                 File.Delete(configFile);
             }
             System.Xml.XmlWriterSettings ws = new System.Xml.XmlWriterSettings();
             ws.Indent = true;
             System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(newConfig.GetType());
             System.Xml.XmlWriter wri = System.Xml.XmlWriter.Create(configFile, ws);
             x.Serialize(wri, newConfig);
             wri.Close();
         }
         catch (Exception e)
         {
             MigService.Log.Error(e);
             return false;
         }
     }
     else
     {
         // HG >= 1.1
         File.Copy(Path.Combine(tempFolderPath, "systemconfig.xml"), configFile, true);
     }
     return true;
 }
Exemplo n.º 6
0
        public HomeGenieService()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            //
            // initialize recent log list
            recentEventsLog = new TsList<LogEntry>();

            #region MIG Service initialization and startup

            //
            // initialize MIGService, interfaces (hw controllers drivers), webservice
            migService = new MIG.MIGService();
            migService.InterfaceModulesChanged += migService_InterfaceModulesChanged;
            migService.InterfacePropertyChanged += migService_InterfacePropertyChanged;
            migService.ServiceRequestPreProcess += migService_ServiceRequestPreProcess;
            migService.ServiceRequestPostProcess += migService_ServiceRequestPostProcess;
            //
            // load system configuration
            systemConfiguration = new SystemConfiguration();
            systemConfiguration.HomeGenie.ServicePort = 8080;
            systemConfiguration.OnUpdate += systemConfiguration_OnUpdate;
            LoadSystemConfig();
            //
            // setup web service handlers
            wshConfig = new Handlers.Config(this);
            wshAutomation = new Handlers.Automation(this);
            wshInterconnection = new Handlers.Interconnection(this);
            wshStatistics = new Handlers.Statistics(this);
            wshLogging = new Handlers.Logging(this);
            //
            // Try to start WebGateway, at  0 < (port - ServicePort) < 10
            bool serviceStarted = false;
            int port = systemConfiguration.HomeGenie.ServicePort;
            while (!serviceStarted && port <= systemConfiguration.HomeGenie.ServicePort + 10)
            {
                // TODO: this should be done like this _services.Gateways["WebService"].Configure(....)
                migService.ConfigureWebGateway(
                    port,
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "html"),
                    "/hg/html",
                    systemConfiguration.HomeGenie.UserPassword
                );
                if (migService.StartGateways())
                {
                    systemConfiguration.HomeGenie.ServicePort = port;
                    serviceStarted = true;
                }
                else
                {
                    port++;
                }
            }

            #endregion MIG Service initialization and startup

            //
            // If we successfully bound to port, then initialize the database.
            if (serviceStarted)
            {
                LogBroadcastEvent(
                    Domains.HomeAutomation_HomeGenie,
                    "SystemInfo",
                    "HomeGenie service ready",
                    "HTTP.PORT",
                    port.ToString()
                );
                systemConfiguration.HomeGenie.ServicePort = port;
                InitializeSystem();
            }
            else
            {
                LogBroadcastEvent(
                    Domains.HomeAutomation_HomeGenie,
                    "SystemInfo",
                    "Http port bind failed.",
                    "HTTP.PORT",
                    port.ToString()
                );
                Program.Quit(false);
            }

            updateChecker = new UpdateChecker(this);
            updateChecker.ArchiveDownloadUpdate += (object sender, ArchiveDownloadEventArgs args) =>
            {
                LogBroadcastEvent(
                    Domains.HomeGenie_UpdateChecker,
                    "0",
                    "HomeGenie Update Checker",
                    "InstallProgress.Message",
                    "= " + args.Status + ": " + args.ReleaseInfo.DownloadUrl
                );
            };
            updateChecker.UpdateProgress += (object sender, UpdateProgressEventArgs args) =>
            {
                LogBroadcastEvent(
                    Domains.HomeGenie_UpdateChecker,
                    "0",
                    "HomeGenie Update Checker",
                    "Update Check",
                    args.Status.ToString()
                );
            };
            updateChecker.InstallProgressMessage += (object sender, string message) =>
            {
                LogBroadcastEvent(
                    Domains.HomeGenie_UpdateChecker,
                    "0",
                    "HomeGenie Update Checker",
                    "InstallProgress.Message",
                    message
                );
            };
            // it will check every 24 hours
            updateChecker.Start();
            //
            statisticsLogger = new StatisticsLogger(this);
            statisticsLogger.Start();
            //
            LogBroadcastEvent(Domains.HomeGenie_System, "0", "HomeGenie System", "HomeGenie", "STARTED");
            //
            // Setup local UPnP device
            SetupUpnp();
        }