예제 #1
0
        public void StartScript()
        {
            if (homegenie == null || eventItem == null || isRunning || String.IsNullOrWhiteSpace(eventItem.Script))
            {
                return;
            }

            if (programThread != null)
            {
                StopScript();
            }

            isRunning = true;
            homegenie.RaiseEvent(this, Domains.HomeAutomation_HomeGenie, SourceModule.Scheduler, eventItem.Name,
                                 Properties.SchedulerScriptStatus, eventItem.Name + ":Start");

            programThread = new Thread(() =>
            {
                try
                {
                    MethodRunResult result = null;
                    try
                    {
                        scriptEngine.Execute(InitScript + eventItem.Script);
                    }
                    catch (Exception ex)
                    {
                        result           = new MethodRunResult();
                        result.Exception = ex;
                    }
                    programThread = null;
                    isRunning     = false;
                    if (result != null && result.Exception != null && result.Exception.GetType() != typeof(TargetException))
                    {
                        homegenie.RaiseEvent(this, Domains.HomeAutomation_HomeGenie, SourceModule.Scheduler,
                                             eventItem.Name, Properties.SchedulerScriptStatus,
                                             eventItem.Name + ":Error (" + result.Exception.Message.Replace('\n', ' ').Replace('\r', ' ') + ")");
                    }
                }
                catch (ThreadAbortException)
                {
                    programThread = null;
                    isRunning     = false;
                    homegenie.RaiseEvent(this, Domains.HomeAutomation_HomeGenie, SourceModule.Scheduler, eventItem.Name,
                                         Properties.SchedulerScriptStatus, eventItem.Name + ":Interrupted");
                }
                homegenie.RaiseEvent(this, Domains.HomeAutomation_HomeGenie, SourceModule.Scheduler, eventItem.Name,
                                     Properties.SchedulerScriptStatus, eventItem.Name + ":End");
            });

            try
            {
                programThread.Start();
            }
            catch
            {
                StopScript();
            }
        }
예제 #2
0
        public void StartScript()
        {
            if (_hgService == null || _eventItem == null || _isRunning || string.IsNullOrWhiteSpace(_eventItem.Script))
            {
                return;
            }

            if (_programThread != null)
            {
                StopScript();
            }

            _isRunning = true;
            _hgService.RaiseEvent(this, Domains.HomeAutomation_HomeGenie, SourceModule.Scheduler, _eventItem.Name, Properties.SchedulerScriptStatus, _eventItem.Name + ":Start");

            _programThread = new Thread(() =>
            {
                try
                {
                    MethodRunResult result = null;
                    try
                    {
                        _scriptEngine.Execute(InitScript + _eventItem.Script);
                    }
                    catch (Exception ex)
                    {
                        result = new MethodRunResult {
                            Exception = ex
                        };
                    }
                    _programThread = null;
                    _isRunning     = false;
                    if (result != null && result.Exception != null && !result.Exception.GetType().Equals(typeof(System.Reflection.TargetException)))
                    {
                        _hgService.RaiseEvent(this, Domains.HomeAutomation_HomeGenie, SourceModule.Scheduler, _eventItem.Name, Properties.SchedulerScriptStatus, "Error (" + result.Exception.Message.Replace('\n', ' ').Replace('\r', ' ') + ")");
                    }
                }
                catch (ThreadAbortException)
                {
                    _programThread = null;
                    _isRunning     = false;
                    _hgService.RaiseEvent(this, Domains.HomeAutomation_HomeGenie, SourceModule.Scheduler, _eventItem.Name, Properties.SchedulerScriptStatus, "Interrupted");
                }
                _hgService.RaiseEvent(this, Domains.HomeAutomation_HomeGenie, SourceModule.Scheduler, _eventItem.Name, Properties.SchedulerScriptStatus, "End");
            });

            try
            {
                _programThread.Start();
            }
            catch
            {
                StopScript();
            }
        }
예제 #3
0
파일: Automation.cs 프로젝트: ardasurya/IoT
        internal ProgramBlock ProgramRun(string address, string options)
        {
            int pid = 0;

            int.TryParse(address, out pid);
            ProgramBlock program = homegenie.ProgramManager.Programs.Find(p => p.Address == pid);

            if (program != null)
            {
                if (program.IsEnabled)
                {
                    try
                    {
                        homegenie.ProgramManager.Run(program, options);
                    }
                    catch (Exception e)
                    {
                        HomeGenieService.LogError(e);
                    }
                }
                else
                {
                    homegenie.RaiseEvent(
                        Domains.HomeGenie_System,
                        Domains.HomeAutomation_HomeGenie_Automation,
                        program.Address.ToString(),
                        "Program Error",
                        Properties.RuntimeError,
                        "Program is disabled, cannot run."
                        );
                }
            }
            return(program);
        }
예제 #4
0
        private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
        {
            // logger of last hope
            if (e.ExceptionObject is Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            var logEntry = new MigEvent(
                Domains.HomeAutomation_HomeGenie,
                "Trapper",
                "Unhandled Exception",
                "Error.Exception",
                e.ExceptionObject.ToString()
                );

            try
            {
                // try broadcast first (we don't want homegenie object to be passed, so use the domain string)
                Homegenie.RaiseEvent(Domains.HomeGenie_System, logEntry);
            }
            catch
            {
                HomeGenieService.LogError(logEntry);
            }
        }
예제 #5
0
        internal void RaiseProgramModuleEvent(ProgramBlock program, string property, string value)
        {
            var programModule = hgService.Modules.Find(m => m.Domain == Domains.HomeAutomation_HomeGenie_Automation && m.Address == program.Address.ToString());

            if (programModule != null)
            {
                Utility.ModuleParameterSet(programModule, property, value);
                hgService.RaiseEvent(program.Address, programModule.Domain, programModule.Address, "Automation Program", property, value);
            }
        }
예제 #6
0
 private void RaiseEvent(string message)
 {
     _homegenie.RaiseEvent(
         Domains.HomeGenie_System,
         Domains.HomeGenie_BackupRestore,
         SourceModule.Master,
         "HomeGenie Backup Restore",
         Properties.InstallProgressMessage,
         message
         );
 }
예제 #7
0
        /// <summary>
        /// Execute a setup function when the program is enabled. It is meant to be used in the "Startup Code" to execute only once
        /// the instructions contained in the passed function. It is mainly used for setting program configuration fields, parameters and features.
        /// </summary>
        /// <param name="functionBlock">Function name or inline delegate.</param>
        /// <remarks />
        /// <example>
        /// Example:
        /// <code>
        ///  Program.Setup(()=>
        ///  {
        ///      Program.AddOption(
        ///          "MaxLevel",
        ///          "40",
        ///          "Keep level below the following value",
        ///          "slider:10:80");
        ///      Program.AddFeature(
        ///          "Dimmer",
        ///          "EnergyManagement.EnergySavingMode",
        ///          "Energy Saving Mode enabled light",
        ///          "checkbox");
        ///  }, 0);
        /// </code>
        /// </example>
        public void Setup(Action functionBlock)
        {
            lock (setupLock)
            {
                if (!this.initialized)
                {
                    if (programModule == null)
                    {
                        RelocateProgramModule();
                    }
                    // mark config options to determine unused ones
                    if (programModule != null)
                    {
                        foreach (var parameter in programModule.Properties)
                        {
                            if (parameter.Name.StartsWith("ConfigureOptions."))
                            {
                                parameter.Description = null;
                            }
                        }
                    }

                    homegenie.RaiseEvent(
                        myProgramId,
                        myProgramDomain,
                        myProgramId.ToString(),
                        "Automation Program",
                        Properties.ProgramStatus,
                        "Setup"
                        );
                    functionBlock();

                    // remove deprecated config options
                    if (programModule != null)
                    {
                        var parameterList = programModule.Properties.FindAll(mp => mp.Name.StartsWith("ConfigureOptions."));
                        foreach (var parameter in parameterList)
                        {
                            if (parameter.Name.StartsWith("ConfigureOptions.") && parameter.Description == null)
                            {
                                programModule.Properties.Remove(parameter);
                            }
                        }
                    }
                    this.initialized = true;

                    homegenie.modules_RefreshPrograms();
                    homegenie.modules_RefreshVirtualModules();

                    homegenie.RaiseEvent(
                        myProgramId,
                        myProgramDomain,
                        myProgramId.ToString(),
                        "Automation Program",
                        Properties.ProgramStatus,
                        "Idle"
                        );
                }
            }
        }
예제 #8
0
        public void ProcessRequest(MigClientRequest request)
        {
            var context       = request.Context.Data as HttpListenerContext;
            var requestOrigin = context.Request.RemoteEndPoint.Address.ToString();

            var migCommand = request.Command;

            switch (migCommand.Command)
            {
            case "Events.Push":
                //TODO: implemet security and trust mechanism
                var stream      = request.RequestText;
                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:" + 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);
                }
                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 = requestOrigin + (migCommand.GetOption(0) != "" ? ":" + migCommand.GetOption(0) : "");
                //
                homegenie.RaiseEvent(
                    requestOrigin,
                    moduleEvent.Module.Domain,
                    moduleEvent.Module.Address,
                    requestOrigin,
                    moduleEvent.Parameter.Name,
                    moduleEvent.Parameter.Value
                    );
                var eventData = new ProgramManager.RoutedEvent()
                {
                    Sender    = requestOrigin,
                    Module    = module,
                    Parameter = moduleEvent.Parameter
                };
                ThreadPool.QueueUserWorkItem(new WaitCallback(homegenie.ProgramManager.RoutePropertyChangedEvent), eventData);
                break;
            }
        }
예제 #9
0
 private void virtualMeterTask(object state)
 {
     while (isRunning)
     {
         for (int m = 0; m < homegenie.Modules.Count; m++)
         {
             var             module    = homegenie.Modules[m];
             ModuleParameter parameter = null;
             parameter = module.Properties.Find(delegate(ModuleParameter mp) { return(mp.Name == Properties.VirtualMeterWatts); });
             if (parameter == null)
             {
                 continue;
             }
             else
             {
                 try
                 {
                     double watts = parameter.DecimalValue;
                     if (watts > 0)
                     {
                         parameter = module.Properties.Find(delegate(ModuleParameter mp) { return(mp.Name == Properties.StatusLevel); });
                         double level     = parameter.DecimalValue;
                         double fuzzyness = (new Random().Next(0, 50) - 25) / 100D;
                         //
                         homegenie.RaiseEvent(
                             Domains.HomeGenie_System,
                             module.Domain,
                             module.Address,
                             module.Description,
                             Properties.MeterWatts,
                             level == 0 ? 0 : ((watts * level) + fuzzyness)
                             );
                         //
                         Thread.Sleep(10);
                     }
                 }
                 catch { }
             }
         }
         Thread.Sleep(reportFrequency);
     }
 }
예제 #10
0
 private void virtualMeterTask(object state)
 {
     while (isRunning)
     {
         for (int m = 0; m < homegenie.Modules.Count; m++)
         {
             var             module    = homegenie.Modules[m];
             ModuleParameter parameter = null;
             parameter = module.Properties.Find(delegate(ModuleParameter mp) { return(mp.Name == Properties.VIRTUALMETER_WATTS); });
             if (parameter == null)
             {
                 continue;
             }
             else
             {
                 try
                 {
                     double watts = double.Parse(parameter.Value.Replace(",", "."), System.Globalization.CultureInfo.InvariantCulture);
                     if (watts > 0)
                     {
                         parameter = module.Properties.Find(delegate(ModuleParameter mp) { return(mp.Name == Properties.STATUS_LEVEL); });
                         double level     = double.Parse(parameter.Value.Replace(",", "."), System.Globalization.CultureInfo.InvariantCulture);
                         double fuzzyness = (new Random().Next(0, 50) - 25) / 100D;
                         //
                         homegenie.RaiseEvent(
                             Domains.HomeGenie_System,
                             module.Domain,
                             module.Address,
                             module.Description,
                             Properties.METER_WATTS,
                             level == 0 ? "0.0" : ((watts * level) + fuzzyness).ToString(System.Globalization.CultureInfo.InvariantCulture)
                             );
                         //
                         Thread.Sleep(10);
                     }
                 }
                 catch { }
             }
         }
         Thread.Sleep(reportFrequency);
     }
 }
예제 #11
0
        private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
        {
            var logEntry = new MigEvent(
                Domains.HomeAutomation_HomeGenie,
                "Trapper",
                "Unhandled Exception",
                "Error.Exception",
                e.ExceptionObject.ToString()
                );

            try
            {
                // try broadcast first (we don't want homegenie object to be passed, so use the domain string)
                _homegenie.RaiseEvent(Domains.HomeGenie_System, logEntry);
            }
            catch
            {
                HomeGenieService.LogError(logEntry);
            }
        }
예제 #12
0
        public bool RestoreConfiguration(string archiveFolder, string selectedPrograms)
        {
            // TODO: move this to a separate class file method (eg. BackupHelper.cs)
            bool success = true;
            // Import automation groups
            var serializer       = new XmlSerializer(typeof(List <Group>));
            var reader           = new StreamReader(Path.Combine(archiveFolder, "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.RaiseEvent(
                        Domains.HomeGenie_System,
                        Domains.HomeGenie_BackupRestore,
                        SourceModule.Master,
                        "HomeGenie Backup Restore",
                        Properties.InstallProgressMessage,
                        "= Added: Automation Group '" + automationGroup.Name + "'"
                        );
                }
            }
            homegenie.UpdateGroupsDatabase("Automation");
            // Copy system configuration files
            File.Copy(Path.Combine(archiveFolder, "groups.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "groups.xml"), true);
            homegenie.RaiseEvent(
                Domains.HomeGenie_System,
                Domains.HomeGenie_BackupRestore,
                SourceModule.Master,
                "HomeGenie Backup Restore",
                Properties.InstallProgressMessage,
                "= Restored: Control Groups"
                );
            File.Copy(Path.Combine(archiveFolder, "modules.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules.xml"), true);
            homegenie.RaiseEvent(
                Domains.HomeGenie_System,
                Domains.HomeGenie_BackupRestore,
                SourceModule.Master,
                "HomeGenie Backup Restore",
                Properties.InstallProgressMessage,
                "= Restored: Modules"
                );
            File.Copy(Path.Combine(archiveFolder, "scheduler.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "scheduler.xml"), true);
            homegenie.RaiseEvent(
                Domains.HomeGenie_System,
                Domains.HomeGenie_BackupRestore,
                SourceModule.Master,
                "HomeGenie Backup Restore",
                Properties.InstallProgressMessage,
                "= Restored: Scheduler Events"
                );
            // Statistics db
            if (File.Exists(Path.Combine(archiveFolder, StatisticsLogger.STATISTICS_DB_FILE)))
            {
                File.Copy(Path.Combine(archiveFolder, StatisticsLogger.STATISTICS_DB_FILE), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, StatisticsLogger.STATISTICS_DB_FILE), true);
                homegenie.RaiseEvent(
                    Domains.HomeGenie_System,
                    Domains.HomeGenie_BackupRestore,
                    SourceModule.Master,
                    "HomeGenie Backup Restore",
                    Properties.InstallProgressMessage,
                    "= Restored: Statistics Database"
                    );
            }
            // Remove all old non-system programs
            var rp = new List <ProgramBlock>();

            foreach (var program in homegenie.ProgramManager.Programs)
            {
                if (program.Address >= ProgramManager.USERSPACE_PROGRAMS_START)
                {
                    rp.Add(program);
                }
            }
            foreach (var program in rp)
            {
                homegenie.ProgramManager.ProgramRemove(program);
                homegenie.RaiseEvent(
                    Domains.HomeGenie_System,
                    Domains.HomeGenie_BackupRestore,
                    SourceModule.Master,
                    "HomeGenie Backup Restore",
                    Properties.InstallProgressMessage,
                    "= Removed: Program '" + program.Name + "' (" + program.Address + ")"
                    );
            }
            // Restore installed packages
            if (File.Exists(Path.Combine(archiveFolder, PackageManager.PACKAGE_LIST_FILE)))
            {
                File.Copy(Path.Combine(archiveFolder, PackageManager.PACKAGE_LIST_FILE), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, PackageManager.PACKAGE_LIST_FILE), true);
                // Restore packages from "installed_packages.json"
                string         installFolder = Path.Combine(archiveFolder, "pkg");
                List <dynamic> pkgList       = homegenie.PackageManager.LoadInstalledPackages();
                foreach (var pkg in pkgList)
                {
                    success = success && homegenie.PackageManager.InstallPackage(pkg.folder_url.ToString(), installFolder);
                }
            }
            // Update program database after package restore
            homegenie.UpdateProgramsDatabase();
            // Update system config
            UpdateSystemConfig(archiveFolder);
            // Remove old MIG Interfaces config/data files (lib/mig/*.xml)
            string migLibFolder = Path.Combine("lib", "mig");

            if (Directory.Exists(migLibFolder))
            {
                foreach (string f in Directory.GetFiles(migLibFolder, "*.xml"))
                {
                    File.Delete(f);
                    homegenie.RaiseEvent(
                        Domains.HomeGenie_System,
                        Domains.HomeGenie_BackupRestore,
                        SourceModule.Master,
                        "HomeGenie Backup Restore",
                        Properties.InstallProgressMessage,
                        "= Removed: MIG Data File '" + f + "'"
                        );
                }
            }
            // Restore MIG configuration/data files if present (from backup folder lib/mig/*.xml)
            migLibFolder = Path.Combine(archiveFolder, "lib", "mig");
            if (Directory.Exists(migLibFolder))
            {
                foreach (string f in Directory.GetFiles(migLibFolder, "*.xml"))
                {
                    File.Copy(f, Path.Combine("lib", "mig", Path.GetFileName(f)), true);
                    homegenie.RaiseEvent(
                        Domains.HomeGenie_System,
                        Domains.HomeGenie_BackupRestore,
                        SourceModule.Master,
                        "HomeGenie Backup Restore",
                        Properties.InstallProgressMessage,
                        "= Restored: '" + Path.Combine("lib", "mig", Path.GetFileName(f)) + "'"
                        );
                }
            }
            // Soft-reload system configuration from newely restored files and save config
            homegenie.SoftReload();
            // Restore user-space automation programs
            serializer = new XmlSerializer(typeof(List <ProgramBlock>));
            reader     = new StreamReader(Path.Combine(archiveFolder, "programs.xml"));
            var newProgramsData = (List <ProgramBlock>)serializer.Deserialize(reader);

            reader.Close();
            foreach (var program in newProgramsData)
            {
                var currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == program.Address);
                program.IsRunning = false;
                // Only restore user space programs
                if (selectedPrograms.Contains("," + program.Address.ToString() + ",") && program.Address >= ProgramManager.USERSPACE_PROGRAMS_START && program.Address < ProgramManager.PACKAGE_PROGRAMS_START)
                {
                    int oldPid = program.Address;
                    if (currentProgram == null)
                    {
                        var newPid = ((currentProgram != null && currentProgram.Address == program.Address) ? homegenie.ProgramManager.GeneratePid() : program.Address);
                        try
                        {
                            File.Copy(Path.Combine(archiveFolder, "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", newPid + ".dll"), true);
                        } catch { }
                        program.Address = newPid;
                        homegenie.ProgramManager.ProgramAdd(program);
                        homegenie.RaiseEvent(
                            Domains.HomeGenie_System,
                            Domains.HomeGenie_BackupRestore,
                            SourceModule.Master,
                            "HomeGenie Backup Restore",
                            Properties.InstallProgressMessage,
                            "= Added: Program '" + program.Name + "' (" + program.Address + ")"
                            );
                    }
                    else if (currentProgram != null)
                    {
                        homegenie.ProgramManager.ProgramRemove(currentProgram);
                        try
                        {
                            File.Copy(Path.Combine(archiveFolder, "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", program.Address + ".dll"), true);
                        }
                        catch
                        {
                        }
                        homegenie.ProgramManager.ProgramAdd(program);
                        homegenie.RaiseEvent(
                            Domains.HomeGenie_System,
                            Domains.HomeGenie_BackupRestore,
                            SourceModule.Master,
                            "HomeGenie Backup Restore",
                            Properties.InstallProgressMessage,
                            "= Replaced: Program '" + program.Name + "' (" + program.Address + ")"
                            );
                    }
                    // Restore Arduino program folder ...
                    // TODO: this is untested yet...
                    if (program.Type.ToLower() == "arduino")
                    {
                        string sourceFolder  = Path.Combine(archiveFolder, "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 < ProgramManager.USERSPACE_PROGRAMS_START || program.Address >= ProgramManager.PACKAGE_PROGRAMS_START))
                {
                    // Only restore Enabled/Disabled status of system programs and packages
                    currentProgram.IsEnabled = program.IsEnabled;
                }
            }
            homegenie.UpdateProgramsDatabase();
            homegenie.RaiseEvent(
                Domains.HomeGenie_System,
                Domains.HomeGenie_BackupRestore,
                SourceModule.Master,
                "HomeGenie Backup Restore",
                Properties.InstallProgressMessage,
                "= Status: Backup Restore " + (success ? "Succesful" : "Errors")
                );
            homegenie.SaveData();

            return(success);
        }
예제 #13
0
        public bool InstallPackage(string pkgFolderUrl, string tempFolderPath)
        {
            string  installFolder = Path.Combine(tempFolderPath, "pkg");
            dynamic pkgData       = null;
            bool    success       = true;

            // Download package specs
            homegenie.RaiseEvent(
                Domains.HomeGenie_System,
                Domains.HomeGenie_PackageInstaller,
                SourceModule.Master,
                "HomeGenie Package Installer",
                Properties.InstallProgressMessage,
                "= Downloading: package.json"
                );
            using (var client = new WebClient())
            {
                try
                {
                    string pkgJson = "[" + client.DownloadString(pkgFolderUrl + "/package.json") + "]";
                    pkgData = (JsonConvert.DeserializeObject(pkgJson) as JArray)[0];
                }
                catch (Exception e)
                {
                    homegenie.RaiseEvent(
                        Domains.HomeGenie_System,
                        Domains.HomeGenie_PackageInstaller,
                        SourceModule.Master,
                        "HomeGenie Package Installer",
                        Properties.InstallProgressMessage,
                        "= ERROR: '" + e.Message + "'"
                        );
                    success = false;
                }
                client.Dispose();
            }
            // Download and install package files
            if (success && pkgData != null)
            {
                // Import Automation Programs in package
                foreach (var program in pkgData.programs)
                {
                    homegenie.RaiseEvent(
                        Domains.HomeGenie_System,
                        Domains.HomeGenie_PackageInstaller,
                        SourceModule.Master,
                        "HomeGenie Package Installer",
                        Properties.InstallProgressMessage,
                        "= Downloading: " + program.file.ToString()
                        );
                    Utility.FolderCleanUp(installFolder);
                    string programFile = Path.Combine(installFolder, program.file.ToString());
                    if (File.Exists(programFile))
                    {
                        File.Delete(programFile);
                    }
                    using (var client = new WebClient())
                    {
                        try
                        {
                            client.DownloadFile(pkgFolderUrl + "/" + program.file.ToString(), programFile);
                        }
                        catch (Exception e)
                        {
                            homegenie.RaiseEvent(
                                Domains.HomeGenie_System,
                                Domains.HomeGenie_PackageInstaller,
                                SourceModule.Master,
                                "HomeGenie Package Installer",
                                Properties.InstallProgressMessage,
                                "= ERROR: '" + e.Message + "'"
                                );
                            success = false;
                        }
                        client.Dispose();
                    }
                    if (success)
                    {
                        homegenie.RaiseEvent(
                            Domains.HomeGenie_System,
                            Domains.HomeGenie_PackageInstaller,
                            SourceModule.Master,
                            "HomeGenie Package Installer",
                            Properties.InstallProgressMessage,
                            "= Installing: " + program.name.ToString()
                            );
                        int pid = int.Parse(program.uid.ToString());
                        // by default enable package programs after installing them
                        var enabled    = true;
                        var oldProgram = homegenie.ProgramManager.ProgramGet(pid);
                        if (oldProgram != null)
                        {
                            homegenie.RaiseEvent(
                                Domains.HomeGenie_System,
                                Domains.HomeGenie_PackageInstaller,
                                SourceModule.Master,
                                "HomeGenie Package Installer",
                                Properties.InstallProgressMessage,
                                "= Replacing: '" + oldProgram.Name + "' with pid " + pid
                                );
                            // if the program was already installed, inherit IsEnabled
                            enabled = oldProgram.IsEnabled;
                            homegenie.ProgramManager.ProgramRemove(oldProgram);
                        }
                        var programBlock = ProgramImport(pid, programFile, program.group.ToString());
                        if (programBlock != null)
                        {
                            string groupName = programBlock.Group;
                            if (!String.IsNullOrWhiteSpace(groupName))
                            {
                                // Add automation program group if does not exist
                                Group newGroup = new Group()
                                {
                                    Name = groupName
                                };
                                if (homegenie.AutomationGroups.Find(g => g.Name == newGroup.Name) == null)
                                {
                                    homegenie.AutomationGroups.Add(newGroup);
                                    homegenie.UpdateGroupsDatabase("Automation");
                                }
                            }
                            programBlock.IsEnabled = enabled;
                            homegenie.RaiseEvent(
                                Domains.HomeGenie_System,
                                Domains.HomeGenie_PackageInstaller,
                                SourceModule.Master,
                                "HomeGenie Package Installer",
                                Properties.InstallProgressMessage,
                                "= Installed: '" + program.name.ToString() + "' as pid " + pid
                                );
                        }
                        else
                        {
                            // TODO: report error and stop the package install procedure
                            success = false;
                        }
                    }
                }
                // Import Widgets in package
                foreach (var widget in pkgData.widgets)
                {
                    homegenie.RaiseEvent(
                        Domains.HomeGenie_System,
                        Domains.HomeGenie_PackageInstaller,
                        SourceModule.Master,
                        "HomeGenie Package Installer",
                        Properties.InstallProgressMessage,
                        "= Downloading: " + widget.file.ToString()
                        );
                    Utility.FolderCleanUp(installFolder);
                    string widgetFile = Path.Combine(installFolder, widget.file.ToString());
                    if (File.Exists(widgetFile))
                    {
                        File.Delete(widgetFile);
                    }
                    using (var client = new WebClient())
                    {
                        try
                        {
                            client.DownloadFile(pkgFolderUrl + "/" + widget.file.ToString(), widgetFile);
                        }
                        catch (Exception e)
                        {
                            homegenie.RaiseEvent(
                                Domains.HomeGenie_System,
                                Domains.HomeGenie_PackageInstaller,
                                SourceModule.Master,
                                "HomeGenie Package Installer",
                                Properties.InstallProgressMessage,
                                "= ERROR: '" + e.Message + "'"
                                );
                            success = false;
                        }
                        client.Dispose();
                    }
                    if (success && WidgetImport(widgetFile, installFolder))
                    {
                        homegenie.RaiseEvent(
                            Domains.HomeGenie_System,
                            Domains.HomeGenie_PackageInstaller,
                            SourceModule.Master,
                            "HomeGenie Package Installer",
                            Properties.InstallProgressMessage,
                            "= Installed: '" + widget.name.ToString() + "'"
                            );
                    }
                    else
                    {
                        // TODO: report error and stop the package install procedure
                        success = false;
                    }
                }
                // Import MIG Interfaces in package
                foreach (var migface in pkgData.interfaces)
                {
                    homegenie.RaiseEvent(
                        Domains.HomeGenie_System,
                        Domains.HomeGenie_PackageInstaller,
                        SourceModule.Master,
                        "HomeGenie Package Installer",
                        Properties.InstallProgressMessage,
                        "= Downloading: " + migface.file.ToString()
                        );
                    Utility.FolderCleanUp(installFolder);
                    string migfaceFile = Path.Combine(installFolder, migface.file.ToString());
                    if (File.Exists(migfaceFile))
                    {
                        File.Delete(migfaceFile);
                    }
                    using (var client = new WebClient())
                    {
                        try
                        {
                            client.DownloadFile(pkgFolderUrl + "/" + migface.file.ToString(), migfaceFile);
                            Utility.UncompressZip(migfaceFile, installFolder);
                            File.Delete(migfaceFile);
                        }
                        catch (Exception e)
                        {
                            homegenie.RaiseEvent(
                                Domains.HomeGenie_System,
                                Domains.HomeGenie_PackageInstaller,
                                SourceModule.Master,
                                "HomeGenie Package Installer",
                                Properties.InstallProgressMessage,
                                "= ERROR: '" + e.Message + "'"
                                );
                            success = false;
                        }
                        client.Dispose();
                    }
                    if (success && InterfaceInstall(installFolder))
                    {
                        homegenie.RaiseEvent(
                            Domains.HomeGenie_System,
                            Domains.HomeGenie_PackageInstaller,
                            SourceModule.Master,
                            "HomeGenie Package Installer",
                            Properties.InstallProgressMessage,
                            "= Installed: '" + migface.name.ToString() + "'"
                            );
                    }
                    else
                    {
                        // TODO: report error and stop the package install procedure
                        success = false;
                    }
                }
            }
            else
            {
                success = false;
            }
            if (success)
            {
                pkgData.folder_url   = pkgFolderUrl;
                pkgData.install_date = DateTime.UtcNow;
                AddInstalledPackage(pkgData);
                homegenie.RaiseEvent(
                    Domains.HomeGenie_System,
                    Domains.HomeGenie_PackageInstaller,
                    SourceModule.Master,
                    "HomeGenie Package Installer",
                    Properties.InstallProgressMessage,
                    "= Status: Package Install Successful"
                    );
            }
            else
            {
                homegenie.RaiseEvent(
                    Domains.HomeGenie_System,
                    Domains.HomeGenie_PackageInstaller,
                    SourceModule.Master,
                    "HomeGenie Package Installer",
                    Properties.InstallProgressMessage,
                    "= Status: Package Install Error"
                    );
            }

            return(success);
        }
예제 #14
0
        public bool InstallPackage(string packageSourceUrl)
        {
            PackageDefinition pkgData;
            bool success;

            (success, pkgData) = DownloadPackageDefinition(packageSourceUrl);

            // Download and install package files
            if (success && pkgData != null)
            {
                // Import Automation Programs in package
                foreach (var program in pkgData.Programs)
                {
                    success = DownloadAndInstallProgram(packageSourceUrl, program);
                }

                // Import Widgets in package
                foreach (var widget in pkgData.Widgets)
                {
                    success = DownloadAndInstallWidget(packageSourceUrl, widget);
                }

                // Import MIG Interfaces in package
                foreach (var @interface in pkgData.Interfaces)
                {
                    success = DownloadAndInstallInterface(packageSourceUrl, @interface);
                }
            }
            else
            {
                success = false;
            }

            if (success)
            {
                pkgData.SourceUrl   = packageSourceUrl;
                pkgData.InstallDate = DateTime.UtcNow;
                AddInstalledPackage(pkgData);
                _homegenie.RaiseEvent(
                    Domains.HomeGenie_System,
                    Domains.HomeGenie_PackageInstaller,
                    SourceModule.Master,
                    "HomeGenie Package Installer",
                    Properties.InstallProgressMessage,
                    "= Status: Package Install Successful"
                    );
            }
            else
            {
                _homegenie.RaiseEvent(
                    Domains.HomeGenie_System,
                    Domains.HomeGenie_PackageInstaller,
                    SourceModule.Master,
                    "HomeGenie Package Installer",
                    Properties.InstallProgressMessage,
                    "= Status: Package Install Error"
                    );
            }

            return(success);
        }
예제 #15
0
        public string CreatePackage(PackageData package)
        {
            string programsFile  = Path.Combine(Utility.GetTmpFolder(), "programs.xml");
            string modulesFile   = Path.Combine(Utility.GetTmpFolder(), "modules.xml");
            string groupsFile    = Path.Combine(Utility.GetTmpFolder(), "groups.xml");
            string schedulesFile = Path.Combine(Utility.GetTmpFolder(), "schedules.xml");
            string packageFile   = Path.Combine(Utility.GetTmpFolder(), "package.json");
            string bundleFile    = Path.Combine(Utility.GetTmpFolder(), package.Id + "-" + package.Version + ".zip");

            try
            {
                // Clean-up
                File.Delete(programsFile);
                File.Delete(packageFile);
                File.Delete(bundleFile);
                // collect programs and modules
                bool saveProgramsRequired = false;
                var  packagePrograms      = new List <ProgramBlock>();
                var  packageModules       = new List <Module>();
                foreach (var item in package.Programs)
                {
                    if (item.Repository != package.Repository || item.PackageId != package.Id)
                    {
                        // item is an external dependency belonging to some other repository/package
                        continue;
                    }
                    var program = homegenie.ProgramManager.ProgramGet(int.Parse(item.Hid));
                    if (program != null)
                    {
                        saveProgramsRequired = true;
                        //if (program.PackageInfo.Repository == null)
                        {
                            program.PackageInfo.Repository = package.Repository;
                        }
                        //if (program.PackageInfo.PackageId == null)
                        {
                            program.PackageInfo.PackageId = package.Id;
                        }
                        // update package version only if repository/package id match
                        if (program.PackageInfo.Repository == package.Repository && program.PackageInfo.PackageId == package.Id)
                        {
                            program.PackageInfo.PackageVersion = package.Version;
                        }
                        if (program.PackageInfo.Id == null)
                        {
                            program.PackageInfo.Id = item.Id;
                        }
                        program.PackageInfo.Version  = item.Version;
                        program.PackageInfo.Required = item.Required;
                        item.Checksum = program.PackageInfo.Checksum = Utility.GetObjectChecksum(new
                        {
                            setup  = program.ScriptSetup,
                            source = program.ScriptSource
                        });
                        packagePrograms.Add(program);
                        // lookup for modules belonging to this program
                        packageModules.AddRange(homegenie.Modules.FindAll((m) =>
                        {
                            var vm = Utility.ModuleParameterGet(m, Properties.VirtualModuleParentId);
                            return((m.Domain == Domains.HomeAutomation_HomeGenie && m.Address == program.Address.ToString()) ||
                                   (vm != null && vm.Value == program.Address.ToString()));
                        }));
                    }
                }
                Utility.UpdateXmlDatabase(packagePrograms, programsFile, null);
                Utility.UpdateXmlDatabase(packageModules, modulesFile, null);
                // collect control groups
                var packageGroups = new List <Group>();
                foreach (var item in package.Groups)
                {
                    var group = homegenie.GetGroups("Control").Find((g) => g.Name == item.Hid);
                    if (group != null)
                    {
                        packageGroups.Add(group);
                    }
                }
                Utility.UpdateXmlDatabase(packageGroups, groupsFile, null);
                // collect schedules
                var packageSchedules = new List <SchedulerItem>();
                foreach (var item in package.Schedules)
                {
                    var schedule = homegenie.ProgramManager.SchedulerService.Get(item.Hid);
                    if (schedule != null)
                    {
                        packageSchedules.Add(schedule);
                    }
                }
                Utility.UpdateXmlDatabase(packageSchedules, schedulesFile, null);
                // add files to zip bundle
                File.WriteAllText(packageFile, JsonConvert.SerializeObject(package));
                Utility.AddFileToZip(bundleFile, packageFile, "package.json");
                Utility.AddFileToZip(bundleFile, programsFile, "programs.xml");
                Utility.AddFileToZip(bundleFile, modulesFile, "modules.xml");
                Utility.AddFileToZip(bundleFile, groupsFile, "groups.xml");
                Utility.AddFileToZip(bundleFile, schedulesFile, "schedules.xml");
                // move files to package folder in data/packages
                string packageFolder = Path.Combine(Utility.GetDataFolder(), "packages", package.Repository, package.Id);
                Utility.FolderCleanUp(packageFolder);
                File.Move(packageFile, Path.Combine(packageFolder, "package.json"));
                File.Move(programsFile, Path.Combine(packageFolder, "programs.xml"));
                File.Move(modulesFile, Path.Combine(packageFolder, "modules.xml"));
                File.Move(groupsFile, Path.Combine(packageFolder, "groups.xml"));
                File.Move(schedulesFile, Path.Combine(packageFolder, "schedules.xml"));
                // update programs db if required
                if (saveProgramsRequired)
                {
                    homegenie.UpdateProgramsDatabase();
                }
            }
            catch (Exception e)
            {
                homegenie.RaiseEvent(
                    Domains.HomeGenie_System,
                    Domains.HomeGenie_PackageInstaller,
                    SourceModule.Master,
                    "HomeGenie Package Installer",
                    Properties.InstallProgressMessage,
                    "= Error: " + e.Message
                    );
                return(null);
            }
            // TODO: cleanup temp files and folders
            return(bundleFile);
        }