private void AddStatToDb(IReadOnlyCollection <ValueStatistics.StatValue> values, Module module, ModuleParameter parameter, DateTime end) { var average = values.Sum(d => d.Value) / values.Count; try { _statisticsRepository.AddStat(new StatisticsDbEntry { TimeStart = parameter.Statistics.LastProcessedTimestap, TimeEnd = end, Domain = module.Domain, Address = module.Address, Parameter = parameter.Name, AvgValue = average, ModuleName = module.Name }); } catch (Exception ex) { HomeGenieService.LogError( Domains.HomeAutomation_HomeGenie, "Service.StatisticsLogger", "Error adding stats to the database", "Exception.StackTrace", $"{ex.Message}: {ex.StackTrace}" ); } }
/// <summary> /// Opens the statistics database. /// </summary> /// <returns><c>true</c>, if statistics database was opened, <c>false</c> otherwise.</returns> internal bool OpenStatisticsDatabase() { bool success = false; if (dbConnection == null) { try { dbConnection = new SQLiteConnection("URI=file:" + GetStatisticsDatabaseName()); dbConnection.Open(); success = true; } catch (Exception ex) { HomeGenieService.LogError( Domains.HomeAutomation_HomeGenie, "Service.StatisticsLogger", "Database Error", "Exception.StackTrace", String.Format("{0}: {1}", ex.Message, ex.StackTrace) ); } } return(success); }
/// <summary> /// Removes older values to keep DB size within configured size limit. /// </summary> /// <param name="daysToKeep">Records older than this number of days are removed.</param> private void CleanOldValuesFromStatisticsDatabase(int daysToKeep) { if (daysToKeep <= 0) { return; } var thresholdDate = _dateTime.UtcNow.Date.AddDays(-daysToKeep); try { _statisticsRepository.CleanOldValues(thresholdDate); HomeGenieService.LogDebug( Domains.HomeAutomation_HomeGenie, "Service.StatisticsLogger", "Cleaned old values from database.", "DayThreshold", thresholdDate.ToString("O") ); } catch (Exception ex) { HomeGenieService.LogError( Domains.HomeAutomation_HomeGenie, "Service.StatisticsLogger", "Error cleaning old stats from the database", "Exception.StackTrace", $"{ex.Message}: {ex.StackTrace}" ); } }
public Dictionary <string, List <StatGraphEntry> > GetMultipleModulesDetailedStats( string parameterName, DateTime startDate, DateTime endDate) { try { var allModulesStats = _statisticsRepository.GetStatsByParameter(parameterName, startDate, endDate); var result = allModulesStats.GroupBy(x => string.IsNullOrEmpty(x.ModuleName) ? $"{x.Domain}.{x.Address}" : x.ModuleName).ToDictionary( x => x.Key, x => x.Select(stat => new StatGraphEntry { Timestamp = Utility.DateToJavascript(stat.TimeStart), Value = stat.AvgValue }).ToList()); return(result); } catch (Exception ex) { HomeGenieService.LogError( Domains.HomeAutomation_HomeGenie, "Service.StatisticsLogger", "Error getting multiple modules detailed stats from the database", "Exception.StackTrace", $"{ex.Message}: {ex.StackTrace}" ); return(null); } }
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); }
/// <summary> /// Raise a module parameter event and set the parameter with the specified value. /// </summary> /// <returns>ProgramHelper.</returns> /// <param name="module">The module source of this event.</param> /// <param name="parameter">Parameter name.</param> /// <param name="value">The new parameter value to set.</param> /// <param name="description">Event description.</param> public ProgramHelper RaiseEvent(ModuleHelper sourceModule, string parameter, string value, string description) { // TODO: deprecate this method, use ModuleHelper.RaiseEvent instead try { var actionEvent = homegenie.MigService.GetEvent( sourceModule.Instance.Domain, sourceModule.Instance.Address, description, parameter, value ); homegenie.RaiseEvent(myProgramId, actionEvent); } catch (Exception ex) { HomeGenieService.LogError( programModule.Domain, programModule.Address, ex.Message, "Exception.StackTrace", ex.StackTrace ); } return(this); }
/// <summary> /// Raise a module parameter event and set the parameter with the specified value. /// </summary> /// <returns>ModuleHelper.</returns> /// <param name="parameter">Parameter name.</param> /// <param name="value">The new parameter value to set.</param> /// <param name="description">Event description.</param> public ModuleHelper RaiseEvent(string parameter, string value, string description) { try { var actionEvent = homegenie.MigService.GetEvent( this.Instance.Domain, this.Instance.Address, description, parameter, value ); homegenie.RaiseEvent(this, actionEvent); } catch (Exception ex) { HomeGenieService.LogError( this.Instance.Domain, this.Instance.Address, ex.Message, "Exception.StackTrace", ex.StackTrace ); } return(this); }
/// <summary> /// Raise a parameter event and set the parameter with the specified value. /// </summary> /// <returns>ProgramHelper.</returns> /// <param name="parameter">Parameter name.</param> /// <param name="value">The new parameter value to set.</param> /// <param name="description">Event description.</param> public ProgramHelper RaiseEvent(string parameter, string value, string description) { try { var actionEvent = homegenie.MigService.GetEvent( programModule.Domain, programModule.Address, description, parameter, value ); homegenie.RaiseEvent(myProgramId, actionEvent); //homegenie.SignalModulePropertyChange(this, programModule, actionEvent); } catch (Exception ex) { HomeGenieService.LogError( programModule.Domain, programModule.Address, ex.Message, "Exception.StackTrace", ex.StackTrace ); } return(this); }
/// <summary> /// Playbacks a wave file. /// </summary> /// <param name="waveUrl">URL of the audio wave file to play.</param> public ProgramHelperBase Play(string waveUrl) { try { string outputDirectory = Utility.GetTmpFolder(); string file = Path.Combine(outputDirectory, "_wave_tmp." + Path.GetExtension(waveUrl)); using (var webClient = new WebClient()) { byte[] audiodata = webClient.DownloadData(waveUrl); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } if (File.Exists(file)) { File.Delete(file); } var stream = File.OpenWrite(file); stream.Write(audiodata, 0, audiodata.Length); stream.Close(); webClient.Dispose(); } SpeechUtils.Play(file); } catch (Exception e) { HomeGenieService.LogError(e); } return(this); }
internal static void PicoSay(string sentence, string locale) { try { var wavFile = Path.Combine(GetTmpFolder(), "_synthesis_tmp.wav"); if (File.Exists(wavFile)) { File.Delete(wavFile); } Process.Start(new ProcessStartInfo(picoPath, " -w " + wavFile + " -l " + locale + " \"" + sentence + "\"") { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory, UseShellExecute = false }).WaitForExit(); if (File.Exists(wavFile)) { Play(wavFile); } } catch (Exception e) { HomeGenieService.LogError(e); } }
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); } }
/// <summary> /// Call the web service url and returns the server response as binary data. /// </summary> /// <returns>Byte array containing the raw server response.</returns> public byte[] GetBytes() { byte[] responseBytes = null; //lock(httpSyncLock) using (var webClient = new WebClient()) { try { if (this.networkCredential != null) { webClient.Credentials = networkCredential; } else if (this.defaultCredentials) { webClient.UseDefaultCredentials = true; } webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"); if (customHeaders.Count > 0) { webClient.Headers.Add(customHeaders); } responseBytes = webClient.DownloadData(this.webServiceUrl); } catch (Exception ex) { HomeGenieService.LogError(Domains.HomeAutomation_HomeGenie_Automation, this.GetType().Name, ex.Message, "Exception.StackTrace", ex.StackTrace); } finally { webClient.Dispose(); } } return(responseBytes); }
/// <summary> /// Call the web service url. /// </summary> /// <returns>String containing the server response.</returns> public string Call() { string returnvalue = ""; //lock(httpSyncLock) using (var webClient = new WebClient()) { try { webClient.Encoding = Encoding.UTF8; if (this.networkCredential != null) { webClient.Credentials = networkCredential; } else if (this.defaultCredentials) { webClient.UseDefaultCredentials = true; } webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"); if (customHeaders.Count > 0) { webClient.Headers.Add(customHeaders); } if (this.method == "") { returnvalue = webClient.DownloadString(this.webServiceUrl); } else { byte[] data = Encoding.UTF8.GetBytes(this.putData); byte[] responsebytes = webClient.UploadData(this.webServiceUrl, this.method, data); returnvalue = Encoding.UTF8.GetString(responsebytes); } } catch (Exception ex) { HomeGenieService.LogError( Domains.HomeAutomation_HomeGenie_Automation, this.GetType().Name, ex.Message, "Exception.StackTrace", ex.StackTrace ); } finally { webClient.Dispose(); } } return(returnvalue); }
public void Say(string sentence, string locale = null, bool goAsync = false) { if (String.IsNullOrWhiteSpace(locale)) { locale = System.Threading.Thread.CurrentThread.CurrentCulture.Name; } try { Utility.Say(sentence, locale, goAsync); } catch (Exception e) { HomeGenieService.LogError(e); } }
public void RoutePropertyChangedEvent(object eventData) { var moduleEvent = (RoutedEvent)eventData; var moduleHelper = new Automation.Scripting.ModuleHelper(homegenie, moduleEvent.Module); string originalValue = moduleEvent.Parameter.Value; for (int p = 0; p < Programs.Count; p++) { var program = Programs[p]; if (program == null || !program.IsEnabled || !isEngineEnabled) { continue; } if ((moduleEvent.Sender == null || !moduleEvent.Sender.Equals(program))) { try { program.Engine.RoutedEventAck.Set(); if (program.Engine.ModuleChangedHandler != null && moduleEvent.Parameter != null) // && proceed) { bool handled = !program.Engine.ModuleChangedHandler(moduleHelper, moduleEvent.Parameter); if (handled) { // stop routing event if "false" is returned MigService.Log.Debug("Event propagation halted by automation program '{0}' ({1}) (Name={2}, OldValue={3}, NewValue={4})", program.Name, program.Address, moduleEvent.Parameter.Name, originalValue, moduleEvent.Parameter.Value); break; } else if (moduleEvent.Parameter.Value != originalValue) { // If manipulated, the event is not routed anymore. MigService.Log.Debug("Event propagation halted - parameter manipulated by automation program '{0}' ({1}) (Name={2}, OldValue={3}, NewValue={4})", program.Name, program.Address, moduleEvent.Parameter.Name, originalValue, moduleEvent.Parameter.Value); break; } } } catch (System.Exception ex) { HomeGenieService.LogError( program.Domain, program.Address.ToString(), ex.Message, "Exception.StackTrace", ex.StackTrace ); } } } }
/// <summary> /// Playbacks a synthesized voice message from speaker. /// </summary> /// <param name="sentence">Message to output.</param> /// <param name="locale">Language locale string (eg. "en-US", "it-IT", "en-GB", "nl-NL",...).</param> /// <param name="goAsync">If true, the command will be executed asyncronously.</param> /// <remarks /> /// <example> /// Example: /// <code> /// Program.Say("The garage door has been opened", "en-US"); /// </code> /// </example> public ProgramHelperBase Say(string sentence, string locale = null, bool goAsync = false) { if (String.IsNullOrWhiteSpace(locale)) { locale = Thread.CurrentThread.CurrentCulture.Name; } try { SpeechUtils.Say(sentence, locale, goAsync); } catch (Exception e) { HomeGenieService.LogError(e); } return(this); }
internal static Thread RunAsyncTask(AsyncFunction functionBlock) { var asyncTask = new Thread(() => { try { functionBlock(); } catch (Exception ex) { HomeGenieService.LogError(Domains.HomeAutomation_HomeGenie, "Service.Utility.RunAsyncTask", ex.Message, "Exception.StackTrace", ex.StackTrace); } }); asyncTask.Start(); return asyncTask; }
/// <summary> /// Resets the statistics database. /// </summary> public void ResetDatabase() { try { _statisticsRepository.ResetStatisticsDatabase(); } catch (Exception ex) { HomeGenieService.LogError( Domains.HomeAutomation_HomeGenie, "Service.StatisticsLogger", "Error resetting database", "Exception.StackTrace", $"{ex.Message}: {ex.StackTrace}" ); } }
private bool CheckAppInstance() { bool success = false; if (programDomain != null) { success = true; } else { try { // Creating app domain programDomain = AppDomain.CurrentDomain; assemblyType = appAssembly.GetType("HomeGenie.Automation.Scripting.ScriptingInstance"); assembly = Activator.CreateInstance(assemblyType); MethodInfo miSetHost = assemblyType.GetMethod("SetHost"); miSetHost.Invoke(assembly, new object[2] { homegenie, programBlock.Address }); methodRun = assemblyType.GetMethod("Run", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); // TODO: v1.1 !!!IMPORTANT!!! the method EvaluateCondition will be renamed to EvaluateStartupCode, // TODO: v1.1 !!!IMPORTANT!!! so if EvaluateCondition is not found look for EvaluateStartupCode method instead methodEvaluateCondition = assemblyType.GetMethod("EvaluateCondition", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); methodReset = assemblyType.GetMethod("Reset"); success = true; } catch (Exception ex) { HomeGenieService.LogError( Domains.HomeAutomation_HomeGenie_Automation, programBlock.Address.ToString(), ex.Message, "Exception.StackTrace", ex.StackTrace ); } } return(success); }
private bool CheckAppInstance() { var success = false; if (_programDomain != null) { success = true; } else { try { // Creating app domain _programDomain = AppDomain.CurrentDomain; _assemblyType = _scriptAssembly.GetType("HomeGenie.Automation.Scripting.ScriptingInstance"); _scriptInstance = Activator.CreateInstance(_assemblyType); var miSetHost = _assemblyType.GetMethod("SetHost"); miSetHost.Invoke(_scriptInstance, new object[2] { HomeGenie, ProgramBlock.Address }); _methodRun = _assemblyType.GetMethod("Run", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); _methodSetup = _assemblyType.GetMethod("Setup", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); _methodReset = _assemblyType.GetMethod("Reset"); success = true; } catch (Exception ex) { HomeGenieService.LogError( Domains.HomeAutomation_HomeGenie_Automation, ProgramBlock.Address.ToString(), ex.Message, "Exception.StackTrace", ex.StackTrace ); } } return(success); }
internal static void GoogleVoiceSay(string sentence, string locale) { try { var mp3File = Path.Combine(GetTmpFolder(), "_synthesis_tmp.mp3"); using (var client = new WebClient()) { client.Encoding = UTF8Encoding.UTF8; client.Headers.Add("Referer", "http://translate.google.com"); var audioData = client.DownloadData("http://translate.google.com/translate_tts?ie=UTF-8&tl=" + Uri.EscapeDataString(locale) + "&q=" + Uri.EscapeDataString(sentence) + "&client=homegenie&ts=" + DateTime.UtcNow.Ticks); if (File.Exists(mp3File)) { File.Delete(mp3File); } var stream = File.OpenWrite(mp3File); stream.Write(audioData, 0, audioData.Length); stream.Close(); client.Dispose(); } var wavFile = mp3File.Replace(".mp3", ".wav"); Process.Start(new ProcessStartInfo("lame", "--decode \"" + mp3File + "\" \"" + wavFile + "\"") { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory, UseShellExecute = false }).WaitForExit(); if (File.Exists(mp3File)) { Play(wavFile); } } catch (Exception e) { HomeGenieService.LogError(e); } }
public void RoutePropertyChangedEvent(object eventData) { var moduleEvent = (RoutedEvent)eventData; var moduleHelper = new Scripting.ModuleHelper(hgService, moduleEvent.Module); for (int p = 0; p < Programs.Count; p++) { var program = Programs[p]; if (program == null || !program.IsEnabled || !isEngineEnabled) { continue; } if ((moduleEvent.Sender == null || !moduleEvent.Sender.Equals(program))) { try { program.Engine.RoutedEventAck.Set(); if (program.Engine.ModuleChangedHandler != null && moduleEvent.Parameter != null) // && proceed) { var param = moduleEvent.Parameter.DeepClone(); bool handled = !program.Engine.ModuleChangedHandler(moduleHelper, param); if (handled) { // stop routing event if "false" is returned MigService.Log.Debug("Event propagation halted by automation program '{0}' ({1}) (Name={2})", program.Name, program.Address, param.Name); break; } } } catch (Exception ex) { HomeGenieService.LogError( program.Domain, program.Address.ToString(), ex.Message, "Exception.StackTrace", ex.StackTrace ); } } } }
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); } }
/// <summary> /// Deletes the stat. /// </summary> /// <returns>The stat.</returns> /// <param name="startDate">Start date.</param> /// <param name="value">Value.</param> public bool DeleteStat(DateTime startDate, string value) { try { var doubleValue = Convert.ToDouble(value.Replace(',', '.'), CultureInfo.InvariantCulture); _statisticsRepository.DeleteStatByDateAndValue(startDate, doubleValue); return(true); } catch (Exception ex) { HomeGenieService.LogError( Domains.HomeAutomation_HomeGenie, "Service.StatisticsLogger", "Error deleting stat from the database", "Exception.StackTrace", $"{ex.Message}: {ex.StackTrace}" ); return(false); } }
private void RelocateProgramModule() { // force automation modules regeneration homegenie.modules_RefreshPrograms(); // try { programModule = homegenie.Modules.Find(rm => rm.Domain == myProgramDomain && rm.Address == myProgramId.ToString()); } catch (Exception ex) { HomeGenieService.LogError( myProgramDomain, myProgramId.ToString(), ex.Message, "Exception.StackTrace", ex.StackTrace ); } }
public void SignalPropertyChange(object sender, Module module, MigEvent eventData) { ModuleParameter parameter = null; try { // Lookup for the existing module parameter parameter = Utility.ModuleParameterGet(module, eventData.Property); if (parameter == null) { parameter = new ModuleParameter() { Name = eventData.Property, Value = eventData.Value.ToString() }; module.Properties.Add(parameter); } else { parameter.Value = eventData.Value.ToString(); } } catch (Exception ex) { HomeGenieService.LogError(ex); } var routedEvent = new RoutedEvent() { Sender = sender, Module = module, Parameter = parameter }; // Route event to Programs->ModuleIsChangingHandler if (RoutePropertyBeforeChangeEvent(routedEvent)) { // Route event to Programs->ModuleChangedHandler ThreadPool.QueueUserWorkItem(new WaitCallback(RoutePropertyChangedEvent), routedEvent); } }
/// <summary> /// Adds a "feature" field to modules matching the specified domain/type. /// Feature fields are used by automation programs to create own handled module parameters. /// This command should only appear inside a Program.Setup delegate. /// </summary> /// <returns> /// ProgramHelper. /// </returns> /// <param name='forDomains'> /// A string with comma separated list of domains of modules that will showing this input field. Use an empty string for all domains. /// </param> /// <param name='forModuleTypes'> /// A string with comma separated list of types of modules that will showing this input field. /// </param> /// <param name='parameterName'> /// Name of the module parameter bound to this feature field. /// </param> /// <param name='description'> /// Description for this input field. /// </param> /// <param name='type'> /// The type of this feature field (eg. "text", "password", "cron.text", ...). Each type can have different initialization options /// that are specified as ":" separated items. See html/ui/widgets folder for a list of possible types/options. /// </param> public ProgramHelper AddFeature( string forDomains, string forModuleTypes, string parameterName, string description, string type ) { var program = homegenie.ProgramManager.Programs.Find(p => p.Address.ToString() == myProgramId.ToString()); ProgramFeature feature = null; // try { feature = program.Features.Find(f => f.Property == parameterName); } catch (Exception ex) { HomeGenieService.LogError( myProgramDomain, myProgramId.ToString(), ex.Message, "Exception.StackTrace", ex.StackTrace ); } // if (feature == null) { feature = new ProgramFeature(); program.Features.Add(feature); } feature.FieldType = type; feature.Property = parameterName; feature.Description = description; feature.ForDomains = forDomains; feature.ForTypes = forModuleTypes; return(this); }
/// <summary> /// Return the feature field associated to the specified module parameter. /// </summary> /// <param name="propertyName">Parameter name.</param> public ProgramFeature Feature(string parameterName) { var program = homegenie.ProgramManager.Programs.Find(p => p.Address.ToString() == myProgramId.ToString()); ProgramFeature feature = null; // try { feature = program.Features.Find(f => f.Property == parameterName); } catch (Exception ex) { HomeGenieService.LogError( myProgramDomain, myProgramId.ToString(), ex.Message, "Exception.StackTrace", ex.StackTrace ); } // return(feature); }
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(); // Currently it deletes oldest 24 hours of data 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.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(); } } } } }
/// <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); }