/// <inheritdoc /> protected override async Task OnClientConnectedAsync(IWebSocketContext context) { cumulus.LogDebugMessage("WS Client Connect: " + context.RemoteEndPoint.Address.ToString() + ", Total clients: " + ConnectedClients); if (station != null) { // send an update right away so the client is not left waiting await station.sendWebSocketData(true); } await Task.CompletedTask; }
// Output the processed response as a JSON string public string ProcessJson(IHttpRequest request) { var rc = false; var query = request.Url.Query; cumulus.LogDebugMessage("API tag: Processing API JSON tag request"); cumulus.LogDataMessage($"API tag: Source = {request.RemoteEndPoint} Input string = {query}"); var output = new StringBuilder("{", query.Length * 2); try { // remove leading "?" and split on "&" var input = new List <string>(query.Substring(1).Split('&')); var parms = new Dictionary <string, string>(); if (input[0] == "rc") { input.RemoveAt(0); rc = true; } foreach (var tag in input) { if (rc) { parms.Add("webtag", tag); parms.Add("rc", "y"); } var val = webtags.GetWebTagText(tag, parms); output.Append($"\"{tag}\":\"{val}\","); if (rc) { parms.Clear(); } } if (output.Length > 1) { // remove trailing "," output.Remove(output.Length - 1, 1); } output.Append('}'); cumulus.LogDataMessage("API tag: Output string = " + output); } catch (Exception ex) { cumulus.LogMessage($"API tag: Error - {ex.Message}"); output.Append($"\"ERROR\":\"{ex.Message}\"}}"); } return(output.ToString()); }
// Output the processed response as a JSON string public string ProcessJson(string query) { var rc = false; cumulus.LogDebugMessage("API tag: Processing API JSON tag request"); cumulus.LogDataMessage("API tag: Input string = " + query); // remove leading "?" and split on "&" var input = new List <string>(query.Substring(1).Split('&')); var parms = new Dictionary <string, string>(); if (input[0] == "rc") { input.RemoveAt(0); rc = true; } var output = new StringBuilder("{", query.Length * 2); foreach (var tag in input) { if (rc) { parms.Add("webtag", tag); parms.Add("rc", "y"); } var val = webtags.GetWebTagText(tag, parms); output.Append($"\"{tag}\":\"{val}\","); if (rc) { parms.Clear(); } } if (output.Length > 1) { // remove trailing "," output.Remove(output.Length - 1, 1); } output.Append("}"); cumulus.LogDataMessage("API tag: Output string = " + output); return(output.ToString()); }
public static void UpdateMQTTfeed(string feedType) { var template = "mqtt/"; if (feedType == "Interval") { template += cumulus.MQTT.IntervalTemplate; } else { template += cumulus.MQTT.UpdateTemplate; } if (!File.Exists(template)) { return; } // use template file cumulus.LogDebugMessage($"MQTT: Using template - {template}"); // read the file var templateText = File.ReadAllText(template); var templateObj = templateText.FromJson <MqttTemplate>(); // process each of the topics in turn try { foreach (var feed in templateObj.topics) { var mqttTokenParser = new TokenParser { Encoding = new System.Text.UTF8Encoding(false) }; mqttTokenParser.OnToken += cumulus.TokenParserOnToken; mqttTokenParser.InputText = feed.data; string message = mqttTokenParser.ToStringFromString(); // send the message _ = SendMessageAsync(feed.topic, message, feed.retain); } } catch (Exception ex) { cumulus.LogMessage($"UpdateMQTTfeed: Error process the template file [{template}], error = {ex.Message}"); } }
internal string FtpNow(IHttpContext context) { try { var data = new StreamReader(context.Request.InputStream).ReadToEnd(); var json = WebUtility.UrlDecode(data); // Dead simple (dirty), there is only one setting at present! var includeGraphs = json.Contains("true"); if (string.IsNullOrEmpty(cumulus.FtpHostname)) { return("{\"result\":\"No FTP host defined\"}"); } if (cumulus.WebUpdating == 1) { cumulus.LogMessage("FTP Now: Warning, a previous web update is still in progress, first chance, skipping attempt"); return("{\"result\":\"A web update is already in progress\"}"); } if (cumulus.WebUpdating >= 2) { cumulus.LogMessage("FTP Now: Warning, a previous web update is still in progress, second chance, aborting connection"); if (cumulus.ftpThread.ThreadState == ThreadState.Running) { cumulus.ftpThread.Abort(); } // If enabled (re)generate the daily graph data files, and upload if (includeGraphs && cumulus.IncludeGraphDataFiles) { cumulus.LogDebugMessage("FTP Now: Generating the daily graph data files"); station.CreateEodGraphDataFiles(); cumulus.DailyGraphDataFilesNeedFTP = true; } cumulus.LogMessage("FTP Now: Trying new web update"); cumulus.WebUpdating = 1; cumulus.ftpThread = new Thread(cumulus.DoHTMLFiles) { IsBackground = true }; cumulus.ftpThread.Start(); return("{\"result\":\"An existing FTP process was aborted, and a new FTP process invoked\"}"); } // If enabled (re)generate the daily graph data files, and upload if (includeGraphs && cumulus.IncludeGraphDataFiles) { cumulus.LogDebugMessage("FTP Now: Generating the daily graph data files"); station.CreateEodGraphDataFiles(); cumulus.DailyGraphDataFilesNeedFTP = true; } cumulus.WebUpdating = 1; cumulus.ftpThread = new Thread(cumulus.DoHTMLFiles) { IsBackground = true }; cumulus.ftpThread.Start(); return("{\"result\":\"FTP process invoked\"}"); } catch (Exception ex) { cumulus.LogMessage($"FTP Now: {ex.Message}"); context.Response.StatusCode = 500; return($"{{\"result\":\"Error: {ex.Message}\"}}"); } }
public string UpdateConfig(IHttpContext context) { var errorMsg = ""; var json = ""; JsonWizard settings; cumulus.LogMessage("Updating settings from the First Time Wizard"); context.Response.StatusCode = 200; try { var data = new StreamReader(context.Request.InputStream).ReadToEnd(); // Start at char 5 to skip the "json:" prefix json = WebUtility.UrlDecode(data.Substring(5)); // de-serialize it to the settings structure settings = json.FromJson <JsonWizard>(); } catch (Exception ex) { var msg = "Error de-serializing Set-up Wizard Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Wizard Data: " + json); context.Response.StatusCode = 500; return(msg); } // process the settings try { cumulus.LogMessage("Updating internet settings"); // website settings try { cumulus.FtpOptions.Enabled = settings.internet.ftp.enabled; if (cumulus.FtpOptions.Enabled) { cumulus.FtpOptions.Directory = settings.internet.ftp.directory ?? string.Empty; cumulus.FtpOptions.Port = settings.internet.ftp.ftpport; cumulus.FtpOptions.Hostname = settings.internet.ftp.hostname ?? string.Empty; cumulus.FtpOptions.FtpMode = (Cumulus.FtpProtocols)settings.internet.ftp.sslftp; cumulus.FtpOptions.Password = settings.internet.ftp.password ?? string.Empty; cumulus.FtpOptions.Username = settings.internet.ftp.username ?? string.Empty; cumulus.FtpOptions.SshAuthen = settings.internet.ftp.sshAuth ?? string.Empty; cumulus.FtpOptions.SshPskFile = settings.internet.ftp.pskFile ?? string.Empty; } cumulus.FtpOptions.LocalCopyEnabled = settings.internet.copy.localcopy; if (cumulus.FtpOptions.LocalCopyEnabled) { cumulus.FtpOptions.LocalCopyFolder = settings.internet.copy.localcopyfolder; } // Now flag all the standard files to FTP/Copy or not // do not process last entry = wxnow.txt, it is not used by the standard site for (var i = 0; i < cumulus.StdWebFiles.Length - 1; i++) { cumulus.StdWebFiles[i].Create = cumulus.FtpOptions.Enabled || cumulus.FtpOptions.LocalCopyEnabled; cumulus.StdWebFiles[i].FTP = cumulus.FtpOptions.Enabled; cumulus.StdWebFiles[i].Copy = cumulus.FtpOptions.LocalCopyEnabled; } // and graph data files for (var i = 0; i < cumulus.GraphDataFiles.Length; i++) { cumulus.GraphDataFiles[i].Create = cumulus.FtpOptions.Enabled || cumulus.FtpOptions.LocalCopyEnabled; cumulus.GraphDataFiles[i].FTP = cumulus.FtpOptions.Enabled; cumulus.GraphDataFiles[i].Copy = cumulus.FtpOptions.LocalCopyEnabled; } // and EOD data files for (var i = 0; i < cumulus.GraphDataEodFiles.Length; i++) { cumulus.GraphDataEodFiles[i].Create = cumulus.FtpOptions.Enabled || cumulus.FtpOptions.LocalCopyEnabled; cumulus.GraphDataEodFiles[i].FTP = cumulus.FtpOptions.Enabled; cumulus.GraphDataEodFiles[i].Copy = cumulus.FtpOptions.LocalCopyEnabled; } // and Realtime files // realtime.txt is not used by the standard site //cumulus.RealtimeFiles[0].Create = cumulus.FtpOptions.Enabled || cumulus.FtpOptions.LocalCopyEnabled; //cumulus.RealtimeFiles[0].FTP = cumulus.FtpOptions.Enabled; //cumulus.RealtimeFiles[0].Copy = cumulus.FtpOptions.LocalCopyEnabled; // realtimegauges.txt IS used by the standard site cumulus.RealtimeFiles[1].Create = cumulus.FtpOptions.Enabled || cumulus.FtpOptions.LocalCopyEnabled; cumulus.RealtimeFiles[1].FTP = cumulus.FtpOptions.Enabled; cumulus.RealtimeFiles[1].Copy = cumulus.FtpOptions.LocalCopyEnabled; // and Moon image cumulus.MoonImage.Enabled = cumulus.FtpOptions.Enabled || cumulus.FtpOptions.LocalCopyEnabled; cumulus.MoonImage.Ftp = cumulus.FtpOptions.Enabled; cumulus.MoonImage.Copy = cumulus.FtpOptions.LocalCopyEnabled; if (cumulus.MoonImage.Enabled) { cumulus.MoonImage.CopyDest = cumulus.FtpOptions.LocalCopyFolder + "images" + cumulus.DirectorySeparator + "moon.png"; } // and NOAA reports cumulus.NOAAconf.Create = cumulus.FtpOptions.Enabled || cumulus.FtpOptions.LocalCopyEnabled; cumulus.NOAAconf.AutoFtp = cumulus.FtpOptions.Enabled; cumulus.NOAAconf.AutoCopy = cumulus.FtpOptions.LocalCopyEnabled; if (cumulus.NOAAconf.AutoCopy) { cumulus.NOAAconf.CopyFolder = cumulus.FtpOptions.LocalCopyFolder + "Reports"; } if (cumulus.NOAAconf.AutoFtp) { cumulus.NOAAconf.FtpFolder = cumulus.FtpOptions.Directory + (cumulus.FtpOptions.Directory.EndsWith("/") ? "" : "/") + "Reports"; } } catch (Exception ex) { var msg = "Error processing internet settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // web settings try { cumulus.RealtimeIntervalEnabled = settings.website.realtime.enabled; if (cumulus.RealtimeIntervalEnabled) { cumulus.FtpOptions.RealtimeEnabled = settings.website.realtime.enablerealtimeftp; cumulus.RealtimeInterval = settings.website.realtime.realtimeinterval * 1000; if (cumulus.RealtimeTimer.Interval != cumulus.RealtimeInterval) { cumulus.RealtimeTimer.Interval = cumulus.RealtimeInterval; } } cumulus.RealtimeTimer.Enabled = cumulus.RealtimeIntervalEnabled; if (!cumulus.RealtimeTimer.Enabled || !cumulus.FtpOptions.RealtimeEnabled) { cumulus.RealtimeTimer.Stop(); cumulus.RealtimeFTPDisconnect(); } cumulus.WebIntervalEnabled = settings.website.interval.enabled; if (cumulus.WebIntervalEnabled) { cumulus.FtpOptions.IntervalEnabled = settings.website.interval.enableintervalftp; cumulus.UpdateInterval = settings.website.interval.ftpinterval; if (cumulus.WebTimer.Interval != cumulus.UpdateInterval * 60 * 1000) { cumulus.WebTimer.Interval = cumulus.UpdateInterval * 60 * 1000; } } } catch (Exception ex) { var msg = "Error processing web settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Location try { cumulus.Altitude = settings.location.altitude; cumulus.AltitudeInFeet = (settings.location.altitudeunit == "feet"); cumulus.LocationName = settings.location.sitename ?? string.Empty; cumulus.LocationDesc = settings.location.description ?? string.Empty; cumulus.Latitude = settings.location.latitude; cumulus.LatTxt = degToString(cumulus.Latitude, true); cumulus.Longitude = settings.location.longitude; cumulus.LonTxt = degToString(cumulus.Longitude, false); } catch (Exception ex) { var msg = "Error processing Location settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Units try { if (cumulus.Units.Wind != settings.units.wind) { cumulus.Units.Wind = settings.units.wind; cumulus.ChangeWindUnits(); cumulus.WindDPlaces = cumulus.StationOptions.RoundWindSpeed ? 0 : cumulus.WindDPlaceDefaults[cumulus.Units.Wind]; cumulus.WindAvgDPlaces = cumulus.WindDPlaces; } if (cumulus.Units.Press != settings.units.pressure) { cumulus.Units.Press = settings.units.pressure; cumulus.ChangePressureUnits(); cumulus.PressDPlaces = cumulus.PressDPlaceDefaults[cumulus.Units.Press]; } if (cumulus.Units.Temp != settings.units.temp) { cumulus.Units.Temp = settings.units.temp; cumulus.ChangeTempUnits(); } if (cumulus.Units.Rain != settings.units.rain) { cumulus.Units.Rain = settings.units.rain; cumulus.ChangeRainUnits(); cumulus.RainDPlaces = cumulus.RainDPlaceDefaults[cumulus.Units.Rain]; } } catch (Exception ex) { var msg = "Error processing Units settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // data logging try { cumulus.DataLogInterval = settings.logs.loginterval; cumulus.RolloverHour = settings.logs.logrollover.time == "9am" ? 9 : 0; if (cumulus.RolloverHour == 9) { cumulus.Use10amInSummer = settings.logs.logrollover.summer10am; } } catch (Exception ex) { var msg = "Error processing Logging setting: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Station type try { if (cumulus.StationType != settings.station.stationtype) { cumulus.LogMessage("Station type changed, restart required"); cumulus.LogConsoleMessage("*** Station type changed, restart required ***", ConsoleColor.Yellow); } cumulus.StationType = settings.station.stationtype; cumulus.StationModel = settings.station.stationmodel; } catch (Exception ex) { var msg = "Error processing Station Type setting: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Davis VP/VP2/Vue try { if (settings.station.davisvp2 != null) { cumulus.DavisOptions.ConnectionType = settings.station.davisvp2.conntype; if (settings.station.davisvp2.tcpsettings != null) { cumulus.DavisOptions.IPAddr = settings.station.davisvp2.tcpsettings.ipaddress ?? string.Empty; cumulus.DavisOptions.PeriodicDisconnectInterval = settings.station.davisvp2.tcpsettings.disconperiod; } if (cumulus.DavisOptions.ConnectionType == 0) { cumulus.ComportName = settings.station.davisvp2.comportname; } // set defaults for Davis cumulus.UVdecimals = 1; if (settings.units.rain == 1) { cumulus.RainDPlaces = 2; } } } catch (Exception ex) { var msg = "Error processing Davis VP/VP2/Vue settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // WLL try { if (settings.station.daviswll != null) { cumulus.DavisOptions.ConnectionType = 2; // Always TCP/IP for WLL cumulus.WLLAutoUpdateIpAddress = settings.station.daviswll.network.autoDiscover; cumulus.DavisOptions.IPAddr = settings.station.daviswll.network.ipaddress ?? string.Empty; cumulus.WllApiKey = settings.station.daviswll.api.apiKey; cumulus.WllApiSecret = settings.station.daviswll.api.apiSecret; cumulus.WllStationId = settings.station.daviswll.api.apiStationId; cumulus.WllPrimaryRain = settings.station.daviswll.primary.rain; cumulus.WllPrimarySolar = settings.station.daviswll.primary.solar; cumulus.WllPrimaryTempHum = settings.station.daviswll.primary.temphum; cumulus.WllPrimaryUV = settings.station.daviswll.primary.uv; cumulus.WllPrimaryWind = settings.station.daviswll.primary.wind; } } catch (Exception ex) { var msg = "Error processing WLL settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // GW1000 connection details try { if (settings.station.gw1000 != null) { cumulus.Gw1000IpAddress = settings.station.gw1000.ipaddress; cumulus.Gw1000AutoUpdateIpAddress = settings.station.gw1000.autoDiscover; cumulus.Gw1000MacAddress = settings.station.gw1000.macaddress; } } catch (Exception ex) { var msg = "Error processing GW1000 settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // weatherflow connection details try { if (settings.station.weatherflow != null) { cumulus.WeatherFlowOptions.WFDeviceId = settings.station.weatherflow.deviceid; cumulus.WeatherFlowOptions.WFTcpPort = settings.station.weatherflow.tcpport; cumulus.WeatherFlowOptions.WFToken = settings.station.weatherflow.token; cumulus.WeatherFlowOptions.WFDaysHist = settings.station.weatherflow.dayshistory; } } catch (Exception ex) { var msg = $"Error processing WeatherFlow settings: {ex.Message}"; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // FineOffset try { if (settings.station.fineoffset != null) { cumulus.FineOffsetOptions.SyncReads = settings.station.fineoffset.syncreads; cumulus.FineOffsetOptions.ReadAvoidPeriod = settings.station.fineoffset.readavoid; } } catch (Exception ex) { var msg = "Error processing Fine Offset settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // EasyWeather try { if (settings.station.easyw != null) { cumulus.EwOptions.Interval = settings.station.easyw.interval; cumulus.EwOptions.Filename = settings.station.easyw.filename; } } catch (Exception ex) { var msg = "Error processing EasyWeather settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Instromet try { if (settings.station.imet != null) { cumulus.ComportName = settings.station.imet.comportname ?? cumulus.ComportName; cumulus.ImetOptions.BaudRate = settings.station.imet.baudrate; } } catch (Exception ex) { var msg = "Error processing Instromet settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // WMR928 try { if (settings.station.wmr928 != null) { cumulus.ComportName = settings.station.wmr928.comportname ?? cumulus.ComportName; } } catch (Exception ex) { var msg = "Error processing WMR928 settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Save the settings cumulus.WriteIniFile(); } catch (Exception ex) { var msg = "Error processing Wizard settings: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Station Data: " + json); errorMsg += msg; context.Response.StatusCode = 500; } return(context.Response.StatusCode == 200 ? "success" : errorMsg); }
public string UpdateConfig(IHttpContext context) { var errorMsg = ""; var json = ""; JsonProgramSettings settings; context.Response.StatusCode = 200; // get the response try { cumulus.LogMessage("Updating Program settings"); var data = new StreamReader(context.Request.InputStream).ReadToEnd(); // Start at char 5 to skip the "json:" prefix json = WebUtility.UrlDecode(data.Substring(5)); // de-serialize it to the settings structure settings = JsonSerializer.DeserializeFromString <JsonProgramSettings>(json); } catch (Exception ex) { var msg = "Error de-serializing Program Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Program Data: " + json); context.Response.StatusCode = 500; return(msg); } // process the settings try { cumulus.ProgramOptions.EnableAccessibility = settings.accessible; cumulus.ProgramOptions.StartupPingHost = settings.startup.startuphostping; cumulus.ProgramOptions.StartupPingEscapeTime = settings.startup.startuppingescape; cumulus.ProgramOptions.StartupDelaySecs = settings.startup.startupdelay; cumulus.ProgramOptions.StartupDelayMaxUptime = settings.startup.startupdelaymaxuptime; cumulus.ProgramOptions.DataStoppedExit = settings.shutdown.datastoppedexit; cumulus.ProgramOptions.DataStoppedMins = settings.shutdown.datastoppedmins; cumulus.ProgramOptions.DebugLogging = settings.logging.debuglogging; cumulus.ProgramOptions.DataLogging = settings.logging.datalogging; cumulus.SmtpOptions.Logging = settings.logging.emaillogging; cumulus.ErrorLogSpikeRemoval = settings.logging.spikelogging; cumulus.ProgramOptions.WarnMultiple = settings.options.stopsecondinstance; cumulus.ProgramOptions.ListWebTags = settings.options.listwebtags; cumulus.ProgramOptions.Culture.RemoveSpaceFromDateSeparator = settings.culture.removespacefromdateseparator; if (cumulus.ProgramOptions.Culture.RemoveSpaceFromDateSeparator && CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator.Contains(" ")) { // get the existing culture var newCulture = CultureInfo.CurrentCulture; // change the date separator newCulture.DateTimeFormat.DateSeparator = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator.Replace(" ", ""); // set current thread culture Thread.CurrentThread.CurrentCulture = newCulture; // set the default culture for other threads CultureInfo.DefaultThreadCurrentCulture = newCulture; } else { var newCulture = CultureInfo.GetCultureInfo(CultureInfo.CurrentCulture.Name); if (!cumulus.ProgramOptions.Culture.RemoveSpaceFromDateSeparator && newCulture.DateTimeFormat.DateSeparator.Contains(" ") && !CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator.Contains(" ")) { // set current thread culture Thread.CurrentThread.CurrentCulture = newCulture; // set the default culture for other threads CultureInfo.DefaultThreadCurrentCulture = newCulture; } } if (settings.logging.ftplogging != cumulus.FtpOptions.Logging) { cumulus.FtpOptions.Logging = settings.logging.ftplogging; cumulus.SetFtpLogging(cumulus.FtpOptions.Logging); } } catch (Exception ex) { var msg = "Error processing Program Options: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Save the settings cumulus.WriteIniFile(); return(context.Response.StatusCode == 200 ? "success" : errorMsg); }
public string UpdateAlarmSettings(IHttpContext context) { var json = ""; JsonAlarmSettings result; JsonAlarmSettingsData settings; try { var data = new StreamReader(context.Request.InputStream).ReadToEnd(); // Start at char 5 to skip the "json:" prefix json = WebUtility.UrlDecode(data); // de-serialize it to the settings structure //var settings = JsonConvert.DeserializeObject<JsonAlarmSettingsData>(json); //var settings = JsonSerializer.DeserializeFromString<JsonAlarmSettingsData>(json); result = json.FromJson <JsonAlarmSettings>(); settings = result.data; } catch (Exception ex) { var msg = "Error de-serializing Alarm Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Alarm Data: " + json); context.Response.StatusCode = 500; return(msg); } try { // process the settings cumulus.LogMessage("Updating Alarm settings"); var emailRequired = false; cumulus.LowTempAlarm.Enabled = settings.tempBelow.Enabled; cumulus.LowTempAlarm.Value = settings.tempBelow.Val; cumulus.LowTempAlarm.Sound = settings.tempBelow.SoundEnabled; cumulus.LowTempAlarm.SoundFile = settings.tempBelow.Sound; cumulus.LowTempAlarm.Notify = settings.tempBelow.Notify; cumulus.LowTempAlarm.Email = settings.tempBelow.Email; cumulus.LowTempAlarm.Latch = settings.tempBelow.Latches; cumulus.LowTempAlarm.LatchHours = settings.tempBelow.LatchHrs; emailRequired = cumulus.LowTempAlarm.Email && cumulus.LowTempAlarm.Enabled; cumulus.LowTempAlarm.Action = settings.tempBelow.Action; cumulus.LowTempAlarm.ActionParams = settings.tempBelow.ActionParams; cumulus.HighTempAlarm.Enabled = settings.tempAbove.Enabled; cumulus.HighTempAlarm.Value = settings.tempAbove.Val; cumulus.HighTempAlarm.Sound = settings.tempAbove.SoundEnabled; cumulus.HighTempAlarm.SoundFile = settings.tempAbove.Sound; cumulus.HighTempAlarm.Notify = settings.tempAbove.Notify; cumulus.HighTempAlarm.Email = settings.tempAbove.Email; cumulus.HighTempAlarm.Latch = settings.tempAbove.Latches; cumulus.HighTempAlarm.LatchHours = settings.tempAbove.LatchHrs; emailRequired = emailRequired || (cumulus.HighTempAlarm.Email && cumulus.HighTempAlarm.Enabled); cumulus.HighTempAlarm.Action = settings.tempAbove.Action; cumulus.HighTempAlarm.ActionParams = settings.tempAbove.ActionParams; cumulus.TempChangeAlarm.Enabled = settings.tempChange.Enabled; cumulus.TempChangeAlarm.Value = settings.tempChange.Val; cumulus.TempChangeAlarm.Sound = settings.tempChange.SoundEnabled; cumulus.TempChangeAlarm.SoundFile = settings.tempChange.Sound; cumulus.TempChangeAlarm.Notify = settings.tempChange.Notify; cumulus.TempChangeAlarm.Email = settings.tempChange.Email; cumulus.TempChangeAlarm.Latch = settings.tempChange.Latches; cumulus.TempChangeAlarm.LatchHours = settings.tempChange.LatchHrs; emailRequired = emailRequired || (cumulus.TempChangeAlarm.Email && cumulus.TempChangeAlarm.Enabled); cumulus.TempChangeAlarm.Action = settings.tempChange.Action; cumulus.TempChangeAlarm.ActionParams = settings.tempChange.ActionParams; cumulus.LowPressAlarm.Enabled = settings.pressBelow.Enabled; cumulus.LowPressAlarm.Value = settings.pressBelow.Val; cumulus.LowPressAlarm.Sound = settings.pressBelow.SoundEnabled; cumulus.LowPressAlarm.SoundFile = settings.pressBelow.Sound; cumulus.LowPressAlarm.Notify = settings.pressBelow.Notify; cumulus.LowPressAlarm.Email = settings.pressBelow.Email; cumulus.LowPressAlarm.Latch = settings.pressBelow.Latches; cumulus.LowPressAlarm.LatchHours = settings.pressBelow.LatchHrs; emailRequired = emailRequired || (cumulus.LowPressAlarm.Email && cumulus.LowPressAlarm.Enabled); cumulus.LowPressAlarm.Action = settings.pressBelow.Action; cumulus.LowPressAlarm.ActionParams = settings.pressBelow.ActionParams; cumulus.HighPressAlarm.Enabled = settings.pressAbove.Enabled; cumulus.HighPressAlarm.Value = settings.pressAbove.Val; cumulus.HighPressAlarm.Sound = settings.pressAbove.SoundEnabled; cumulus.HighPressAlarm.SoundFile = settings.pressAbove.Sound; cumulus.HighPressAlarm.Notify = settings.pressAbove.Notify; cumulus.HighPressAlarm.Email = settings.pressAbove.Email; cumulus.HighPressAlarm.Latch = settings.pressAbove.Latches; cumulus.HighPressAlarm.LatchHours = settings.pressAbove.LatchHrs; emailRequired = emailRequired || (cumulus.HighPressAlarm.Email && cumulus.HighPressAlarm.Enabled); cumulus.HighPressAlarm.Action = settings.pressAbove.Action; cumulus.HighPressAlarm.ActionParams = settings.pressAbove.ActionParams; cumulus.PressChangeAlarm.Enabled = settings.pressChange.Enabled; cumulus.PressChangeAlarm.Value = settings.pressChange.Val; cumulus.PressChangeAlarm.Sound = settings.pressChange.SoundEnabled; cumulus.PressChangeAlarm.SoundFile = settings.pressChange.Sound; cumulus.PressChangeAlarm.Notify = settings.pressChange.Notify; cumulus.PressChangeAlarm.Email = settings.pressChange.Email; cumulus.PressChangeAlarm.Latch = settings.pressChange.Latches; cumulus.PressChangeAlarm.LatchHours = settings.pressChange.LatchHrs; emailRequired = emailRequired || (cumulus.PressChangeAlarm.Email && cumulus.PressChangeAlarm.Enabled); cumulus.PressChangeAlarm.Action = settings.pressChange.Action; cumulus.PressChangeAlarm.ActionParams = settings.pressChange.ActionParams; cumulus.HighRainTodayAlarm.Enabled = settings.rainAbove.Enabled; cumulus.HighRainTodayAlarm.Value = settings.rainAbove.Val; cumulus.HighRainTodayAlarm.Sound = settings.rainAbove.SoundEnabled; cumulus.HighRainTodayAlarm.SoundFile = settings.rainAbove.Sound; cumulus.HighRainTodayAlarm.Notify = settings.rainAbove.Notify; cumulus.HighRainTodayAlarm.Email = settings.rainAbove.Email; cumulus.HighRainTodayAlarm.Latch = settings.rainAbove.Latches; cumulus.HighRainTodayAlarm.LatchHours = settings.rainAbove.LatchHrs; emailRequired = emailRequired || (cumulus.HighRainTodayAlarm.Email && cumulus.HighRainTodayAlarm.Enabled); cumulus.HighRainTodayAlarm.Action = settings.rainAbove.Action; cumulus.HighRainTodayAlarm.ActionParams = settings.rainAbove.ActionParams; cumulus.HighRainRateAlarm.Enabled = settings.rainRateAbove.Enabled; cumulus.HighRainRateAlarm.Value = settings.rainRateAbove.Val; cumulus.HighRainRateAlarm.Sound = settings.rainRateAbove.SoundEnabled; cumulus.HighRainRateAlarm.SoundFile = settings.rainRateAbove.Sound; cumulus.HighRainRateAlarm.Notify = settings.rainRateAbove.Notify; cumulus.HighRainRateAlarm.Email = settings.rainRateAbove.Email; cumulus.HighRainRateAlarm.Latch = settings.rainRateAbove.Latches; cumulus.HighRainRateAlarm.LatchHours = settings.rainRateAbove.LatchHrs; emailRequired = emailRequired || (cumulus.HighRainRateAlarm.Email && cumulus.HighRainRateAlarm.Enabled); cumulus.HighRainRateAlarm.Action = settings.rainRateAbove.Action; cumulus.HighRainRateAlarm.ActionParams = settings.rainRateAbove.ActionParams; cumulus.IsRainingAlarm.Enabled = settings.isRaining.Enabled; cumulus.IsRainingAlarm.Sound = settings.isRaining.SoundEnabled; cumulus.IsRainingAlarm.SoundFile = settings.isRaining.Sound; cumulus.IsRainingAlarm.Notify = settings.isRaining.Notify; cumulus.IsRainingAlarm.Email = settings.isRaining.Email; cumulus.IsRainingAlarm.Latch = settings.isRaining.Latches; cumulus.IsRainingAlarm.LatchHours = settings.isRaining.LatchHrs; emailRequired = emailRequired || (cumulus.IsRainingAlarm.Email && cumulus.IsRainingAlarm.Enabled); cumulus.IsRainingAlarm.Action = settings.isRaining.Action; cumulus.IsRainingAlarm.ActionParams = settings.isRaining.ActionParams; cumulus.HighGustAlarm.Enabled = settings.gustAbove.Enabled; cumulus.HighGustAlarm.Value = settings.gustAbove.Val; cumulus.HighGustAlarm.Sound = settings.gustAbove.SoundEnabled; cumulus.HighGustAlarm.SoundFile = settings.gustAbove.Sound; cumulus.HighGustAlarm.Notify = settings.gustAbove.Notify; cumulus.HighGustAlarm.Email = settings.gustAbove.Email; cumulus.HighGustAlarm.Latch = settings.gustAbove.Latches; cumulus.HighGustAlarm.LatchHours = settings.gustAbove.LatchHrs; emailRequired = emailRequired || (cumulus.HighGustAlarm.Email && cumulus.HighGustAlarm.Enabled); cumulus.HighGustAlarm.Action = settings.gustAbove.Action; cumulus.HighGustAlarm.ActionParams = settings.gustAbove.ActionParams; cumulus.HighWindAlarm.Enabled = settings.windAbove.Enabled; cumulus.HighWindAlarm.Value = settings.windAbove.Val; cumulus.HighWindAlarm.Sound = settings.windAbove.SoundEnabled; cumulus.HighWindAlarm.SoundFile = settings.windAbove.Sound; cumulus.HighWindAlarm.Notify = settings.windAbove.Notify; cumulus.HighWindAlarm.Email = settings.windAbove.Email; cumulus.HighWindAlarm.Latch = settings.windAbove.Latches; cumulus.HighWindAlarm.LatchHours = settings.windAbove.LatchHrs; emailRequired = emailRequired || (cumulus.HighWindAlarm.Email && cumulus.HighWindAlarm.Enabled); cumulus.HighWindAlarm.Action = settings.windAbove.Action; cumulus.HighWindAlarm.ActionParams = settings.windAbove.ActionParams; cumulus.SensorAlarm.Enabled = settings.contactLost.Enabled; cumulus.SensorAlarm.Sound = settings.contactLost.SoundEnabled; cumulus.SensorAlarm.SoundFile = settings.contactLost.Sound; cumulus.SensorAlarm.Notify = settings.contactLost.Notify; cumulus.SensorAlarm.Email = settings.contactLost.Email; cumulus.SensorAlarm.Latch = settings.contactLost.Latches; cumulus.SensorAlarm.LatchHours = settings.contactLost.LatchHrs; cumulus.SensorAlarm.TriggerThreshold = settings.contactLost.Threshold; emailRequired = emailRequired || (cumulus.SensorAlarm.Email && cumulus.SensorAlarm.Enabled); cumulus.SensorAlarm.Action = settings.contactLost.Action; cumulus.SensorAlarm.ActionParams = settings.contactLost.ActionParams; cumulus.DataStoppedAlarm.Enabled = settings.dataStopped.Enabled; cumulus.DataStoppedAlarm.Sound = settings.dataStopped.SoundEnabled; cumulus.DataStoppedAlarm.SoundFile = settings.dataStopped.Sound; cumulus.DataStoppedAlarm.Notify = settings.dataStopped.Notify; cumulus.DataStoppedAlarm.Email = settings.dataStopped.Email; cumulus.DataStoppedAlarm.Latch = settings.dataStopped.Latches; cumulus.DataStoppedAlarm.LatchHours = settings.dataStopped.LatchHrs; cumulus.DataStoppedAlarm.TriggerThreshold = settings.dataStopped.Threshold; emailRequired = emailRequired || (cumulus.DataStoppedAlarm.Email && cumulus.DataStoppedAlarm.Enabled); cumulus.DataStoppedAlarm.Action = settings.dataStopped.Action; cumulus.DataStoppedAlarm.ActionParams = settings.dataStopped.ActionParams; cumulus.BatteryLowAlarm.Enabled = settings.batteryLow.Enabled; cumulus.BatteryLowAlarm.Sound = settings.batteryLow.SoundEnabled; cumulus.BatteryLowAlarm.SoundFile = settings.batteryLow.Sound; cumulus.BatteryLowAlarm.Notify = settings.batteryLow.Notify; cumulus.BatteryLowAlarm.Email = settings.batteryLow.Email; cumulus.BatteryLowAlarm.Latch = settings.batteryLow.Latches; cumulus.BatteryLowAlarm.LatchHours = settings.batteryLow.LatchHrs; cumulus.BatteryLowAlarm.TriggerThreshold = settings.batteryLow.Threshold; emailRequired = emailRequired || (cumulus.BatteryLowAlarm.Email && cumulus.BatteryLowAlarm.Enabled); cumulus.BatteryLowAlarm.Action = settings.batteryLow.Action; cumulus.BatteryLowAlarm.ActionParams = settings.batteryLow.ActionParams; cumulus.SpikeAlarm.Enabled = settings.spike.Enabled; cumulus.SpikeAlarm.Sound = settings.spike.SoundEnabled; cumulus.SpikeAlarm.SoundFile = settings.spike.Sound; cumulus.SpikeAlarm.Notify = settings.spike.Notify; cumulus.SpikeAlarm.Email = settings.spike.Email; cumulus.SpikeAlarm.Latch = settings.spike.Latches; cumulus.SpikeAlarm.LatchHours = settings.spike.LatchHrs; cumulus.SpikeAlarm.TriggerThreshold = settings.spike.Threshold; emailRequired = emailRequired || (cumulus.SpikeAlarm.Email && cumulus.SpikeAlarm.Enabled); cumulus.SpikeAlarm.Action = settings.spike.Action; cumulus.SpikeAlarm.ActionParams = settings.spike.ActionParams; cumulus.UpgradeAlarm.Enabled = settings.upgrade.Enabled; cumulus.UpgradeAlarm.Sound = settings.upgrade.SoundEnabled; cumulus.UpgradeAlarm.SoundFile = settings.upgrade.Sound; cumulus.UpgradeAlarm.Notify = settings.upgrade.Notify; cumulus.UpgradeAlarm.Email = settings.upgrade.Email; cumulus.UpgradeAlarm.Latch = settings.upgrade.Latches; cumulus.UpgradeAlarm.LatchHours = settings.upgrade.LatchHrs; emailRequired = emailRequired || (cumulus.UpgradeAlarm.Email && cumulus.UpgradeAlarm.Enabled); cumulus.UpgradeAlarm.Action = settings.upgrade.Action; cumulus.UpgradeAlarm.ActionParams = settings.upgrade.ActionParams; cumulus.HttpUploadAlarm.Enabled = settings.httpUpload.Enabled; cumulus.HttpUploadAlarm.Sound = settings.httpUpload.SoundEnabled; cumulus.HttpUploadAlarm.SoundFile = settings.httpUpload.Sound; cumulus.HttpUploadAlarm.Notify = settings.httpUpload.Notify; cumulus.HttpUploadAlarm.Email = settings.httpUpload.Email; cumulus.HttpUploadAlarm.Latch = settings.httpUpload.Latches; cumulus.HttpUploadAlarm.LatchHours = settings.httpUpload.LatchHrs; cumulus.HttpUploadAlarm.TriggerThreshold = settings.httpUpload.Threshold; emailRequired = emailRequired || (cumulus.HttpUploadAlarm.Email && cumulus.HttpUploadAlarm.Enabled); cumulus.HttpUploadAlarm.Action = settings.httpUpload.Action; cumulus.HttpUploadAlarm.ActionParams = settings.httpUpload.ActionParams; cumulus.MySqlUploadAlarm.Enabled = settings.mySqlUpload.Enabled; cumulus.MySqlUploadAlarm.Sound = settings.mySqlUpload.SoundEnabled; cumulus.MySqlUploadAlarm.SoundFile = settings.mySqlUpload.Sound; cumulus.MySqlUploadAlarm.Notify = settings.mySqlUpload.Notify; cumulus.MySqlUploadAlarm.Email = settings.mySqlUpload.Email; cumulus.MySqlUploadAlarm.Latch = settings.mySqlUpload.Latches; cumulus.MySqlUploadAlarm.LatchHours = settings.mySqlUpload.LatchHrs; cumulus.MySqlUploadAlarm.TriggerThreshold = settings.mySqlUpload.Threshold; emailRequired = emailRequired || (cumulus.MySqlUploadAlarm.Email && cumulus.MySqlUploadAlarm.Enabled); cumulus.MySqlUploadAlarm.Action = settings.mySqlUpload.Action; cumulus.MySqlUploadAlarm.ActionParams = settings.mySqlUpload.ActionParams; // validate the from email if (emailRequired && !EmailSender.CheckEmailAddress(result.email.fromEmail.Trim())) { var msg = "ERROR: Alarm email option enabled and an invalid Alarm from email address entered"; cumulus.LogMessage(msg); context.Response.StatusCode = 500; return(msg); } else { cumulus.AlarmFromEmail = result.email.fromEmail.Trim(); } // validate the destination email(s) var emails = result.email.destEmail.Trim().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i < emails.Length; i++) { emails[i] = emails[i].Trim(); if (!EmailSender.CheckEmailAddress(emails[i])) { var msg = "ERROR: Invalid Alarm destination email address entered"; cumulus.LogMessage(msg); context.Response.StatusCode = 500; return(msg); } } cumulus.AlarmDestEmail = emails; cumulus.AlarmEmailHtml = result.email.useHtml; // Save the settings cumulus.WriteIniFile(); context.Response.StatusCode = 200; } catch (Exception ex) { cumulus.LogMessage("Error processing Alarm settings: " + ex.Message); cumulus.LogDebugMessage("Alarm Data: " + json); context.Response.StatusCode = 500; return(ex.Message); } return("success"); }
public string UpdateConfig(IHttpContext context) { var errorMsg = ""; var json = ""; JsonInternetSettingsData settings; context.Response.StatusCode = 200; try { var data = new StreamReader(context.Request.InputStream).ReadToEnd(); // Start at char 5 to skip the "json:" prefix json = WebUtility.UrlDecode(data.Substring(5)); // de-serialize it to the settings structure settings = json.FromJson <JsonInternetSettingsData>(); } catch (Exception ex) { var msg = "Error de-serializing Internet Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Internet Data: " + json); context.Response.StatusCode = 500; return(msg); } // process the settings try { cumulus.LogMessage("Updating internet settings"); // website settings try { cumulus.FtpOptions.Enabled = settings.website.enabled; if (cumulus.FtpOptions.Enabled) { cumulus.FtpOptions.Directory = settings.website.directory ?? string.Empty; cumulus.FtpOptions.Port = settings.website.ftpport; cumulus.FtpOptions.Hostname = settings.website.hostname ?? string.Empty; cumulus.FtpOptions.FtpMode = (Cumulus.FtpProtocols)settings.website.sslftp; cumulus.FtpOptions.Password = settings.website.password ?? string.Empty; cumulus.FtpOptions.Username = settings.website.username ?? string.Empty; cumulus.FtpOptions.SshAuthen = settings.website.sshAuth ?? string.Empty; cumulus.FtpOptions.SshPskFile = settings.website.pskFile ?? string.Empty; cumulus.DeleteBeforeUpload = settings.website.general.ftpdelete; cumulus.FTPRename = settings.website.general.ftprename; cumulus.UTF8encode = settings.website.general.utf8encode; if (cumulus.FtpOptions.FtpMode == Cumulus.FtpProtocols.FTP || cumulus.FtpOptions.FtpMode == Cumulus.FtpProtocols.FTPS) { cumulus.FtpOptions.AutoDetect = settings.website.advanced.autodetect; cumulus.FtpOptions.ActiveMode = settings.website.advanced.activeftp; cumulus.FtpOptions.DisableEPSV = settings.website.advanced.disableftpsepsv; } if (cumulus.FtpOptions.FtpMode == Cumulus.FtpProtocols.FTPS) { cumulus.FtpOptions.DisableExplicit = settings.website.advanced.disableftpsexplicit; cumulus.FtpOptions.IgnoreCertErrors = settings.website.advanced.ignorecerts; } } cumulus.FtpOptions.LocalCopyEnabled = settings.website.localcopy; if (cumulus.FtpOptions.LocalCopyEnabled) { cumulus.FtpOptions.LocalCopyFolder = settings.website.localcopyfolder; } } catch (Exception ex) { var msg = "Error processing website settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // web settings try { cumulus.RealtimeIntervalEnabled = settings.websettings.realtime.enabled; if (cumulus.RealtimeIntervalEnabled) { cumulus.FtpOptions.RealtimeEnabled = settings.websettings.realtime.enablerealtimeftp; cumulus.RealtimeInterval = settings.websettings.realtime.realtimeinterval * 1000; if (cumulus.RealtimeTimer.Interval != cumulus.RealtimeInterval) { cumulus.RealtimeTimer.Interval = cumulus.RealtimeInterval; } for (var i = 0; i < cumulus.RealtimeFiles.Length; i++) { cumulus.RealtimeFiles[i].Create = settings.websettings.realtime.files[i].create; cumulus.RealtimeFiles[i].FTP = cumulus.RealtimeFiles[i].Create && settings.websettings.realtime.files[i].ftp; cumulus.RealtimeFiles[i].Copy = cumulus.RealtimeFiles[i].Create && settings.websettings.realtime.files[i].copy; } } cumulus.RealtimeTimer.Enabled = cumulus.RealtimeIntervalEnabled; if (!cumulus.RealtimeTimer.Enabled || !cumulus.FtpOptions.RealtimeEnabled) { cumulus.RealtimeFTPDisconnect(); } cumulus.WebIntervalEnabled = settings.websettings.interval.enabled; if (cumulus.WebIntervalEnabled) { cumulus.FtpOptions.IntervalEnabled = settings.websettings.interval.enableintervalftp; cumulus.UpdateInterval = settings.websettings.interval.ftpinterval; if (cumulus.WebTimer.Interval != cumulus.UpdateInterval * 60 * 1000) { cumulus.WebTimer.Interval = cumulus.UpdateInterval * 60 * 1000; } for (var i = 0; i < cumulus.StdWebFiles.Length; i++) { cumulus.StdWebFiles[i].Create = settings.websettings.interval.stdfiles.files[i].create; cumulus.StdWebFiles[i].FTP = cumulus.StdWebFiles[i].Create && settings.websettings.interval.stdfiles.files[i].ftp; cumulus.StdWebFiles[i].Copy = cumulus.StdWebFiles[i].Create && settings.websettings.interval.stdfiles.files[i].copy; } for (var i = 0; i < cumulus.GraphDataFiles.Length; i++) { cumulus.GraphDataFiles[i].Create = settings.websettings.interval.graphfiles.files[i].create; cumulus.GraphDataFiles[i].FTP = cumulus.GraphDataFiles[i].Create && settings.websettings.interval.graphfiles.files[i].ftp; cumulus.GraphDataFiles[i].Copy = cumulus.GraphDataFiles[i].Create && settings.websettings.interval.graphfiles.files[i].copy; } for (var i = 0; i < cumulus.GraphDataEodFiles.Length; i++) { cumulus.GraphDataEodFiles[i].Create = settings.websettings.interval.graphfileseod.files[i].create; cumulus.GraphDataEodFiles[i].FTP = cumulus.GraphDataEodFiles[i].Create && settings.websettings.interval.graphfileseod.files[i].ftp; cumulus.GraphDataEodFiles[i].Copy = cumulus.GraphDataEodFiles[i].Create && settings.websettings.interval.graphfileseod.files[i].copy; } } } catch (Exception ex) { var msg = "Error processing web settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // external programs try { if (settings.externalprograms != null) { cumulus.DailyProgram = settings.externalprograms.dailyprogram ?? string.Empty; cumulus.DailyParams = settings.externalprograms.dailyprogramparams ?? string.Empty; cumulus.ExternalProgram = settings.externalprograms.program ?? string.Empty; cumulus.ExternalParams = settings.externalprograms.programparams ?? string.Empty; cumulus.RealtimeProgram = settings.externalprograms.realtimeprogram ?? string.Empty; cumulus.RealtimeParams = settings.externalprograms.realtimeprogramparams ?? string.Empty; } } catch (Exception ex) { var msg = "Error processing external programs: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // MQTT try { cumulus.MQTT.Server = settings.mqtt.server ?? string.Empty; cumulus.MQTT.Port = settings.mqtt.port; cumulus.MQTT.UseTLS = settings.mqtt.useTls; cumulus.MQTT.Username = settings.mqtt.username ?? string.Empty; cumulus.MQTT.Password = settings.mqtt.password ?? string.Empty; cumulus.MQTT.EnableDataUpdate = settings.mqtt.dataUpdate.enabled; if (cumulus.MQTT.EnableDataUpdate) { cumulus.MQTT.UpdateTemplate = settings.mqtt.dataUpdate.template ?? string.Empty; } cumulus.MQTT.EnableInterval = settings.mqtt.interval.enabled; if (cumulus.MQTT.EnableInterval) { cumulus.MQTT.IntervalTime = settings.mqtt.interval.time; cumulus.MQTT.IntervalTemplate = settings.mqtt.interval.template ?? string.Empty; cumulus.MQTTTimer.Interval = cumulus.MQTT.IntervalTime * 1000; cumulus.MQTTTimer.Enabled = cumulus.MQTT.EnableInterval && !string.IsNullOrWhiteSpace(cumulus.MQTT.IntervalTemplate); } } catch (Exception ex) { var msg = "Error processing MQTT settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Moon Image try { cumulus.MoonImage.Enabled = settings.moonimage.enabled; if (cumulus.MoonImage.Enabled) { cumulus.MoonImage.Size = settings.moonimage.size; if (cumulus.MoonImage.Size < 10) { cumulus.MoonImage.Size = 10; } cumulus.MoonImage.Ftp = settings.moonimage.includemoonimage; if (cumulus.MoonImage.Ftp) { cumulus.MoonImage.FtpDest = settings.moonimage.ftpdest; } cumulus.MoonImage.Copy = settings.moonimage.copyimage; if (cumulus.MoonImage.Copy) { cumulus.MoonImage.CopyDest = settings.moonimage.copydest; } } } catch (Exception ex) { var msg = "Error processing Moon image settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // HTTP proxy try { cumulus.HTTPProxyPassword = settings.proxies.httpproxy.password ?? string.Empty; cumulus.HTTPProxyPort = settings.proxies.httpproxy.port; cumulus.HTTPProxyName = settings.proxies.httpproxy.proxy ?? string.Empty; cumulus.HTTPProxyUser = settings.proxies.httpproxy.user ?? string.Empty; } catch (Exception ex) { var msg = "Error processing HTTP proxy settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // email settings try { cumulus.SmtpOptions.Enabled = settings.emailsettings.enabled; if (cumulus.SmtpOptions.Enabled) { cumulus.SmtpOptions.Server = settings.emailsettings.server; cumulus.SmtpOptions.Port = settings.emailsettings.port; cumulus.SmtpOptions.SslOption = settings.emailsettings.ssloption; cumulus.SmtpOptions.RequiresAuthentication = settings.emailsettings.authenticate; cumulus.SmtpOptions.User = settings.emailsettings.user; cumulus.SmtpOptions.Password = settings.emailsettings.password; cumulus.SmtpOptions.IgnoreCertErrors = settings.emailsettings.ignorecerterrors; if (cumulus.emailer == null) { cumulus.emailer = new EmailSender(cumulus); } } } catch (Exception ex) { var msg = "Error processing Email settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // misc settings try { cumulus.WebcamURL = settings.misc.webcamurl ?? string.Empty; cumulus.ForumURL = settings.misc.forumurl ?? string.Empty; } catch (Exception ex) { var msg = "Error processing Misc settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Save the settings cumulus.WriteIniFile(); cumulus.SetUpHttpProxy(); //cumulus.SetFtpLogging(cumulus.FTPlogging); // Setup MQTT if (cumulus.MQTT.EnableDataUpdate || cumulus.MQTT.EnableInterval) { if (!MqttPublisher.configured) { MqttPublisher.Setup(cumulus); } if (cumulus.MQTT.EnableInterval) { cumulus.MQTTTimer.Elapsed -= cumulus.MQTTTimerTick; cumulus.MQTTTimer.Elapsed += cumulus.MQTTTimerTick; cumulus.MQTTTimer.Start(); } else { cumulus.MQTTTimer.Stop(); } } else { cumulus.MQTTTimer.Stop(); } } catch (Exception ex) { var msg = "Error processing Internet settings: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Internet data: " + json); errorMsg += msg; context.Response.StatusCode = 500; } return(context.Response.StatusCode == 200 ? "success" : errorMsg); }
//public string UpdateNoaaConfig(HttpListenerContext context) public string UpdateConfig(IHttpContext context) { var json = ""; JsonNOAASettingsData settings; try { var data = new StreamReader(context.Request.InputStream).ReadToEnd(); // Start at char 5 to skip the "json:" prefix json = WebUtility.UrlDecode(data.Substring(5)); // de-serialize it to the settings structure settings = json.FromJson <JsonNOAASettingsData>(); } catch (Exception ex) { var msg = "Error de-serializing NOAA Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("NOAA Data: " + json); context.Response.StatusCode = 500; return(msg); } // process the settings try { cumulus.LogMessage("Updating NOAA settings"); cumulus.NOAAconf.Create = settings.autosave; if (cumulus.NOAAconf.Create) { cumulus.NOAAconf.Name = settings.sitedetails.sitename; cumulus.NOAAconf.City = settings.sitedetails.city; cumulus.NOAAconf.State = settings.sitedetails.state; cumulus.NOAAconf.MonthFile = settings.outputfiles.monthfileformat; cumulus.NOAAconf.YearFile = settings.outputfiles.yearfileformat; cumulus.NOAAconf.Use12hour = settings.options.timeformat == 1; cumulus.NOAAconf.UseUtf8 = settings.options.utf8; cumulus.NOAAconf.UseDotDecimal = settings.options.dotdecimal; cumulus.NOAAconf.UseMinMaxAvg = settings.options.minmaxavg; cumulus.NOAAconf.AutoFtp = settings.ftp.autotransfer; cumulus.NOAAconf.FtpFolder = settings.ftp.dstfolder; cumulus.NOAAconf.AutoCopy = settings.copy.autotransfer; cumulus.NOAAconf.CopyFolder = settings.copy.dstfolder; cumulus.NOAAconf.HeatThreshold = settings.thresholds.heatingthreshold; cumulus.NOAAconf.CoolThreshold = settings.thresholds.coolingthreshold; cumulus.NOAAconf.MaxTempComp1 = settings.thresholds.maxtempcomp1; cumulus.NOAAconf.MaxTempComp2 = settings.thresholds.maxtempcomp2; cumulus.NOAAconf.MinTempComp1 = settings.thresholds.mintempcomp1; cumulus.NOAAconf.MinTempComp2 = settings.thresholds.mintempcomp2; cumulus.NOAAconf.RainComp1 = settings.thresholds.raincomp1; cumulus.NOAAconf.RainComp2 = settings.thresholds.raincomp2; cumulus.NOAAconf.RainComp3 = settings.thresholds.raincomp3; // normal mean temps cumulus.NOAAconf.TempNorms[1] = settings.normalmeantemps.jan; cumulus.NOAAconf.TempNorms[2] = settings.normalmeantemps.feb; cumulus.NOAAconf.TempNorms[3] = settings.normalmeantemps.mar; cumulus.NOAAconf.TempNorms[4] = settings.normalmeantemps.apr; cumulus.NOAAconf.TempNorms[5] = settings.normalmeantemps.may; cumulus.NOAAconf.TempNorms[6] = settings.normalmeantemps.jun; cumulus.NOAAconf.TempNorms[7] = settings.normalmeantemps.jul; cumulus.NOAAconf.TempNorms[8] = settings.normalmeantemps.aug; cumulus.NOAAconf.TempNorms[9] = settings.normalmeantemps.sep; cumulus.NOAAconf.TempNorms[10] = settings.normalmeantemps.oct; cumulus.NOAAconf.TempNorms[11] = settings.normalmeantemps.nov; cumulus.NOAAconf.TempNorms[12] = settings.normalmeantemps.dec; // normal rain cumulus.NOAAconf.RainNorms[1] = settings.normalrain.jan; cumulus.NOAAconf.RainNorms[2] = settings.normalrain.feb; cumulus.NOAAconf.RainNorms[3] = settings.normalrain.mar; cumulus.NOAAconf.RainNorms[4] = settings.normalrain.apr; cumulus.NOAAconf.RainNorms[5] = settings.normalrain.may; cumulus.NOAAconf.RainNorms[6] = settings.normalrain.jun; cumulus.NOAAconf.RainNorms[6] = settings.normalrain.jul; cumulus.NOAAconf.RainNorms[8] = settings.normalrain.aug; cumulus.NOAAconf.RainNorms[9] = settings.normalrain.sep; cumulus.NOAAconf.RainNorms[10] = settings.normalrain.oct; cumulus.NOAAconf.RainNorms[11] = settings.normalrain.nov; cumulus.NOAAconf.RainNorms[12] = settings.normalrain.dec; } // Save the settings cumulus.WriteIniFile(); context.Response.StatusCode = 200; } catch (Exception ex) { var msg = "Error processing NOAA settings: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("NOAA data: " + json); context.Response.StatusCode = 500; return(msg); } return("success"); }
public static void Setup(Cumulus cumulus) { MqttPublisher.cumulus = cumulus; var mqttFactory = new MqttFactory(); mqttClient = (MqttClient)mqttFactory.CreateMqttClient(); var clientId = Guid.NewGuid().ToString(); var mqttTcpOptions = new MQTTnet.Client.MqttClientTcpOptions { Server = cumulus.MQTT.Server, Port = cumulus.MQTT.Port, TlsOptions = new MQTTnet.Client.MqttClientTlsOptions { UseTls = cumulus.MQTT.UseTLS } }; switch (cumulus.MQTT.IpVersion) { case 4: mqttTcpOptions.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork; break; case 6: mqttTcpOptions.AddressFamily = System.Net.Sockets.AddressFamily.InterNetworkV6; break; default: mqttTcpOptions.AddressFamily = System.Net.Sockets.AddressFamily.Unspecified; break; } var mqttOptions = new MQTTnet.Client.MqttClientOptions { ChannelOptions = mqttTcpOptions, ClientId = clientId, Credentials = string.IsNullOrEmpty(cumulus.MQTT.Password) ? null : new MQTTnet.Client.MqttClientCredentials(cumulus.MQTT.Username, System.Text.Encoding.UTF8.GetBytes(cumulus.MQTT.Password)), CleanSession = true }; Connect(mqttOptions); mqttClient.DisconnectedAsync += (async e => { cumulus.LogMessage("Error: MQTT disconnected from the server"); await Task.Delay(TimeSpan.FromSeconds(5)); cumulus.LogDebugMessage("MQTT attempting to reconnect with server"); try { Connect(mqttOptions); cumulus.LogDebugMessage("MQTT reconnected OK"); } catch { cumulus.LogMessage("Error: MQTT reconnection to server failed"); } }); configured = true; }
public static void UpdateMQTTfeed(string feedType) { string topic; var template = "mqtt/"; if (feedType == "Interval") { template += cumulus.MQTT.IntervalTemplate; topic = cumulus.MQTT.IntervalTopic; } else { template += cumulus.MQTT.UpdateTemplate; topic = cumulus.MQTT.UpdateTopic; // Refresh our copy of the template contents if the filename has changed // We want to avoid reading the template file every few seconds if possible. if (cumulus.MQTT.UpdateTemplate != dataupdateTemplateFile) { if (File.Exists(template)) { try { using (TextReader reader = new StreamReader(template, new System.Text.UTF8Encoding(false))) { dataupdateTemplateContent = reader.ReadToEnd(); } } catch (Exception e) { cumulus.LogMessage($"MQTT: Error reading template file {template} - {e.Message}"); return; } dataupdateTemplateFile = cumulus.MQTT.UpdateTemplate; } else { cumulus.LogMessage($"MQTT: Error, unable to find template file - {template}"); return; } } } if (!File.Exists(template)) { return; } // use template file cumulus.LogDebugMessage($"MQTT: Using template - {template}"); bool retain; var mqttTokenParser = new TokenParser { Encoding = new System.Text.UTF8Encoding(false) }; mqttTokenParser.OnToken += cumulus.TokenParserOnToken; string message; if (feedType == "Interval") { mqttTokenParser.SourceFile = template; message = mqttTokenParser.ToString(); retain = cumulus.MQTT.IntervalRetained; } else { mqttTokenParser.InputText = dataupdateTemplateContent; message = mqttTokenParser.ToStringFromString(); retain = cumulus.MQTT.UpdateRetained; } // send the message _ = SendMessageAsync(topic, message, retain); }
public string UpdateConfig(IHttpContext context) { var errorMsg = ""; var json = ""; JsonProgramSettings settings; context.Response.StatusCode = 200; // get the response try { cumulus.LogMessage("Updating Program settings"); var data = new StreamReader(context.Request.InputStream).ReadToEnd(); // Start at char 5 to skip the "json:" prefix json = WebUtility.UrlDecode(data.Substring(5)); // de-serialize it to the settings structure settings = JsonSerializer.DeserializeFromString <JsonProgramSettings>(json); } catch (Exception ex) { var msg = "Error de-serializing Program Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Program Data: " + json); context.Response.StatusCode = 500; return(msg); } // process the settings try { cumulus.ProgramOptions.EnableAccessibility = settings.accessible; cumulus.ProgramOptions.StartupPingHost = settings.startup.startuphostping; cumulus.ProgramOptions.StartupPingEscapeTime = settings.startup.startuppingescape; cumulus.ProgramOptions.StartupDelaySecs = settings.startup.startupdelay; cumulus.ProgramOptions.StartupDelayMaxUptime = settings.startup.startupdelaymaxuptime; cumulus.ProgramOptions.DebugLogging = settings.logging.debuglogging; cumulus.ProgramOptions.DataLogging = settings.logging.datalogging; cumulus.SmtpOptions.Logging = settings.logging.emaillogging; cumulus.ErrorLogSpikeRemoval = settings.logging.spikelogging; cumulus.ProgramOptions.WarnMultiple = settings.options.stopsecondinstance; cumulus.ProgramOptions.ListWebTags = settings.options.listwebtags; if (settings.logging.ftplogging != cumulus.FtpOptions.Logging) { cumulus.FtpOptions.Logging = settings.logging.ftplogging; cumulus.SetFtpLogging(cumulus.FtpOptions.Logging); } } catch (Exception ex) { var msg = "Error processing Program Options: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Save the settings cumulus.WriteIniFile(); return(context.Response.StatusCode == 200 ? "success" : errorMsg); }
//public object UpdateMysqlConfig(HttpListenerContext context) public object UpdateConfig(IHttpContext context) { string json = ""; JsonMysqlSettings settings; try { var data = new StreamReader(context.Request.InputStream).ReadToEnd(); // Start at char 5 to skip the "json:" prefix json = WebUtility.UrlDecode(data.Substring(5)); // de-serialize it to the settings structure settings = json.FromJson <JsonMysqlSettings>(); } catch (Exception ex) { var msg = "Error de-serializing MySQL Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("MySQL Data: " + json); context.Response.StatusCode = 500; return(msg); } // process the settings try { cumulus.LogMessage("Updating MySQL settings"); // server cumulus.MySqlConnSettings.Server = settings.server.host; if (settings.server.port > 0 && settings.server.port < 65536) { cumulus.MySqlConnSettings.Port = settings.server.port; } else { cumulus.MySqlConnSettings.Port = 3306; } cumulus.MySqlConnSettings.Database = settings.server.database; cumulus.MySqlConnSettings.UserID = settings.server.user; cumulus.MySqlConnSettings.Password = settings.server.pass; // options cumulus.MySqlSettings.UpdateOnEdit = settings.options.updateonedit; cumulus.MySqlSettings.BufferOnfailure = settings.options.bufferonerror; //monthly cumulus.MySqlSettings.Monthly.Enabled = settings.monthly.enabled; if (cumulus.MySqlSettings.Monthly.Enabled) { cumulus.MySqlSettings.Monthly.TableName = String.IsNullOrWhiteSpace(settings.monthly.table) ? "Monthly" : settings.monthly.table; } //realtime cumulus.MySqlSettings.Realtime.Enabled = settings.realtime.enabled; if (cumulus.MySqlSettings.Realtime.Enabled) { cumulus.MySqlSettings.RealtimeRetention = settings.realtime.retentionVal + " " + settings.realtime.retentionUnit; cumulus.MySqlSettings.Realtime.TableName = String.IsNullOrWhiteSpace(settings.realtime.table) ? "Realtime" : settings.realtime.table; cumulus.MySqlSettings.RealtimeLimit1Minute = settings.realtime.limit1min; } //dayfile cumulus.MySqlSettings.Dayfile.Enabled = settings.dayfile.enabled; if (cumulus.MySqlSettings.Dayfile.Enabled) { cumulus.MySqlSettings.Dayfile.TableName = String.IsNullOrWhiteSpace(settings.dayfile.table) ? "Dayfile" : settings.dayfile.table; } // custom seconds cumulus.MySqlSettings.CustomSecs.Enabled = settings.customseconds.enabled; if (cumulus.MySqlSettings.CustomSecs.Enabled) { cumulus.MySqlSettings.CustomSecs.Command = settings.customseconds.command; cumulus.MySqlSettings.CustomSecs.Interval = settings.customseconds.interval; } // custom minutes cumulus.MySqlSettings.CustomMins.Enabled = settings.customminutes.enabled; if (cumulus.MySqlSettings.CustomMins.Enabled) { cumulus.MySqlSettings.CustomMins.Command = settings.customminutes.command; cumulus.CustomMySqlMinutesIntervalIndex = settings.customminutes.intervalindex; if (cumulus.CustomMySqlMinutesIntervalIndex >= 0 && cumulus.CustomMySqlMinutesIntervalIndex < cumulus.FactorsOf60.Length) { cumulus.MySqlSettings.CustomMins.Interval = cumulus.FactorsOf60[cumulus.CustomMySqlMinutesIntervalIndex]; } else { cumulus.MySqlSettings.CustomMins.Interval = 10; } } // custom roll-over cumulus.MySqlSettings.CustomRollover.Enabled = settings.customrollover.enabled; if (cumulus.MySqlSettings.CustomRollover.Enabled) { cumulus.MySqlSettings.CustomRollover.Command = settings.customrollover.command; } // Save the settings cumulus.WriteIniFile(); cumulus.SetMonthlySqlCreateString(); cumulus.SetStartOfMonthlyInsertSQL(); cumulus.SetDayfileSqlCreateString(); cumulus.SetStartOfDayfileInsertSQL(); cumulus.SetRealtimeSqlCreateString(); cumulus.SetStartOfRealtimeInsertSQL(); cumulus.CustomMysqlSecondsTimer.Interval = cumulus.MySqlSettings.CustomSecs.Interval * 1000; cumulus.CustomMysqlSecondsTimer.Enabled = cumulus.MySqlSettings.CustomSecs.Enabled; context.Response.StatusCode = 200; } catch (Exception ex) { var msg = "Error processing settings: " + ex.Message; cumulus.LogMessage(msg); context.Response.StatusCode = 500; return(msg); } return("success"); }
internal bool OpenTcpPort(string ipaddr, int port) { ipAddress = ipaddr; tcpPort = port; connecting = true; CloseTcpPort(); int attempt = 0; // Creating the new TCP socket effectively opens it - specify IP address or domain name and port while (attempt < 5 && socket == null) { attempt++; cumulus.LogDebugMessage("Ecowitt Gateway Connect attempt " + attempt); try { socket = new TcpClient(ipaddr, port); if (!socket.Connected) { try { socket.Close(); socket.Dispose(); } catch { } socket = null; } } catch (Exception ex) { cumulus.LogMessage("Error opening TCP port: " + ex.Message); } Thread.Sleep(5000); } // Set the timeout of the underlying stream if (socket != null) { try { stream = socket.GetStream(); stream.ReadTimeout = 2500; cumulus.LogDebugMessage("Ecowitt Gateway reconnected"); connecting = false; connected = true; } catch (ObjectDisposedException) { socket = null; } catch (Exception ex) { cumulus.LogMessage("Error reconnecting Ecowitt Gateway: " + ex.Message); } } else { cumulus.LogDebugMessage("Ecowitt Gateway connect failed"); connecting = false; return(false); } return(true); }
public string UpdateConfig(IHttpContext context) { var errorMsg = ""; var json = ""; JsonExtraSensorSettings settings; context.Response.StatusCode = 200; try { var data = new StreamReader(context.Request.InputStream).ReadToEnd(); // Start at char 5 to skip the "json:" prefix json = WebUtility.UrlDecode(data.Substring(5)); // de-serialize it to the settings structure settings = json.FromJson <JsonExtraSensorSettings>(); } catch (Exception ex) { var msg = "Error de-serializing ExtraSensor Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("ExtraSensor Data: " + json); context.Response.StatusCode = 500; return(msg); } // process the settings try { cumulus.LogMessage("Updating extra sensor settings"); // General settings try { cumulus.StationOptions.PrimaryAqSensor = settings.airquality.primaryaqsensor; cumulus.airQualityIndex = settings.airquality.aqi; } catch (Exception ex) { var msg = "Error processing General settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // AirLink settings try { cumulus.AirLinkIsNode = settings.airLink.isNode; cumulus.AirLinkApiKey = settings.airLink.apiKey; cumulus.AirLinkApiSecret = settings.airLink.apiSecret; cumulus.AirLinkAutoUpdateIpAddress = settings.airLink.autoUpdateIp; cumulus.AirLinkInEnabled = settings.airLink.indoor.enabled; if (cumulus.AirLinkInEnabled) { cumulus.AirLinkInIPAddr = settings.airLink.indoor.ipAddress; cumulus.AirLinkInHostName = settings.airLink.indoor.hostname; cumulus.AirLinkInStationId = settings.airLink.indoor.stationId; if (cumulus.AirLinkInStationId < 10 && cumulus.AirLinkIsNode) { cumulus.AirLinkInStationId = cumulus.WllStationId; } } cumulus.AirLinkOutEnabled = settings.airLink.outdoor.enabled; if (cumulus.AirLinkOutEnabled) { cumulus.AirLinkOutIPAddr = settings.airLink.outdoor.ipAddress; cumulus.AirLinkOutHostName = settings.airLink.outdoor.hostname; cumulus.AirLinkOutStationId = settings.airLink.outdoor.stationId; if (cumulus.AirLinkOutStationId < 10 && cumulus.AirLinkIsNode) { cumulus.AirLinkOutStationId = cumulus.WllStationId; } } } catch (Exception ex) { var msg = "Error processing AirLink settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Ecowitt Extra settings try { if (settings.httpSensors.extraStation == 0) { cumulus.EcowittExtraEnabled = true; cumulus.EcowittExtraUseSolar = settings.httpSensors.ecowitt.useSolar; cumulus.EcowittExtraUseUv = settings.httpSensors.ecowitt.useUv; cumulus.EcowittExtraUseTempHum = settings.httpSensors.ecowitt.useTempHum; //cumulus.EcowittExtraUseSoilTemp = settings.httpSensors.ecowitt.useSoilTemp; cumulus.EcowittExtraUseSoilMoist = settings.httpSensors.ecowitt.useSoilMoist; cumulus.EcowittExtraUseLeafWet = settings.httpSensors.ecowitt.useLeafWet; cumulus.EcowittExtraUseUserTemp = settings.httpSensors.ecowitt.useUserTemp; cumulus.EcowittExtraUseAQI = settings.httpSensors.ecowitt.useAQI; cumulus.EcowittExtraUseCo2 = settings.httpSensors.ecowitt.useCo2; cumulus.EcowittExtraUseLightning = settings.httpSensors.ecowitt.useLightning; cumulus.EcowittExtraUseLeak = settings.httpSensors.ecowitt.useLeak; cumulus.EcowittExtraSetCustomServer = settings.httpSensors.ecowitt.setcustom; cumulus.EcowittExtraGatewayAddr = settings.httpSensors.ecowitt.gwaddr; cumulus.EcowittExtraLocalAddr = settings.httpSensors.ecowitt.localaddr; cumulus.EcowittExtraCustomInterval = settings.httpSensors.ecowitt.interval; cumulus.Gw1000PrimaryTHSensor = settings.httpSensors.ecowitt.mappings.primaryTHsensor; if (cumulus.EcowittMapWN34[1] != settings.httpSensors.ecowitt.mappings.wn34chan1) { if (cumulus.EcowittMapWN34[1] == 0) { station.UserTemp[1] = 0; } else { station.SoilTemp[cumulus.EcowittMapWN34[1]] = 0; } cumulus.EcowittMapWN34[1] = settings.httpSensors.ecowitt.mappings.wn34chan1; } if (cumulus.EcowittMapWN34[2] != settings.httpSensors.ecowitt.mappings.wn34chan2) { if (cumulus.EcowittMapWN34[2] == 0) { station.UserTemp[2] = 0; } else { station.SoilTemp[cumulus.EcowittMapWN34[2]] = 0; } cumulus.EcowittMapWN34[2] = settings.httpSensors.ecowitt.mappings.wn34chan2; } if (cumulus.EcowittMapWN34[3] != settings.httpSensors.ecowitt.mappings.wn34chan3) { if (cumulus.EcowittMapWN34[3] == 0) { station.UserTemp[3] = 0; } else { station.SoilTemp[cumulus.EcowittMapWN34[3]] = 0; } cumulus.EcowittMapWN34[3] = settings.httpSensors.ecowitt.mappings.wn34chan3; } if (cumulus.EcowittMapWN34[4] != settings.httpSensors.ecowitt.mappings.wn34chan4) { if (cumulus.EcowittMapWN34[4] == 0) { station.UserTemp[4] = 0; } else { station.SoilTemp[cumulus.EcowittMapWN34[4]] = 0; } cumulus.EcowittMapWN34[4] = settings.httpSensors.ecowitt.mappings.wn34chan4; } if (cumulus.EcowittMapWN34[5] != settings.httpSensors.ecowitt.mappings.wn34chan5) { if (cumulus.EcowittMapWN34[5] == 0) { station.UserTemp[5] = 0; } else { station.SoilTemp[cumulus.EcowittMapWN34[5]] = 0; } cumulus.EcowittMapWN34[5] = settings.httpSensors.ecowitt.mappings.wn34chan5; } if (cumulus.EcowittMapWN34[6] != settings.httpSensors.ecowitt.mappings.wn34chan6) { if (cumulus.EcowittMapWN34[6] == 0) { station.UserTemp[6] = 0; } else { station.SoilTemp[cumulus.EcowittMapWN34[6]] = 0; } cumulus.EcowittMapWN34[6] = settings.httpSensors.ecowitt.mappings.wn34chan6; } if (cumulus.EcowittMapWN34[7] != settings.httpSensors.ecowitt.mappings.wn34chan7) { if (cumulus.EcowittMapWN34[7] == 0) { station.UserTemp[7] = 0; } else { station.SoilTemp[cumulus.EcowittMapWN34[7]] = 0; } cumulus.EcowittMapWN34[7] = settings.httpSensors.ecowitt.mappings.wn34chan7; } if (cumulus.EcowittMapWN34[8] != settings.httpSensors.ecowitt.mappings.wn34chan8) { if (cumulus.EcowittMapWN34[8] == 0) { station.UserTemp[8] = 0; } else { station.SoilTemp[cumulus.EcowittMapWN34[8]] = 0; } cumulus.EcowittMapWN34[8] = settings.httpSensors.ecowitt.mappings.wn34chan8; } // Also enable extra logging if applicable if (cumulus.EcowittExtraUseTempHum || cumulus.EcowittExtraUseSoilTemp || cumulus.EcowittExtraUseSoilMoist || cumulus.EcowittExtraUseLeafWet || cumulus.EcowittExtraUseUserTemp || cumulus.EcowittExtraUseAQI || cumulus.EcowittExtraUseCo2) { cumulus.StationOptions.LogExtraSensors = true; } } else { cumulus.EcowittExtraEnabled = false; } } catch (Exception ex) { var msg = "Error processing Ecowitt settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Ambient Extra settings try { if (settings.httpSensors.extraStation == 1) { cumulus.AmbientExtraEnabled = true; cumulus.AmbientExtraUseSolar = settings.httpSensors.ambient.useSolar; cumulus.AmbientExtraUseUv = settings.httpSensors.ambient.useUv; cumulus.AmbientExtraUseTempHum = settings.httpSensors.ambient.useTempHum; //cumulus.AmbientExtraUseSoilTemp = settings.httpSensors.ambient.useSoilTemp; cumulus.AmbientExtraUseSoilMoist = settings.httpSensors.ambient.useSoilMoist; //cumulus.AmbientExtraUseLeafWet = settings.httpSensors.ambient.useLeafWet; cumulus.AmbientExtraUseAQI = settings.httpSensors.ambient.useAQI; cumulus.AmbientExtraUseCo2 = settings.httpSensors.ambient.useCo2; cumulus.AmbientExtraUseLightning = settings.httpSensors.ambient.useLightning; cumulus.AmbientExtraUseLeak = settings.httpSensors.ambient.useLeak; // Also enable extra logging if applicable if (cumulus.AmbientExtraUseTempHum || cumulus.AmbientExtraUseSoilTemp || cumulus.AmbientExtraUseSoilMoist || cumulus.AmbientExtraUseAQI || cumulus.AmbientExtraUseCo2) { cumulus.StationOptions.LogExtraSensors = true; } } else { cumulus.AmbientExtraEnabled = false; } } catch (Exception ex) { var msg = "Error processing Ambient settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Blake-Larsen settings try { cumulus.SolarOptions.UseBlakeLarsen = settings.blakeLarsen.enabled; } catch (Exception ex) { var msg = "Error processing Blake-Larsen settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // RG-11 settings try { cumulus.RG11Enabled = settings.rg11.port1.enabled; if (cumulus.RG11Enabled) { cumulus.RG11Port = settings.rg11.port1.commPort; cumulus.RG11TBRmode = settings.rg11.port1.tipMode; cumulus.RG11tipsize = settings.rg11.port1.tipSize; cumulus.RG11IgnoreFirst = settings.rg11.port1.ignoreFirst; cumulus.RG11DTRmode = settings.rg11.port1.dtrMode; } cumulus.RG11Enabled2 = settings.rg11.port2.enabled; if (cumulus.RG11Enabled2) { cumulus.RG11Port2 = settings.rg11.port2.commPort; cumulus.RG11TBRmode2 = settings.rg11.port2.tipMode; cumulus.RG11tipsize2 = settings.rg11.port2.tipSize; cumulus.RG11IgnoreFirst2 = settings.rg11.port2.ignoreFirst; cumulus.RG11DTRmode2 = settings.rg11.port2.dtrMode; } } catch (Exception ex) { var msg = "Error processing RG-11 settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Save the settings cumulus.WriteIniFile(); } catch (Exception ex) { var msg = "Error processing Extra Sensor settings: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Extra Sensor Data: " + json); errorMsg += msg; context.Response.StatusCode = 500; } return(context.Response.StatusCode == 200 ? "success" : errorMsg); }
//public string UpdateCalibrationConfig(HttpListenerContext context) public string UpdateConfig(IHttpContext context) { var json = ""; JsonCalibrationSettingsData settings; var invC = new CultureInfo(""); try { var data = new StreamReader(context.Request.InputStream).ReadToEnd(); json = WebUtility.UrlDecode(data.Substring(5)); // de-serialize it to the settings structure settings = json.FromJson <JsonCalibrationSettingsData>(); } catch (Exception ex) { var msg = "Error de-serializing Calibration Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Calibration Data: " + json); context.Response.StatusCode = 500; return(msg); } try { // process the settings cumulus.LogMessage("Updating calibration settings"); // offsets cumulus.Calib.Press.Offset = Convert.ToDouble(settings.pressure.offset, invC); cumulus.Calib.Temp.Offset = Convert.ToDouble(settings.temp.offset, invC); cumulus.Calib.InTemp.Offset = Convert.ToDouble(settings.tempin.offset, invC); cumulus.Calib.Hum.Offset = settings.hum.offset; cumulus.Calib.WindDir.Offset = settings.winddir.offset; cumulus.Calib.Solar.Offset = Convert.ToDouble(settings.solar.offset); cumulus.Calib.UV.Offset = Convert.ToDouble(settings.uv.offset, invC); cumulus.Calib.WetBulb.Offset = Convert.ToDouble(settings.wetbulb.offset, invC); // multipliers cumulus.Calib.Press.Mult = Convert.ToDouble(settings.pressure.multiplier, invC); cumulus.Calib.WindSpeed.Mult = Convert.ToDouble(settings.windspd.multiplier, invC); cumulus.Calib.WindGust.Mult = Convert.ToDouble(settings.gust.multiplier, invC); cumulus.Calib.Temp.Mult = Convert.ToDouble(settings.temp.multiplier, invC); cumulus.Calib.Temp.Mult2 = Convert.ToDouble(settings.temp.multiplier2, invC); cumulus.Calib.Hum.Mult = Convert.ToDouble(settings.hum.multiplier, invC); cumulus.Calib.Hum.Mult2 = Convert.ToDouble(settings.hum.multiplier2, invC); cumulus.Calib.Rain.Mult = Convert.ToDouble(settings.rain.multiplier, invC); cumulus.Calib.Solar.Mult = Convert.ToDouble(settings.solar.multiplier, invC); cumulus.Calib.UV.Mult = Convert.ToDouble(settings.uv.multiplier, invC); cumulus.Calib.WetBulb.Mult = Convert.ToDouble(settings.wetbulb.multiplier, invC); // spike removal cumulus.Spike.TempDiff = Convert.ToDouble(settings.temp.spike, invC); cumulus.Spike.HumidityDiff = Convert.ToDouble(settings.hum.spike, invC); cumulus.Spike.WindDiff = Convert.ToDouble(settings.windspd.spike, invC); cumulus.Spike.GustDiff = Convert.ToDouble(settings.gust.spike, invC); cumulus.Spike.MaxHourlyRain = Convert.ToDouble(settings.rain.spikehour, invC); cumulus.Spike.MaxRainRate = Convert.ToDouble(settings.rain.spikerate, invC); cumulus.Spike.PressDiff = Convert.ToDouble(settings.pressure.spike, invC); // limits cumulus.Limit.TempHigh = Convert.ToDouble(settings.temp.limitmax, invC); cumulus.Limit.TempLow = Convert.ToDouble(settings.temp.limitmin, invC); cumulus.Limit.DewHigh = Convert.ToDouble(settings.dewpt.limitmax, invC); cumulus.Limit.PressHigh = Convert.ToDouble(settings.pressure.limitmax, invC); cumulus.Limit.PressLow = Convert.ToDouble(settings.pressure.limitmin, invC); cumulus.Limit.WindHigh = Convert.ToDouble(settings.gust.limitmax, invC); // Save the settings cumulus.WriteIniFile(); // Clear the spike alarm cumulus.SpikeAlarm.Triggered = false; // Log the new values cumulus.LogMessage("Setting new calibration values..."); cumulus.LogOffsetsMultipliers(); context.Response.StatusCode = 200; } catch (Exception ex) { cumulus.LogMessage("Error setting Calibration settings: " + ex.Message); cumulus.LogDebugMessage("Calibration Data: " + json); context.Response.StatusCode = 500; return(ex.Message); } return("success"); }
public string UpdateConfig(IHttpContext context) { var errorMsg = ""; var json = ""; JsonThirdPartySettings settings; context.Response.StatusCode = 200; try { var data = new StreamReader(context.Request.InputStream).ReadToEnd(); // Start at char 5 to skip the "json:" prefix json = WebUtility.UrlDecode(data.Substring(5)); // de-serialize it to the settings structure settings = json.FromJson <JsonThirdPartySettings>(); } catch (Exception ex) { var msg = "Error de-serializing 3rdParty Settings JSON: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("3rdParty Data: " + json); context.Response.StatusCode = 500; return(msg); } // process the settings try { cumulus.LogMessage("Updating third party settings"); // wunderground try { cumulus.Wund.Enabled = settings.wunderground.enabled; if (cumulus.Wund.Enabled) { cumulus.Wund.SendIndoor = settings.wunderground.includeindoor; cumulus.Wund.SendSolar = settings.wunderground.includesolar; cumulus.Wund.SendUV = settings.wunderground.includeuv; cumulus.Wund.SendAirQuality = settings.wunderground.includeaq; cumulus.Wund.Interval = settings.wunderground.interval; cumulus.Wund.PW = settings.wunderground.password ?? string.Empty; cumulus.Wund.RapidFireEnabled = settings.wunderground.rapidfire; cumulus.Wund.SendAverage = settings.wunderground.sendavgwind; cumulus.Wund.ID = settings.wunderground.stationid ?? string.Empty; cumulus.Wund.CatchUp = settings.wunderground.catchup; cumulus.Wund.SynchronisedUpdate = (!cumulus.Wund.RapidFireEnabled) && (60 % cumulus.Wund.Interval == 0); cumulus.WundTimer.Interval = cumulus.Wund.RapidFireEnabled ? 5000 : cumulus.Wund.Interval * 60 * 1000; cumulus.WundTimer.Enabled = cumulus.Wund.Enabled && !cumulus.Wund.SynchronisedUpdate && !string.IsNullOrWhiteSpace(cumulus.Wund.ID) && !string.IsNullOrWhiteSpace(cumulus.Wund.PW); } } catch (Exception ex) { var msg = "Error processing wunderground settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Windy try { cumulus.Windy.Enabled = settings.windy.enabled; if (cumulus.Windy.Enabled) { //cumulus.WindySendSolar = settings.windy.includesolar; cumulus.Windy.SendUV = settings.windy.includeuv; cumulus.Windy.Interval = settings.windy.interval; cumulus.Windy.ApiKey = settings.windy.apikey; cumulus.Windy.StationIdx = settings.windy.stationidx; cumulus.Windy.CatchUp = settings.windy.catchup; } } catch (Exception ex) { var msg = "Error processing Windy settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Awekas try { cumulus.AWEKAS.Enabled = settings.awekas.enabled; if (cumulus.AWEKAS.Enabled) { cumulus.AWEKAS.Interval = settings.awekas.interval; cumulus.AWEKAS.Lang = settings.awekas.lang; cumulus.AWEKAS.PW = settings.awekas.password ?? string.Empty; cumulus.AWEKAS.ID = settings.awekas.user ?? string.Empty; cumulus.AWEKAS.SendSolar = settings.awekas.includesolar; cumulus.AWEKAS.SendUV = settings.awekas.includeuv; cumulus.AWEKAS.SendSoilTemp = settings.awekas.includesoiltemp; cumulus.AWEKAS.SendSoilMoisture = settings.awekas.includesoilmoisture; cumulus.AWEKAS.SendLeafWetness = settings.awekas.includeleafwetness; cumulus.AWEKAS.SendIndoor = settings.awekas.includeindoor; cumulus.AWEKAS.SendAirQuality = settings.awekas.includeaq; cumulus.AWEKAS.SynchronisedUpdate = (cumulus.AWEKAS.Interval % 60 == 0); cumulus.AwekasTimer.Interval = cumulus.AWEKAS.Interval * 1000; cumulus.AwekasTimer.Enabled = cumulus.AWEKAS.Enabled && !cumulus.AWEKAS.SynchronisedUpdate && !string.IsNullOrWhiteSpace(cumulus.AWEKAS.ID) && !string.IsNullOrWhiteSpace(cumulus.AWEKAS.PW); } } catch (Exception ex) { var msg = "Error processing AWEKAS settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // WeatherCloud try { cumulus.WCloud.Enabled = settings.weathercloud.enabled; if (cumulus.WCloud.Enabled) { cumulus.WCloud.ID = settings.weathercloud.wid ?? string.Empty; cumulus.WCloud.PW = settings.weathercloud.key ?? string.Empty; cumulus.WCloud.Interval = settings.weathercloud.interval; cumulus.WCloud.SendSolar = settings.weathercloud.includesolar; cumulus.WCloud.SendUV = settings.weathercloud.includeuv; cumulus.WCloud.SendAirQuality = settings.weathercloud.includeaqi; cumulus.WCloud.SendSoilMoisture = settings.weathercloud.includesoilmoist; cumulus.WCloud.SoilMoistureSensor = settings.weathercloud.moistsensor; cumulus.WCloud.SendLeafWetness = settings.weathercloud.includeleafwet; cumulus.WCloud.LeafWetnessSensor = settings.weathercloud.leafwetsensor; } } catch (Exception ex) { var msg = "Error processing WeatherCloud settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // PWS weather try { cumulus.PWS.Enabled = settings.pwsweather.enabled; if (cumulus.PWS.Enabled) { cumulus.PWS.Interval = settings.pwsweather.interval; cumulus.PWS.SendSolar = settings.pwsweather.includesolar; cumulus.PWS.SendUV = settings.pwsweather.includeuv; cumulus.PWS.PW = settings.pwsweather.password ?? string.Empty; cumulus.PWS.ID = settings.pwsweather.stationid ?? string.Empty; cumulus.PWS.CatchUp = settings.pwsweather.catchup; } } catch (Exception ex) { var msg = "Error processing PWS weather settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // WOW try { cumulus.WOW.Enabled = settings.wow.enabled; if (cumulus.WOW.Enabled) { cumulus.WOW.SendSolar = settings.wow.includesolar; cumulus.WOW.SendUV = settings.wow.includeuv; cumulus.WOW.SendSoilTemp = settings.wow.includesoiltemp; cumulus.WOW.SoilTempSensor = settings.wow.soiltempsensor; cumulus.WOW.Interval = settings.wow.interval; cumulus.WOW.PW = settings.wow.password ?? string.Empty; cumulus.WOW.ID = settings.wow.stationid ?? string.Empty; cumulus.WOW.CatchUp = settings.wow.catchup; } } catch (Exception ex) { var msg = "Error processing WOW settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // CWOP try { cumulus.APRS.Enabled = settings.cwop.enabled; if (cumulus.APRS.Enabled) { cumulus.APRS.ID = settings.cwop.id ?? string.Empty;; cumulus.APRS.Interval = settings.cwop.interval; cumulus.APRS.SendSolar = settings.cwop.includesolar; cumulus.APRS.PW = settings.cwop.password ?? string.Empty;; cumulus.APRS.Port = settings.cwop.port; cumulus.APRS.Server = settings.cwop.server ?? string.Empty;; } } catch (Exception ex) { var msg = "Error processing CWOP settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // OpenWeatherMap try { cumulus.OpenWeatherMap.Enabled = settings.openweathermap.enabled; if (cumulus.OpenWeatherMap.Enabled) { cumulus.OpenWeatherMap.CatchUp = settings.openweathermap.catchup; cumulus.OpenWeatherMap.PW = settings.openweathermap.apikey; cumulus.OpenWeatherMap.ID = settings.openweathermap.stationid; cumulus.OpenWeatherMap.Interval = settings.openweathermap.interval; } } catch (Exception ex) { var msg = "Error processing OpenWeatherMap settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Wind Guru try { cumulus.WindGuru.Enabled = settings.windguru.enabled; if (cumulus.WindGuru.Enabled) { cumulus.WindGuru.ID = settings.windguru.uid; cumulus.WindGuru.PW = settings.windguru.password; cumulus.WindGuru.SendRain = settings.windguru.includerain; cumulus.WindGuru.Interval = settings.windguru.interval; } } catch (Exception ex) { var msg = "Error processing WindGuru settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Custom HTTP try { // custom seconds cumulus.CustomHttpSecondsEnabled = settings.customhttp.customseconds.enabled; cumulus.CustomHttpSecondsTimer.Enabled = cumulus.CustomHttpSecondsEnabled; if (cumulus.CustomHttpSecondsEnabled) { cumulus.CustomHttpSecondsStrings[0] = settings.customhttp.customseconds.url[0] ?? string.Empty; for (var i = 1; i < 10; i++) { if (i < settings.customhttp.customseconds.url.Length) { cumulus.CustomHttpSecondsStrings[i] = settings.customhttp.customseconds.url[i] ?? null; } else { cumulus.CustomHttpSecondsStrings[i] = null; } } cumulus.CustomHttpSecondsInterval = settings.customhttp.customseconds.interval; cumulus.CustomHttpSecondsTimer.Interval = cumulus.CustomHttpSecondsInterval * 1000; } // custom minutes cumulus.CustomHttpMinutesEnabled = settings.customhttp.customminutes.enabled; if (cumulus.CustomHttpMinutesEnabled) { cumulus.CustomHttpMinutesStrings[0] = settings.customhttp.customminutes.url[0] ?? string.Empty; for (var i = 1; i < 10; i++) { if (i < settings.customhttp.customseconds.url.Length) { cumulus.CustomHttpMinutesStrings[i] = settings.customhttp.customminutes.url[i] ?? null; } else { cumulus.CustomHttpMinutesStrings[i] = null; } } cumulus.CustomHttpMinutesIntervalIndex = settings.customhttp.customminutes.intervalindex; if (cumulus.CustomHttpMinutesIntervalIndex >= 0 && cumulus.CustomHttpMinutesIntervalIndex < cumulus.FactorsOf60.Length) { cumulus.CustomHttpMinutesInterval = cumulus.FactorsOf60[cumulus.CustomHttpMinutesIntervalIndex]; } else { cumulus.CustomHttpMinutesInterval = 10; } } // custom roll-over cumulus.CustomHttpRolloverEnabled = settings.customhttp.customrollover.enabled; if (cumulus.CustomHttpRolloverEnabled) { cumulus.CustomHttpRolloverStrings[0] = settings.customhttp.customrollover.url[0] ?? string.Empty; for (var i = 1; i < 10; i++) { if (i < settings.customhttp.customrollover.url.Length) { cumulus.CustomHttpMinutesStrings[i] = settings.customhttp.customrollover.url[i] ?? null; } else { cumulus.CustomHttpMinutesStrings[i] = null; } } } } catch (Exception ex) { var msg = "Error processing Custom settings: " + ex.Message; cumulus.LogMessage(msg); errorMsg += msg + "\n\n"; context.Response.StatusCode = 500; } // Save the settings cumulus.WriteIniFile(); // Do OpenWeatherMap set-up cumulus.EnableOpenWeatherMap(); } catch (Exception ex) { var msg = "Error processing Third Party settings: " + ex.Message; cumulus.LogMessage(msg); cumulus.LogDebugMessage("Third Party data: " + json); errorMsg += msg; context.Response.StatusCode = 500; } return(context.Response.StatusCode == 200 ? "success" : errorMsg); }
public static List <Observation> GetRestPacket(string url, string token, int deviceId, DateTime start, DateTime end, Cumulus c) { List <Observation> ret = new List <Observation>(); cumulus = c; using (var httpClient = new HttpClient()) { var tpStart = start; var tpEnd = end; double ts = tpEnd.Subtract(tpStart).TotalDays; while (ts > 0) { long st; long end_time; st = WeatherPacket.ToUnixTimeSeconds(tpStart); end_time = WeatherPacket.ToUnixTimeSeconds(end); if (ts > 4) // load max 4 days at a time { tpStart = tpStart.AddDays(4); end_time = WeatherPacket.ToUnixTimeSeconds(tpStart) - 1; // subtract a second so we don't overlap ts = tpEnd.Subtract(tpStart).TotalDays; } else { ts = 0; } cumulus.LogDebugMessage($"GetRestPacket: Requesting from URL - {url}device/{deviceId}?token=<<token>>&time_start={st}&time_end={end_time}"); using (var response = httpClient.GetAsync($"{url}device/{deviceId}?token={token}&time_start={st}&time_end={end_time}") ) { string apiResponse = response.Result.Content.ReadAsStringAsync().Result; var rp = JsonSerializer.DeserializeFromString <RestPacket>(apiResponse); if (rp != null && rp.status.status_message.Equals("SUCCESS") && rp.obs != null) { foreach (var ob in rp.obs) { ret.Add(new Observation(ob)); } } else if (rp != null && rp.status.status_message.Equals("SUCCESS")) { // no data for time period, ignore //cumulus.LogConsoleMessage($"No data for time period from {tpStart} to {end}"); } else { var msg = $"Error downloading tempest history: {apiResponse}"; cumulus.LogMessage(msg); cumulus.LogConsoleMessage(msg, ConsoleColor.Red); if (rp.status.status_code == 404) { cumulus.LogConsoleMessage("Normally indicates incorrect Device ID"); ts = -1; // force a stop, fatal error } if (rp.status.status_code == 401) { cumulus.LogConsoleMessage("Normally indicates incorrect Token"); ts = -1; // force a stop, fatal error } } } } } return(ret); }