コード例 #1
0
        public StatisticsLogger(HomeGenieService hg)
        {
            homegenie = hg;
            dbSizeLimit = hg.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes * 1024 * 1024;
            _statisticsTimeResolutionSeconds = hg.SystemConfiguration.HomeGenie.Statistics.StatisticsTimeResolutionSeconds;

        }
コード例 #2
0
ファイル: Config.cs プロジェクト: Solertis/HomeGenie
 public Config(HomeGenieService hg)
 {
     homegenie = hg;
     tempFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder());
     widgetBasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "html", "pages", "control", "widgets");
     groupWallpapersPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "html", "images", "wallpapers");
 }
コード例 #3
0
        public StatisticsLogger(HomeGenieService hg)
        {
            homegenie = hg;
            dbSizeLimit = hg.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes * 1024 * 1024;
            _statisticsTimeResolutionSeconds = hg.SystemConfiguration.HomeGenie.Statistics.StatisticsTimeResolutionSeconds;

            logInterval = new Timer(TimeSpan.FromSeconds(_statisticsTimeResolutionSeconds).TotalMilliseconds);
            logInterval.Elapsed += logInterval_Elapsed;
        }
コード例 #4
0
 public StatisticsLogger(HomeGenieService hg)
 {
     homegenie = hg;
     logInterval = new Timer(TimeSpan.FromMinutes(STATISTICS_TIME_RESOLUTION_MINUTES).TotalMilliseconds);
     logInterval.Elapsed += logInterval_Elapsed;
 }
コード例 #5
0
 public ModulesManager(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #6
0
 public SchedulerHelper(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #7
0
 public PackageManager(HomeGenieService hg)
 {
     homegenie      = hg;
     widgetBasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "html", "pages", "control", "widgets");
 }
コード例 #8
0
 public UpdateInstaller(HomeGenieService homeGenieService)
 {
     _homeGenieService = homeGenieService;
 }
コード例 #9
0
        public List <ProgramError> Compile()
        {
            List <ProgramError> errors = new List <ProgramError>();

            // check for output directory
            if (!Directory.Exists(Path.GetDirectoryName(AssemblyFile)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(AssemblyFile));
            }

            // dispose assembly and interrupt current task (if any)
            programBlock.IsEnabled = false;


            // clean up old assembly files
            try
            {
                if (File.Exists(this.AssemblyFile))
                {
                    File.Delete(this.AssemblyFile);
                }
                if (File.Exists(this.AssemblyFile + ".mdb"))
                {
                    File.Delete(this.AssemblyFile + ".mdb");
                }
                if (File.Exists(this.AssemblyFile.Replace(".dll", ".mdb")))
                {
                    File.Delete(this.AssemblyFile.Replace(".dll", ".mdb"));
                }
                if (File.Exists(this.AssemblyFile + ".pdb"))
                {
                    File.Delete(this.AssemblyFile + ".pdb");
                }
                if (File.Exists(this.AssemblyFile.Replace(".dll", ".pdb")))
                {
                    File.Delete(this.AssemblyFile.Replace(".dll", ".pdb"));
                }
            }
            catch (Exception ee)
            {
                HomeGenieService.LogError(ee);
            }


            // DO NOT CHANGE THE FOLLOWING LINES OF CODE
            // it is a lil' trick for mono compatibility
            // since it will be caching the assembly when using the same name
            // and use the old one instead of the new one
            string tmpfile = Path.Combine("programs", Guid.NewGuid().ToString() + ".dll");

            System.CodeDom.Compiler.CompilerResults result = new System.CodeDom.Compiler.CompilerResults(null);
            try
            {
                result = CSharpAppFactory.CompileScript(programBlock.ScriptCondition, programBlock.ScriptSource, tmpfile);
            }
            catch (Exception ex)
            {
                // report errors during post-compilation process
                result.Errors.Add(new System.CodeDom.Compiler.CompilerError(programBlock.Name, 0, 0, "-1", ex.Message));
            }

            if (result.Errors.Count > 0)
            {
                int sourceLines = programBlock.ScriptSource.Split('\n').Length;
                foreach (System.CodeDom.Compiler.CompilerError error in result.Errors)
                {
                    int    errorRow  = (error.Line - CSharpAppFactory.PROGRAM_CODE_OFFSET);
                    string blockType = "CR";
                    if (errorRow >= sourceLines + CSharpAppFactory.CONDITION_CODE_OFFSET)
                    {
                        errorRow -= (sourceLines + CSharpAppFactory.CONDITION_CODE_OFFSET);
                        blockType = "TC";
                    }
                    if (!error.IsWarning)
                    {
                        errors.Add(new ProgramError()
                        {
                            Line         = errorRow,
                            Column       = error.Column,
                            ErrorMessage = error.ErrorText,
                            ErrorNumber  = error.ErrorNumber,
                            CodeBlock    = blockType
                        });
                    }
                    else
                    {
                        var warning = String.Format("{0},{1},{2}: {3}", blockType, errorRow, error.Column, error.ErrorText);
                        homegenie.ProgramManager.RaiseProgramModuleEvent(programBlock, Properties.CompilerWarning, warning);
                    }
                }
            }
            if (errors.Count == 0)
            {
                // move/copy new assembly files
                // rename temp file to production file
                appAssembly = result.CompiledAssembly;
                try
                {
                    //string tmpfile = new Uri(value.CodeBase).LocalPath;
                    File.Move(tmpfile, this.AssemblyFile);
                    if (File.Exists(tmpfile + ".mdb"))
                    {
                        File.Move(tmpfile + ".mdb", this.AssemblyFile + ".mdb");
                    }
                    if (File.Exists(tmpfile.Replace(".dll", ".mdb")))
                    {
                        File.Move(tmpfile.Replace(".dll", ".mdb"), this.AssemblyFile.Replace(".dll", ".mdb"));
                    }
                    if (File.Exists(tmpfile + ".pdb"))
                    {
                        File.Move(tmpfile + ".pdb", this.AssemblyFile + ".pdb");
                    }
                    if (File.Exists(tmpfile.Replace(".dll", ".pdb")))
                    {
                        File.Move(tmpfile.Replace(".dll", ".pdb"), this.AssemblyFile.Replace(".dll", ".pdb"));
                    }
                }
                catch (Exception ee)
                {
                    HomeGenieService.LogError(ee);
                }
            }

            return(errors);
        }
コード例 #10
0
 public ProgramHelper(HomeGenieService hg, int programId) : base(hg)
 {
     myProgramId = programId;
 }
コード例 #11
0
        private void logInterval_Elapsed(object sender, ElapsedEventArgs eventArgs)
        {
            var end     = DateTime.UtcNow;
            var modules = (TsList <Module>)homegenie.Modules; //.DeepClone();

            for (int m = 0; m < modules.Count; m++)
            {
                var module = modules[m];
                for (int p = 0; p < module.Properties.Count; p++)
                {
                    var parameter = module.Properties[p];
                    if (parameter.Statistics.Values.Count > 0)
                    {
                        var values = parameter.Statistics.Values.FindAll(sv => (sv.Timestamp.Ticks <= end.Ticks && sv.Timestamp.Ticks > parameter.Statistics.LastProcessedTimestamp.Ticks));
                        if (values.Count > 0)
                        {
                            double average = (values.Sum(d => d.Value) / values.Count);
                            try
                            {
                                string dbName   = GetStatisticsDatabaseName();
                                var    fileInfo = new FileInfo(dbName);
                                if (fileInfo.Length > dbSizeLimit)
                                {
                                    // Delete old data (1 day data slot)
                                    var dateRange        = GetDateRange();
                                    var removeOldestData = dbConnection.CreateCommand();
                                    removeOldestData.Parameters.Add(new SQLiteParameter("@deleteBefore", DateTimeToSQLite(dateRange.TimeStart.AddHours(24))));
                                    removeOldestData.CommandText = "DELETE FROM ValuesHist WHERE TimeStart < @deleteBefore";
                                    removeOldestData.ExecuteNonQuery();
                                    removeOldestData.CommandText = "VACUUM";
                                    removeOldestData.ExecuteNonQuery();
                                }
                                var dbCommand = dbConnection.CreateCommand();
                                // "TimeStart","TimeEnd","Domain","Address","Parameter","AverageValue", "CustomData"
                                dbCommand.Parameters.Add(new SQLiteParameter("@timestart", DateTimeToSQLite(parameter.Statistics.LastProcessedTimestamp)));
                                dbCommand.Parameters.Add(new SQLiteParameter("@timeend", DateTimeToSQLite(end)));
                                dbCommand.Parameters.Add(new SQLiteParameter("@domain", module.Domain));
                                dbCommand.Parameters.Add(new SQLiteParameter("@address", module.Address));
                                dbCommand.Parameters.Add(new SQLiteParameter("@parameter", parameter.Name));
                                dbCommand.Parameters.Add(new SQLiteParameter("@avgvalue", average.ToString(CultureInfo.InvariantCulture)));
                                dbCommand.Parameters.Add(new SQLiteParameter("@data", module.Name));
                                dbCommand.CommandText = "INSERT INTO ValuesHist VALUES (@timestart, @timeend, @domain, @address, @parameter, @avgvalue, @data)";
                                dbCommand.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                HomeGenieService.LogError(
                                    Domains.HomeAutomation_HomeGenie,
                                    "Service.StatisticsLogger",
                                    "Database Error",
                                    "Exception.StackTrace",
                                    String.Format("{0}: {1}", ex.Message, ex.StackTrace)
                                    );
                                // try close/reopen (perhaps some locking issue)
                                CloseStatisticsDatabase();
                                OpenStatisticsDatabase();
                            }
                            //
                            // reset statistics history sample
                            //
                            parameter.Statistics.LastProcessedTimestamp = end;
                            parameter.Statistics.Values.Clear();
                        }
                    }
                }
            }
        }
コード例 #12
0
 public StatisticsLogger(HomeGenieService hg)
 {
     _homegenie            = hg;
     _loginterval          = new Timer(TimeSpan.FromMinutes(STATISTICS_TIME_RESOLUTION_MINUTES).TotalMilliseconds);
     _loginterval.Elapsed += _loginterval_Elapsed;
 }
コード例 #13
0
 public void SetHost(HomeGenieService hg)
 {
     (this as IProgramEngine).Unload();
     Homegenie = hg;
     (this as IProgramEngine).Load();
 }
コード例 #14
0
ファイル: Config.cs プロジェクト: bitroniq/HomeGenie
 public Config(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #15
0
ファイル: CSharpEngine.cs プロジェクト: Bounz/HomeGenie-BE
        public List <ProgramError> Compile()
        {
            var errors = new List <ProgramError>();

            // check for output directory
            if (!Directory.Exists(Path.GetDirectoryName(AssemblyFile)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(AssemblyFile));
            }

            // dispose assembly and interrupt current task (if any)
            ProgramBlock.IsEnabled = false;

            // clean up old assembly files
            try
            {
                // If the file to be deleted does not exist, no exception is thrown.
                File.Delete(AssemblyFile);
                File.Delete(AssemblyFile + ".mdb");
                File.Delete(AssemblyFile.Replace(".dll", ".mdb"));
                File.Delete(AssemblyFile + ".pdb");
                File.Delete(AssemblyFile.Replace(".dll", ".pdb"));
            }
            catch (Exception ex)
            {
                HomeGenieService.LogError(ex);
            }

            // DO NOT CHANGE THE FOLLOWING LINES OF CODE
            // it is a lil' trick for mono compatibility
            // since it will be caching the assembly when using the same name
            // and use the old one instead of the new one
            var tmpFile = Path.Combine(FilePaths.ProgramsFolder, Guid.NewGuid() + ".dll");
            var result  = new CompilerResults(null);

            try
            {
                result = CSharpAppFactory.CompileScript(ProgramBlock.ScriptCondition, ProgramBlock.ScriptSource, tmpFile);
            }
            catch (Exception ex)
            {
                // report errors during post-compilation process
                result.Errors.Add(new CompilerError(ProgramBlock.Name, 0, 0, "-1", ex.Message));
            }

            if (result.Errors.Count > 0)
            {
                var sourceLines = ProgramBlock.ScriptSource.Split('\n').Length;
                foreach (CompilerError error in result.Errors)
                {
                    var errorRow  = (error.Line - CSharpAppFactory.ProgramCodeOffset);
                    var blockType = CodeBlockEnum.CR;
                    if (errorRow >= sourceLines + CSharpAppFactory.ConditionCodeOffset)
                    {
                        errorRow -= (sourceLines + CSharpAppFactory.ConditionCodeOffset);
                        blockType = CodeBlockEnum.TC;
                    }
                    if (!error.IsWarning)
                    {
                        errors.Add(new ProgramError {
                            Line         = errorRow,
                            Column       = error.Column,
                            ErrorMessage = error.ErrorText,
                            ErrorNumber  = error.ErrorNumber,
                            CodeBlock    = blockType
                        });
                    }
                    else
                    {
                        var warning = string.Format("{0},{1},{2}: {3}", blockType, errorRow, error.Column, error.ErrorText);
                        Homegenie.ProgramManager.RaiseProgramModuleEvent(ProgramBlock, Properties.CompilerWarning, warning);
                    }
                }
            }

            if (errors.Count != 0)
            {
                return(errors);
            }

            // move/copy new assembly files
            // rename temp file to production file
            _scriptAssembly = result.CompiledAssembly;
            try
            {
                //string tmpfile = new Uri(value.CodeBase).LocalPath;
                File.Move(tmpFile, AssemblyFile);
                if (File.Exists(tmpFile + ".mdb"))
                {
                    File.Move(tmpFile + ".mdb", AssemblyFile + ".mdb");
                }
                if (File.Exists(tmpFile.Replace(".dll", ".mdb")))
                {
                    File.Move(tmpFile.Replace(".dll", ".mdb"), AssemblyFile.Replace(".dll", ".mdb"));
                }
                if (File.Exists(tmpFile + ".pdb"))
                {
                    File.Move(tmpFile + ".pdb", AssemblyFile + ".pdb");
                }
                if (File.Exists(tmpFile.Replace(".dll", ".pdb")))
                {
                    File.Move(tmpFile.Replace(".dll", ".pdb"), AssemblyFile.Replace(".dll", ".pdb"));
                }
            }
            catch (Exception ee)
            {
                HomeGenieService.LogError(ee);
            }

            return(errors);
        }
コード例 #16
0
 /// <summary>
 /// Sends an E-Mail.
 /// </summary>
 /// <returns><c>true</c>, if message was sent, <c>false</c> otherwise.</returns>
 /// <param name="from">Message sender.</param>
 /// <param name="recipients">Message recipients.</param>
 /// <param name="subject">Message subject.</param>
 /// <param name="messageText">Message text.</param>
 public bool SendMessage(string from, string recipients, string subject, string messageText)
 {
     this.mailFrom = from;
     //this.mailTo = recipients;
     this.mailSubject = subject;
     this.mailBody    = messageText;
     //
     lock (smtpSyncLock)
         using (var message = new System.Net.Mail.MailMessage())
         {
             string[] mailRecipients = recipients.Split(';');
             for (int e = 0; e < mailRecipients.Length; e++)
             {
                 message.To.Add(mailRecipients[e]);
             }
             message.Subject = this.mailSubject;
             message.From    = new MailAddress(this.mailFrom);
             message.Body    = this.mailBody;
             //
             for (int a = 0; a < attachments.Count; a++)
             {
                 var attachment = new Attachment(
                     new MemoryStream(attachments.ElementAt(a).Value),
                     attachments.ElementAt(a).Key
                     );
                 message.Attachments.Add(attachment);
             }
             //
             if (this.mailService == "")
             {
                 // this is a System Parameter
                 var spSmtpServer = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                 {
                     return(mp.Name == "Messaging.Email.SmtpServer");
                 });
                 if (spSmtpServer != null)
                 {
                     this.mailService = spSmtpServer.Value;
                 }
             }
             if (this.mailPort == -1)
             {
                 // this is a System Parameter
                 var spSmtpPort = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                 {
                     return(mp.Name == "Messaging.Email.SmtpPort");
                 });
                 if (spSmtpPort != null && spSmtpPort.DecimalValue > 0)
                 {
                     this.mailPort = (int)spSmtpPort.DecimalValue;
                 }
             }
             if (this.mailSsl == -1)
             {
                 // this is a System Parameter
                 var spSmtpUseSsl = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                 {
                     return(mp.Name == "Messaging.Email.SmtpUseSsl");
                 });
                 if (spSmtpUseSsl != null && spSmtpUseSsl.Value.ToLower() == "true")
                 {
                     this.mailSsl = 1;
                 }
             }
             var credentials = this.networkCredential;
             if (credentials == null)
             {
                 var username = "";
                 // this is a System Parameter
                 var spSmtpUserName = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                 {
                     return(mp.Name == "Messaging.Email.SmtpUserName");
                 });
                 if (spSmtpUserName != null)
                 {
                     username = spSmtpUserName.Value;
                 }
                 if (!String.IsNullOrWhiteSpace(username))
                 {
                     var password = "";
                     // this is a System Parameter
                     var spSmtpPassword = homegenie.Parameters.Find(delegate(ModuleParameter mp)
                     {
                         return(mp.Name == "Messaging.Email.SmtpPassword");
                     });
                     if (spSmtpPassword != null)
                     {
                         password = spSmtpPassword.Value;
                     }
                     credentials = new NetworkCredential(username, password);
                 }
             }
             //
             using (var smtpClient = new SmtpClient(this.mailService))
             {
                 try
                 {
                     smtpClient.Credentials    = credentials;
                     smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                     if (this.mailPort > 0)
                     {
                         smtpClient.Port = this.mailPort;
                     }
                     if (this.mailSsl > 0)
                     {
                         smtpClient.EnableSsl = (this.mailSsl == 1);
                     }
                     smtpClient.Send(message);
                     attachments.Clear();
                 }
                 catch (Exception ex)
                 {
                     HomeGenieService.LogError(
                         Domains.HomeAutomation_HomeGenie_Automation,
                         this.GetType().Name,
                         ex.Message,
                         "Exception.StackTrace",
                         ex.StackTrace
                         );
                     return(false);
                 }
                 finally
                 {
                     smtpClient.Dispose();
                 }
             }
         }
     return(true);
 }
コード例 #17
0
ファイル: NetHelper.cs プロジェクト: orf53975/HomeGenie
 public NetHelper(HomeGenieService hg)
 {
     _homegenie = hg;
 }
コード例 #18
0
ファイル: Statistics.cs プロジェクト: Qu3uk/HomeGenie
 public Statistics(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #19
0
 public StatisticsLogger(HomeGenieService hg)
 {
     homegenie   = hg;
     dbSizeLimit = hg.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes * 1024 * 1024;
     statsTimeResolutionSeconds = hg.SystemConfiguration.HomeGenie.Statistics.StatisticsTimeResolutionSeconds;
 }
コード例 #20
0
 public Automation(HomeGenieService hg)
 {
     _hg = hg;
 }
コード例 #21
0
 public ProgramManager(HomeGenieService hg)
 {
     homegenie        = hg;
     macroRecorder    = new MacroRecorder(this);
     schedulerService = new SchedulerService(this);
 }
コード例 #22
0
 public Logging(HomeGenieService hg)
 {
     _hg = hg;
 }
コード例 #23
0
ファイル: Statistics.cs プロジェクト: raptorjr/HomeGenie-BE
 public Statistics(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #24
0
ファイル: Automation.cs プロジェクト: mtudury/HomeGenie
 public Automation(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #25
0
 public VirtualMeter(HomeGenieService hg)
 {
     homegenie = hg;
     Start();
 }
コード例 #26
0
 public Interconnection(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #27
0
 public void SetHost(HomeGenieService hg)
 {
     homegenie = hg;
     // force ScriptingHost assignment
     this.Type = codeType;
 }
コード例 #28
0
 public EventsHelper(HomeGenieService hg, int programId)
 {
     homegenie   = hg;
     myProgramId = programId;
 }
コード例 #29
0
 public ModuleHelper(HomeGenieService hg, Module module)
     : base(hg)
 {
     this.module = module;
 }
コード例 #30
0
ファイル: SettingsHelper.cs プロジェクト: yply/HomeGenie
 public SettingsHelper(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #31
0
ファイル: Interconnection.cs プロジェクト: Qu3uk/HomeGenie
 public Interconnection(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #32
0
ファイル: Config.cs プロジェクト: Solertis/HomeGenie
        internal static ProgramBlock ProgramImport(HomeGenieService homegenie, int newPid, string archiveName, string groupName)
        {
            ProgramBlock newProgram;
            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 = groupName;
            homegenie.ProgramManager.ProgramAdd(newProgram);

            newProgram.IsEnabled = false;
            newProgram.ScriptErrors = "";
            newProgram.Engine.SetHost(homegenie);

            if (newProgram.Type.ToLower() != "arduino")
            {
                homegenie.ProgramManager.CompileScript(newProgram);
            }
            return newProgram;
        }
コード例 #33
0
ファイル: NetHelper.cs プロジェクト: orf53975/HomeGenie
        /// <summary>
        /// Sends an E-Mail.
        /// </summary>
        /// <returns><c>true</c>, if message was sent, <c>false</c> otherwise.</returns>
        /// <param name="from">Message sender.</param>
        /// <param name="recipients">Message recipients.</param>
        /// <param name="subject">Message subject.</param>
        /// <param name="messageText">Message text.</param>
        public bool SendMessage(string from, string recipients, string subject, string messageText)
        {
            Log.Trace("SendMessage: called for recipients {0}", recipients);
            var mailFrom    = from;
            var mailSubject = subject;
            var mailBody    = messageText;

            //
            Log.Trace("SendMessage: getting smtpSyncLock");
            lock (_smtpSyncLock)
            {
                Log.Trace("SendMessage: got smtpSyncLock");
                using (var message = new MailMessage())
                {
                    var mailRecipients = recipients.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var recipient in mailRecipients)
                    {
                        message.To.Add(recipient);
                    }
                    message.Subject = mailSubject;
                    message.From    = new MailAddress(mailFrom);
                    message.Body    = mailBody;
                    //
                    for (var a = 0; a < _attachments.Count; a++)
                    {
                        var attachment = new Attachment(new MemoryStream(_attachments.ElementAt(a).Value), _attachments.ElementAt(a).Key);
                        message.Attachments.Add(attachment);
                    }
                    //
                    if (_mailService == "")
                    {
                        // this is a System Parameter
                        var spSmtpServer = _homegenie.Parameters.Find(mp => mp.Name == "Messaging.Email.SmtpServer");
                        if (spSmtpServer != null)
                        {
                            _mailService = spSmtpServer.Value;
                        }
                    }
                    if (_mailPort == -1)
                    {
                        // this is a System Parameter
                        var spSmtpPort = _homegenie.Parameters.Find(mp => mp.Name == "Messaging.Email.SmtpPort");
                        if (spSmtpPort != null && spSmtpPort.DecimalValue > 0)
                        {
                            _mailPort = (int)spSmtpPort.DecimalValue;
                        }
                    }
                    if (!_mailSsl.HasValue)
                    {
                        // this is a System Parameter
                        var spSmtpUseSsl = _homegenie.Parameters.Find(mp => mp.Name == "Messaging.Email.SmtpUseSsl");
                        if (spSmtpUseSsl != null && (spSmtpUseSsl.Value.ToLower() == "true" ||
                                                     spSmtpUseSsl.Value.ToLower() == "on" ||
                                                     spSmtpUseSsl.DecimalValue == 1))
                        {
                            _mailSsl = true;
                        }
                    }
                    var credentials = _networkCredential;
                    if (credentials == null)
                    {
                        var username = "";
                        // this is a System Parameter
                        var spSmtpUserName = _homegenie.Parameters.Find(mp => mp.Name == "Messaging.Email.SmtpUserName");
                        if (spSmtpUserName != null)
                        {
                            username = spSmtpUserName.Value;
                        }
                        if (!string.IsNullOrWhiteSpace(username))
                        {
                            var password = "";
                            // this is a System Parameter
                            var spSmtpPassword = _homegenie.Parameters.Find(mp => mp.Name == "Messaging.Email.SmtpPassword");
                            if (spSmtpPassword != null)
                            {
                                password = spSmtpPassword.Value;
                            }
                            credentials = new NetworkCredential(username, password);
                        }
                    }
                    //

                    using (var smtpClient = new SmtpClient(_mailService))
                    {
                        try
                        {
                            smtpClient.Credentials    = credentials;
                            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                            if (_mailPort > 0)
                            {
                                smtpClient.Port = _mailPort;
                            }
                            smtpClient.EnableSsl = _mailSsl == true;

                            Log.Trace("SendMessage: going to send email {0} using mailService '{1}', port '{2}', credentials {3}, using SSL = {4}",
                                      message.ToString(), _mailService, _mailPort, credentials.ToString(), smtpClient.EnableSsl);
                            smtpClient.Send(message);
                            Log.Trace("Email sent");
                            _attachments.Clear();
                        }
                        catch (Exception ex)
                        {
                            Log.Trace(ex, "SendMessage: error sending email {0}");
                            Log.Error(ex);
                            HomeGenieService.LogError(Domains.HomeAutomation_HomeGenie_Automation, GetType().Name, ex.Message, "Exception.StackTrace", ex.StackTrace);
                            return(false);
                        }
                        finally
                        {
                            Log.Trace("SendMessage: disposing smtpClient");
                            smtpClient.Dispose();
                        }
                    }
                }
            }

            return(true);
        }
コード例 #34
0
ファイル: Logging.cs プロジェクト: jarrettv/HomeGenie
 public Logging(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #35
0
ファイル: BackupManager.cs プロジェクト: mtudury/HomeGenie
 public BackupManager(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #36
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            Console.OutputEncoding = Encoding.UTF8;

            /* Change current culture
             * CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
             * System.Threading.Thread.CurrentThread.CurrentCulture = culture;
             * System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
             */
            var os       = Environment.OSVersion;
            var platform = os.Platform;

            // TODO: run "uname" to determine OS type
            if (platform == PlatformID.Unix)
            {
                var libusblink = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "libusb-1.0.so");

                // RaspBerry Pi armel dependency check and needed symlink
                // TODO: check for armhf version
                if (File.Exists("/lib/arm-linux-gnueabi/libusb-1.0.so.0.1.0") && !File.Exists(libusblink))
                {
                    ShellCommand("ln", " -s \"/lib/arm-linux-gnueabi/libusb-1.0.so.0.1.0\" \"" + libusblink + "\"");
                }

                // Debian/Ubuntu 64bit dependency and needed symlink check
                if (File.Exists("/lib/x86_64-linux-gnu/libusb-1.0.so.0") && !File.Exists(libusblink))
                {
                    ShellCommand("ln", " -s \"/lib/x86_64-linux-gnu/libusb-1.0.so.0\" \"" + libusblink + "\"");
                }

                // lirc
                var liblirclink = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "liblirc_client.so");
                if (File.Exists("/usr/lib/liblirc_client.so") && !File.Exists(liblirclink))
                {
                    ShellCommand("ln", " -s \"/usr/lib/liblirc_client.so\" \"" + liblirclink + "\"");
                }
                else if (File.Exists("/usr/lib/liblirc_client.so.0") && !File.Exists(liblirclink))
                {
                    ShellCommand("ln", " -s \"/usr/lib/liblirc_client.so.0\" \"" + liblirclink + "\"");
                }

                // video 4 linux interop
                if (Raspberry.Board.Current.IsRaspberryPi)
                {
                    ShellCommand("cp", " -f \"" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "v4l/raspbian_libCameraCaptureV4L.so") + "\" \"" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "libCameraCaptureV4L.so") + "\"");
                    //
                    //if (File.Exists("/usr/lib/libgdiplus.so") && !File.Exists("/usr/local/lib/libgdiplus.so"))
                    //{
                    //    ShellCommand("ln", " -s \"/usr/lib/libgdiplus.so\" \"/usr/local/lib/libgdiplus.so\"");
                    //}
                }
                else // fallback (ubuntu and other 64bit debians)
                {
                    string v4lfile = "v4l/debian64_libCameraCaptureV4L.so.gd3";
                    if (!File.Exists("/usr/lib/x86_64-linux-gnu/libgd.so.3"))
                    {
                        v4lfile = "v4l/debian64_libCameraCaptureV4L.so";
                    }
                    ShellCommand(
                        "cp",
                        " -f \"" + Path.Combine(
                            AppDomain.CurrentDomain.BaseDirectory,
                            v4lfile
                            ) + "\" \"" + Path.Combine(
                            AppDomain.CurrentDomain.BaseDirectory,
                            "libCameraCaptureV4L.so"
                            ) + "\""
                        );
                }
                //
                if (!File.Exists("~/.lircrc"))
                {
                    var lircrc = "begin\n" +
                                 "        prog = homegenie\n" +
                                 "        button = KEY_1\n" +
                                 "        repeat = 3\n" +
                                 "        config = KEY_1\n" +
                                 "end\n";
                    try
                    {
                        File.WriteAllText("~/.lircrc", lircrc);
                    }
                    catch { }
                }
            }
            //
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            //
            AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles = "true";
            //
            _homegenie = new HomeGenieService();
            //
            do
            {
                System.Threading.Thread.Sleep(2000);
            } while (_isrunning);
            //
            System.Threading.Thread.Sleep(2000);
            //
            ShutDown();
        }
コード例 #37
0
ファイル: ProgramHelperBase.cs プロジェクト: ardasurya/IoT
 public ProgramHelperBase(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #38
0
ファイル: Config.cs プロジェクト: jarrettv/HomeGenie
 public Config(HomeGenieService hg)
 {
     homegenie = hg;
 }
コード例 #39
0
        private void logInterval_Elapsed(object sender, ElapsedEventArgs eventArgs)
        {
            var end     = DateTime.UtcNow;
            var modules = (TsList <Module>)homegenie.Modules; //.DeepClone();

            for (int m = 0; m < modules.Count; m++)
            {
                var module = modules[m];
                for (int p = 0; p < module.Properties.Count; p++)
                {
                    var parameter = module.Properties[p];
                    if (parameter.Statistics.Values.Count > 0)
                    {
                        var values = parameter.Statistics.Values.FindAll(sv => (sv.Timestamp.Ticks <= end.Ticks && sv.Timestamp.Ticks > parameter.Statistics.LastProcessedTimestap.Ticks));
                        if (values.Count > 0)
                        {
                            double average = (values.Sum(d => d.Value) / values.Count);
                            //
                            //TODO: improve db file age/size check for archiving old data
                            //
                            try
                            {
                                string dbName   = GetStatisticsDatabaseName();
                                var    fileInfo = new FileInfo(dbName);
                                if (fileInfo.Length > dbSizeLimit)
                                {
                                    ResetStatisticsDatabase();
                                    // TODO: Test method below, then use that instead of rsetting whole database.
                                    //CleanOldValuesFromStatisticsDatabase();
                                }
                                //
                                var dbCommand = dbConnection.CreateCommand();
                                // "TimeStart","TimeEnd","Domain","Address","Parameter","AverageValue", "CustomData"
                                dbCommand.Parameters.Add(new SQLiteParameter("@timestart", DateTimeToSQLite(parameter.Statistics.LastProcessedTimestap)));
                                dbCommand.Parameters.Add(new SQLiteParameter("@timeend", DateTimeToSQLite(end)));
                                dbCommand.Parameters.Add(new SQLiteParameter("@domain", module.Domain));
                                dbCommand.Parameters.Add(new SQLiteParameter("@address", module.Address));
                                dbCommand.Parameters.Add(new SQLiteParameter("@parameter", parameter.Name));
                                dbCommand.Parameters.Add(new SQLiteParameter("@avgvalue", average.ToString(CultureInfo.InvariantCulture)));
                                dbCommand.Parameters.Add(new SQLiteParameter("@data", module.Name));
                                dbCommand.CommandText = "INSERT INTO ValuesHist VALUES (@timestart, @timeend, @domain, @address, @parameter, @avgvalue, @data)";
                                dbCommand.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                HomeGenieService.LogError(
                                    Domains.HomeAutomation_HomeGenie,
                                    "Service.StatisticsLogger",
                                    "Database Error",
                                    "Exception.StackTrace",
                                    String.Format("{0}: {1}", ex.Message, ex.StackTrace)
                                    );
                                // try close/reopen (perhaps some locking issue)
                                CloseStatisticsDatabase();
                                OpenStatisticsDatabase();
                            }
                            //
                            // reset statistics history sample
                            //
                            parameter.Statistics.LastProcessedTimestap = end;
                            parameter.Statistics.Values.Clear();
                        }
                    }
                }
            }
        }