예제 #1
0
        public WMR100Station(Cumulus cumulus) : base(cumulus)
        {
            cumulus.Manufacturer = cumulus.OREGONUSB;
            var devicelist = DeviceList.Local;
            var station    = devicelist.GetHidDeviceOrNull(Vendorid, Productid);

            if (station != null)
            {
                cumulus.LogMessage("WMR100 station found");

                if (station.TryOpen(out stream))
                {
                    cumulus.LogMessage("Stream opened");
                }

                packetBuffer = new byte[PacketBufferBound];

                WMR200ExtraTempValues = new double[11];
                WMR200ExtraHumValues  = new double[11];
                WMR200ChannelPresent  = new bool[11];
                WMR200ExtraDPValues   = new double[11];

                LoadLastHoursFromDataLogs(DateTime.Now);
            }
            else
            {
                cumulus.LogMessage("WMR100 station not found!");
                cumulus.LogConsoleMessage("WMR100 station not found!");
            }
        }
예제 #2
0
        public WMR100Station(Cumulus cumulus) : base(cumulus)
        {
            cumulus.Manufacturer = cumulus.OREGONUSB;
            devicelist           = DeviceList.Local;
            station = devicelist.GetHidDeviceOrNull(Vendorid, Productid);

            if (station != null)
            {
                cumulus.LogMessage(DateTime.Now.ToLongTimeString() + " WMR100 station found");

                if (station.TryOpen(out stream))
                {
                    cumulus.LogMessage(DateTime.Now.ToLongTimeString() + " Stream opened");
                }

                PacketBuffer = new byte[PacketBufferBound];

                WMR200ExtraTempValues = new double[11];
                WMR200ExtraHumValues  = new double[11];
                WMR200ChannelPresent  = new bool[11];
                WMR200ExtraDPValues   = new double[11];
            }
            else
            {
                cumulus.LogMessage(DateTime.Now.ToLongTimeString() + " WMR100 station not found!");
                Console.WriteLine("WMR100 station not found!");
            }
        }
예제 #3
0
        public Simulator(Cumulus cumulus) : base(cumulus)
        {
            cumulus.LogMessage("Station type = Simulator");

            cumulus.LogMessage("Last update time = " + cumulus.LastUpdateTime);

            cancellationToken = tokenSource.Token;

            random = new Random();

            currData = new DataSet();

            cumulus.StationOptions.CalculatedDP            = true;
            cumulus.StationOptions.CalculatedET            = true;
            cumulus.StationOptions.CalculatedWC            = true;
            cumulus.StationOptions.UseWind10MinAvg         = true;
            cumulus.StationOptions.UseCumulusPresstrendstr = true;
            cumulus.StationOptions.UseSpeedForAvgCalc      = false;

            WindAverage = 0;

            timerStartNeeded = true;
            LoadLastHoursFromDataLogs(cumulus.LastUpdateTime);
            DoDayResetIfNeeded();
            DoTrendValues(DateTime.Now);
        }
예제 #4
0
        public WS2300Station(Cumulus cumulus) : base(cumulus)
        {
            cumulus.Manufacturer = cumulus.LACROSSE;
            calculaterainrate    = true;

            cumulus.LogMessage("WS2300: Attempting to open " + cumulus.ComportName);

            comport = new SerialPort(cumulus.ComportName, 2400, Parity.None, 8, StopBits.One)
            {
                Handshake    = Handshake.None,
                DtrEnable    = false,
                RtsEnable    = true,
                ReadTimeout  = 500,
                WriteTimeout = 1000
            };

            try
            {
                comport.Open();
                cumulus.LogMessage("COM port opened");
            }
            catch (Exception ex)
            {
                cumulus.LogMessage(ex.Message);
                //MessageBox.Show(ex.Message);
            }

            if (comport.IsOpen)
            {
                // Read the data from the logger
                cumulus.CurrentActivity = "Reading archive data";
                startReadingHistoryData();
            }
        }
예제 #5
0
        //public string UpdateCalibrationConfig(HttpListenerContext context)
        public string UpdateCalibrationConfig(IHttpContext context)
        {
            try
            {
                var InvC = new CultureInfo("");
                var data = new StreamReader(context.Request.InputStream).ReadToEnd();

                var json = WebUtility.UrlDecode(data.Substring(5));

                // de-serialize it to the settings structure
                var settings = JsonConvert.DeserializeObject <JsonCalibrationSettingsData>(json);
                // process the settings
                cumulus.LogMessage("Updating calibration settings");

                // offsets
                cumulus.PressOffset   = Convert.ToDouble(settings.offsets.pressure, InvC);
                cumulus.TempOffset    = Convert.ToDouble(settings.offsets.temperature, InvC);
                cumulus.InTempoffset  = Convert.ToDouble(settings.offsets.indoortemp, InvC);
                cumulus.HumOffset     = settings.offsets.humidity;
                cumulus.WindDirOffset = settings.offsets.winddir;
                cumulus.UVOffset      = Convert.ToDouble(settings.offsets.uv, InvC);
                cumulus.WetBulbOffset = Convert.ToDouble(settings.offsets.wetbulb, InvC);

                // multipliers
                cumulus.WindSpeedMult = Convert.ToDouble(settings.multipliers.windspeed, InvC);
                cumulus.WindGustMult  = Convert.ToDouble(settings.multipliers.windgust, InvC);
                cumulus.TempMult      = Convert.ToDouble(settings.multipliers.outdoortemp, InvC);
                cumulus.HumMult       = Convert.ToDouble(settings.multipliers.humidity, InvC);
                cumulus.RainMult      = Convert.ToDouble(settings.multipliers.rainfall, InvC);
                cumulus.UVMult        = Convert.ToDouble(settings.multipliers.uv, InvC);
                cumulus.WetBulbMult   = Convert.ToDouble(settings.multipliers.wetbulb, InvC);

                // spike removal
                cumulus.EWtempdiff           = Convert.ToDouble(settings.spikeremoval.outdoortemp, InvC);
                cumulus.EWhumiditydiff       = Convert.ToDouble(settings.spikeremoval.humidity, InvC);
                cumulus.EWwinddiff           = Convert.ToDouble(settings.spikeremoval.windspeed, InvC);
                cumulus.EWgustdiff           = Convert.ToDouble(settings.spikeremoval.windgust, InvC);
                cumulus.EWmaxHourlyRain      = Convert.ToDouble(settings.spikeremoval.maxhourlyrain, InvC);
                cumulus.EWmaxRainRate        = Convert.ToDouble(settings.spikeremoval.maxrainrate, InvC);
                cumulus.EWpressurediff       = Convert.ToDouble(settings.spikeremoval.pressure, InvC);
                cumulus.ErrorLogSpikeRemoval = settings.spikeremoval.log;

                // Save the settings
                cumulus.WriteIniFile();

                context.Response.StatusCode = 200;
            }
            catch (Exception ex)
            {
                cumulus.LogMessage(ex.Message);
                context.Response.StatusCode = 500;
                return(ex.Message);
            }
            return("success");
        }
예제 #6
0
 private static async void Connect(MQTTnet.Client.Options.IMqttClientOptions options)
 {
     try
     {
         await mqttClient.ConnectAsync(options, CancellationToken.None);
     }
     catch (Exception e)
     {
         cumulus.LogMessage("MQTT Error: failed to connect to the host");
         cumulus.LogMessage(e.Message);
     }
 }
예제 #7
0
        // 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());
        }
예제 #8
0
        public string UpdateProgramConfig(IHttpContext context)
        {
            var errorMsg = "";

            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
                var json = WebUtility.UrlDecode(data.Substring(5));

                // de-serialize it to the settings structure
                var settings = JsonSerializer.DeserializeFromString <JsonProgramSettingsOptions>(json);

                // process the settings
                try
                {
                    cumulus.ProgramOptions.StartupPingHost       = settings.startuphostping;
                    cumulus.ProgramOptions.StartupPingEscapeTime = settings.startuppingescape;
                    cumulus.ProgramOptions.StartupDelaySecs      = settings.startupdelay;
                    cumulus.ProgramOptions.StartupDelayMaxUptime = settings.startupdelaymaxuptime;
                    cumulus.ProgramOptions.DebugLogging          = settings.debuglogging;
                    cumulus.ProgramOptions.DataLogging           = settings.datalogging;
                    cumulus.ProgramOptions.WarnMultiple          = settings.stopsecondinstance;
                }
                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();
            }
            catch (Exception ex)
            {
                cumulus.LogMessage(ex.Message);
                context.Response.StatusCode = 500;
                return(ex.Message);
            }

            return(context.Response.StatusCode == 200 ? "success" : errorMsg);
        }
예제 #9
0
        public HttpStationEcowitt(Cumulus cumulus, WeatherStation station = null) : base(cumulus)
        {
            this.station = station;

            if (station == null)
            {
                cumulus.LogMessage("Creating HTTP Station (Ecowitt)");
            }
            else
            {
                cumulus.LogMessage("Creating Extra Sensors - HTTP Station (Ecowitt)");
            }

            //cumulus.StationOptions.CalculatedWC = true;
            // GW1000 does not provide average wind speeds
            // Do not set these if we are only using extra sensors
            if (station == null)
            {
                cumulus.StationOptions.UseWind10MinAve    = true;
                cumulus.StationOptions.UseSpeedForAvgCalc = false;
                // GW1000 does not send DP, so force MX to calculate it
                cumulus.StationOptions.CalculatedDP = true;
                // Same for Wind Chill
                cumulus.StationOptions.CalculatedWC = true;
            }

            cumulus.Manufacturer = cumulus.ECOWITT;
            if (station == null || (station != null && cumulus.EcowittExtraUseAQI))
            {
                cumulus.AirQualityUnitText = "µg/m³";
            }
            if (station == null || (station != null && cumulus.EcowittExtraUseSoilMoist))
            {
                cumulus.SoilMoistureUnitText = "%";
            }

            // Only perform the Start-up if we are a proper station, not a Extra Sensor
            if (station == null)
            {
                Start();
            }
            else
            {
                cumulus.LogMessage("Extra Sensors - HTTP Station (Ecowitt) - Waiting for data...");
            }
        }
예제 #10
0
        public List <string> GenerateNoaaYearReport(int year)
        {
            NOAA     noaa   = new NOAA(cumulus);
            DateTime noaats = new DateTime(year, 1, 1);

            cumulus.LogMessage("Creating NOAA yearly report");
            report = noaa.CreateYearlyReport(noaats);
            // If not using UTF, then we have to convert the character set
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            var encoding       = cumulus.NOAAUseUTF8 ? utf8WithoutBom : System.Text.Encoding.GetEncoding("iso-8859-1");
            var reportName     = noaats.ToString(cumulus.NOAAYearFileFormat);

            noaafile = cumulus.ReportPath + reportName;
            cumulus.LogMessage("Saving yearly NOAA report as " + noaafile);
            File.WriteAllLines(noaafile, report, encoding);

            return(report);
        }
예제 #11
0
        private static async Task SendMessageAsync(string topic, string message, bool retain)
        {
            cumulus.LogDataMessage($"MQTT: publishing to topic '{topic}', message '{message}'");
            if (mqttClient.IsConnected)
            {
                var mqttMsg = new MqttApplicationMessageBuilder()
                              .WithTopic(topic)
                              .WithPayload(message)
                              .WithRetainFlag(retain)
                              .Build();

                await mqttClient.PublishAsync(mqttMsg, CancellationToken.None);
            }
            else
            {
                cumulus.LogMessage("MQTT: Error - Not connected to MQTT server - message not sent");
            }
        }
예제 #12
0
        public TempestStation(Cumulus cumulus) : base(cumulus)
        {
            cumulus.Manufacturer = cumulus.WEATHERFLOW;
            calculaterainrate    = false;

            cumulus.LogMessage("Station type = Tempest");
            LoadLastHoursFromDataLogs(cumulus.LastUpdateTime);

            Task.Run(getAndProcessHistoryData);            // grab old data, then start the station
        }
예제 #13
0
        public WM918Station(Cumulus cumulus)
            : base(cumulus)
        {
            cumulus.Manufacturer = cumulus.OREGON;
            // station supplies rain rate
            calculaterainrate = false;

            cumulus.LogMessage("Station type = WM918");

            startReadingHistoryData();
        }
예제 #14
0
        public HttpStationAmbient(Cumulus cumulus, WeatherStation station = null) : base(cumulus)
        {
            this.station = station;

            if (station == null)
            {
                cumulus.LogMessage("Creating HTTP Station (Ambient)");
            }
            else
            {
                cumulus.LogMessage("Creating Extra Sensors - HTTP Station (Ambient)");
            }


            //cumulus.StationOptions.CalculatedWC = true;
            // Ambient does not provide average wind speeds
            cumulus.StationOptions.UseWind10MinAve    = true;
            cumulus.StationOptions.UseSpeedForAvgCalc = false;
            // Ambient does not send the rain rate, so we will calculate it
            calculaterainrate = true;
            // Ambient does not send DP, so force MX to calculate it
            //cumulus.StationOptions.CalculatedDP = true;

            cumulus.Manufacturer = cumulus.AMBIENT;
            if (station == null || (station != null && cumulus.AmbientExtraUseAQI))
            {
                cumulus.AirQualityUnitText = "µg/m³";
            }
            if (station == null || (station != null && cumulus.AmbientExtraUseSoilMoist))
            {
                cumulus.SoilMoistureUnitText = "%";
            }

            // Only perform the Start-up if we are a proper station, not a Extra Sensor
            if (station == null)
            {
                Start();
            }
        }
예제 #15
0
        public ImetStation(Cumulus cumulus) : base(cumulus)
        {
            cumulus.Manufacturer = cumulus.INSTROMET;
            cumulus.LogMessage("ImetWaitTime=" + cumulus.ImetWaitTime);
            cumulus.LogMessage("ImetBaudRate=" + cumulus.ImetBaudRate);
            cumulus.LogMessage("Instromet: Attempting to open " + cumulus.ComportName);

            calculaterainrate = true;

            comport = new SerialPort(cumulus.ComportName, cumulus.ImetBaudRate, Parity.None, 8, StopBits.One)
            {
                Handshake = Handshake.None, RtsEnable = true, DtrEnable = true
            };

            try
            {
                comport.ReadTimeout = 1000;
                comport.Open();
                cumulus.LogMessage("COM port opened");
            }
            catch (Exception ex)
            {
                cumulus.LogMessage(ex.Message);
                //MessageBox.Show(ex.Message);
            }

            if (comport.IsOpen)
            {
                ImetSetLoggerInterval(cumulus.logints[cumulus.DataLogInterval]);
                if (cumulus.SyncTime)
                {
                    SetStationClock();
                }

                // Read the data from the logger
                cumulus.CurrentActivity = "Reading archive data";
                startReadingHistoryData();
            }
        }
예제 #16
0
        //internal string EditRainToday(HttpListenerContext context)
        internal string EditRainToday(IHttpContext context)
        {
            var    InvC    = new CultureInfo("");
            var    request = context.Request;
            string text;

            using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
            {
                text = reader.ReadToEnd();
            }

            string[] kvPair          = text.Split('=');
            string   key             = kvPair[0];
            string   raintodaystring = kvPair[1];

            if (!String.IsNullOrEmpty(raintodaystring))
            {
                try
                {
                    double raintoday = Double.Parse(raintodaystring, CultureInfo.InvariantCulture);
                    cumulus.LogMessage("Before rain today edit, raintoday=" + station.RainToday.ToString(cumulus.RainFormat) + " Raindaystart=" + station.raindaystart.ToString(cumulus.RainFormat));
                    station.RainToday    = raintoday;
                    station.raindaystart = station.Raincounter - (station.RainToday / cumulus.RainMult);
                    cumulus.LogMessage("After rain today edit,  raintoday=" + station.RainToday.ToString(cumulus.RainFormat) + " Raindaystart=" + station.raindaystart.ToString(cumulus.RainFormat));
                }
                catch (Exception ex)
                {
                    cumulus.LogMessage("Edit rain today: " + ex.Message);
                }
            }

            var json = "{\"raintoday\":\"" + station.RainToday.ToString(cumulus.RainFormat, InvC) +
                       "\",\"raincounter\":\"" + station.Raincounter.ToString(cumulus.RainFormat, InvC) +
                       "\",\"startofdayrain\":\"" + station.raindaystart.ToString(cumulus.RainFormat, InvC) +
                       "\",\"rainmult\":\"" + cumulus.RainMult.ToString("F3", InvC) + "\"}";

            return(json);
        }
예제 #17
0
        public HttpStationWund(Cumulus cumulus) : base(cumulus)
        {
            cumulus.LogMessage("Starting HTTP Station (Wunderground)");

            cumulus.StationOptions.CalculatedWC = true;
            cumulus.Units.AirQualityUnitText    = "µg/m³";
            cumulus.Units.SoilMoistureUnitText  = "%";
            cumulus.Units.LeafWetnessUnitText   = "%";

            // Wunderground does not send the rain rate, so we will calculate it
            calculaterainrate = true;

            Start();
        }
예제 #18
0
        public TempestStation(Cumulus cumulus) : base(cumulus)
        {
            calculaterainrate = false;

            cumulus.LogMessage("Station type = Tempest");

            // Tempest does not provide pressure trend strings
            cumulus.StationOptions.UseCumulusPresstrendstr = true;

            // Tempest does not provide wind chill
            cumulus.StationOptions.CalculatedWC = true;

            LoadLastHoursFromDataLogs(cumulus.LastUpdateTime);

            Task.Run(getAndProcessHistoryData);            // grab old data, then start the station
        }
예제 #19
0
 private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
 {
     try
     {
         cumulus.LogMessage(e.ExceptionObject.ToString());
         Trace.Flush();
         Console.WriteLine(e.ExceptionObject.ToString());
         Console.WriteLine("**** An error has occurred - please zip up the MXdiags folder and post it in the forum ****");
         Console.WriteLine("Press Enter to terminate");
         Console.ReadLine();
         Environment.Exit(1);
     }
     catch (Exception)
     {
     }
 }
예제 #20
0
 private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
 {
     try
     {
         cumulus.LogMessage(e.ExceptionObject.ToString());
         Trace.Flush();
         Console.WriteLine(e.ExceptionObject.ToString());
         Console.WriteLine("**** Ha ocurrido un error - enviar los registros de la carpeta MXdiags a [email protected] ****");
         Console.WriteLine("Presiona Enter para terminar");
         Console.ReadLine();
         Environment.Exit(1);
     }
     catch (Exception)
     {
     }
 }
예제 #21
0
        public ImetStation(Cumulus cumulus) : base(cumulus)
        {
            cumulus.Manufacturer = cumulus.INSTROMET;
            cumulus.LogMessage("ImetUpdateLogPointer=" + cumulus.ImetOptions.ImetUpdateLogPointer);
            cumulus.LogMessage("ImetWaitTime=" + cumulus.ImetOptions.ImetWaitTime);
            cumulus.LogMessage("ImetReadDelay=" + cumulus.ImetOptions.ImetReadDelay);
            cumulus.LogMessage("ImetOptions.ImetBaudRate=" + cumulus.ImetOptions.ImetBaudRate);
            cumulus.LogMessage("Instromet: Attempting to open " + cumulus.ComportName);

            calculaterainrate = true;

            // Change the default dps for rain and sunshine from 1 to 2 for IMet stations
            cumulus.RainDPlaces           = cumulus.SunshineDPlaces = 2;
            cumulus.RainDPlaceDefaults[0] = 2;              // mm
            cumulus.RainDPlaceDefaults[1] = 3;              // in
            cumulus.RainFormat            = cumulus.SunFormat = "F2";

            comport = new SerialPort(cumulus.ComportName, cumulus.ImetOptions.ImetBaudRate, Parity.None, 8, StopBits.One)
            {
                Handshake = Handshake.None, RtsEnable = true, DtrEnable = true
            };

            try
            {
                comport.ReadTimeout = 1000;
                comport.Open();
                cumulus.LogMessage("COM port opened");
            }
            catch (Exception ex)
            {
                cumulus.LogMessage(ex.Message);
                //MessageBox.Show(ex.Message);
            }

            if (comport.IsOpen)
            {
                ImetSetLoggerInterval(cumulus.logints[cumulus.DataLogInterval]);
                if (cumulus.StationOptions.SyncTime)
                {
                    SetStationClock();
                }

                // Read the data from the logger
                cumulus.CurrentActivity = "Reading archive data";
                startReadingHistoryData();
            }
        }
예제 #22
0
        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);
        }
예제 #23
0
        //public string UpdateCalibrationConfig(HttpListenerContext context)
        public string UpdateCalibrationConfig(IHttpContext context)
        {
            try
            {
                var InvC = new CultureInfo("");
                var data = new StreamReader(context.Request.InputStream).ReadToEnd();

                var json = WebUtility.UrlDecode(data.Substring(5));

                // de-serialize it to the settings structure
                var settings = JsonConvert.DeserializeObject <JsonCalibrationSettingsData>(json);
                // process the settings
                cumulus.LogMessage("Updating calibration settings");

                // offsets
                cumulus.PressOffset   = Convert.ToDouble(settings.offsets.pressure, InvC);
                cumulus.TempOffset    = Convert.ToDouble(settings.offsets.temperature, InvC);
                cumulus.InTempoffset  = Convert.ToDouble(settings.offsets.indoortemp, InvC);
                cumulus.HumOffset     = settings.offsets.humidity;
                cumulus.WindDirOffset = settings.offsets.winddir;
                cumulus.SolarOffset   = Convert.ToDouble(settings.offsets.solar);
                cumulus.UVOffset      = Convert.ToDouble(settings.offsets.uv, InvC);
                cumulus.WetBulbOffset = Convert.ToDouble(settings.offsets.wetbulb, InvC);

                // multipliers
                cumulus.PressMult     = Convert.ToDouble(settings.multipliers.pressure, InvC);
                cumulus.WindSpeedMult = Convert.ToDouble(settings.multipliers.windspeed, InvC);
                cumulus.WindGustMult  = Convert.ToDouble(settings.multipliers.windgust, InvC);
                cumulus.TempMult      = Convert.ToDouble(settings.multipliers.outdoortemp, InvC);
                cumulus.HumMult       = Convert.ToDouble(settings.multipliers.humidity, InvC);
                cumulus.RainMult      = Convert.ToDouble(settings.multipliers.rainfall, InvC);
                cumulus.SolarMult     = Convert.ToDouble(settings.multipliers.solar, InvC);
                cumulus.UVMult        = Convert.ToDouble(settings.multipliers.uv, InvC);
                cumulus.WetBulbMult   = Convert.ToDouble(settings.multipliers.wetbulb, InvC);

                // spike removal
                cumulus.SpikeTempDiff      = Convert.ToDouble(settings.spikeremoval.outdoortemp, InvC);
                cumulus.SpikeHumidityDiff  = Convert.ToDouble(settings.spikeremoval.humidity, InvC);
                cumulus.SpikeWindDiff      = Convert.ToDouble(settings.spikeremoval.windspeed, InvC);
                cumulus.SpikeGustDiff      = Convert.ToDouble(settings.spikeremoval.windgust, InvC);
                cumulus.SpikeMaxHourlyRain = Convert.ToDouble(settings.spikeremoval.maxhourlyrain, InvC);
                cumulus.SpikeMaxRainRate   = Convert.ToDouble(settings.spikeremoval.maxrainrate, InvC);
                cumulus.SpikePressDiff     = Convert.ToDouble(settings.spikeremoval.pressure, InvC);

                // limits
                cumulus.LimitTempHigh  = Convert.ToDouble(settings.limits.temphigh, InvC);
                cumulus.LimitTempLow   = Convert.ToDouble(settings.limits.templow, InvC);
                cumulus.LimitDewHigh   = Convert.ToDouble(settings.limits.dewhigh, InvC);
                cumulus.LimitPressHigh = Convert.ToDouble(settings.limits.presshigh, InvC);
                cumulus.LimitPressLow  = Convert.ToDouble(settings.limits.presslow, InvC);
                cumulus.LimitWindHigh  = Convert.ToDouble(settings.limits.windhigh, InvC);

                cumulus.ErrorLogSpikeRemoval = settings.log;

                // Save the settings
                cumulus.WriteIniFile();

                // Clear the spike alarm
                cumulus.SpikeAlarmState = false;

                // Log the new values
                cumulus.LogMessage("Setting new calibration values...");
                cumulus.LogOffsetsMultipliers();

                context.Response.StatusCode = 200;
            }
            catch (Exception ex)
            {
                cumulus.LogMessage(ex.Message);
                context.Response.StatusCode = 500;
                return(ex.Message);
            }
            return("success");
        }
예제 #24
0
        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);
        }
예제 #25
0
        //public string UpdateNoaaConfig(HttpListenerContext context)
        public string UpdateNoaaConfig(IHttpContext context)
        {
            try
            {
                var data = new StreamReader(context.Request.InputStream).ReadToEnd();

                // Start at char 5 to skip the "json:" prefix
                var json = WebUtility.UrlDecode(data.Substring(5));

                // de-serialize it to the settings structure
                var settings = json.FromJson <JsonNOAASettingsData>();
                // process the settings
                cumulus.LogMessage("Updating NOAA settings");

                cumulus.NOAAname             = settings.sitename;
                cumulus.NOAAcity             = settings.city;
                cumulus.NOAAstate            = settings.state;
                cumulus.NOAA12hourformat     = settings.timeformat == 0;
                cumulus.NOAAMonthFileFormat  = settings.monthfileformat;
                cumulus.NOAAYearFileFormat   = settings.yearfileformat;
                cumulus.NOAAUseUTF8          = settings.utf8;
                cumulus.NOAAUseDotDecimal    = settings.dotdecimal;
                cumulus.NOAAAutoSave         = settings.autosave;
                cumulus.NOAAAutoFTP          = settings.autoftp;
                cumulus.NOAAFTPDirectory     = settings.ftpdirectory;
                cumulus.NOAAheatingthreshold = settings.heatingthreshold;
                cumulus.NOAAcoolingthreshold = settings.coolingthreshold;
                cumulus.NOAAmaxtempcomp1     = settings.maxtempcomp1;
                cumulus.NOAAmaxtempcomp2     = settings.maxtempcomp2;
                cumulus.NOAAmintempcomp1     = settings.mintempcomp1;
                cumulus.NOAAmintempcomp2     = settings.mintempcomp2;
                cumulus.NOAAraincomp1        = settings.raincomp1;
                cumulus.NOAAraincomp2        = settings.raincomp2;
                cumulus.NOAAraincomp3        = settings.raincomp3;

                // normal mean temps
                cumulus.NOAATempNorms[1]  = settings.normalmeantemps.jan;
                cumulus.NOAATempNorms[2]  = settings.normalmeantemps.feb;
                cumulus.NOAATempNorms[3]  = settings.normalmeantemps.mar;
                cumulus.NOAATempNorms[4]  = settings.normalmeantemps.apr;
                cumulus.NOAATempNorms[5]  = settings.normalmeantemps.may;
                cumulus.NOAATempNorms[6]  = settings.normalmeantemps.jun;
                cumulus.NOAATempNorms[7]  = settings.normalmeantemps.jul;
                cumulus.NOAATempNorms[8]  = settings.normalmeantemps.aug;
                cumulus.NOAATempNorms[9]  = settings.normalmeantemps.sep;
                cumulus.NOAATempNorms[10] = settings.normalmeantemps.oct;
                cumulus.NOAATempNorms[11] = settings.normalmeantemps.nov;
                cumulus.NOAATempNorms[12] = settings.normalmeantemps.dec;

                // normal rain
                cumulus.NOAARainNorms[1]  = settings.normalrain.jan;
                cumulus.NOAARainNorms[2]  = settings.normalrain.feb;
                cumulus.NOAARainNorms[3]  = settings.normalrain.mar;
                cumulus.NOAARainNorms[4]  = settings.normalrain.apr;
                cumulus.NOAARainNorms[5]  = settings.normalrain.may;
                cumulus.NOAARainNorms[6]  = settings.normalrain.jun;
                cumulus.NOAARainNorms[6]  = settings.normalrain.jul;
                cumulus.NOAARainNorms[8]  = settings.normalrain.aug;
                cumulus.NOAARainNorms[9]  = settings.normalrain.sep;
                cumulus.NOAARainNorms[10] = settings.normalrain.oct;
                cumulus.NOAARainNorms[11] = settings.normalrain.nov;
                cumulus.NOAARainNorms[12] = settings.normalrain.dec;

                // Save the settings
                cumulus.WriteIniFile();

                context.Response.StatusCode = 200;
            }
            catch (Exception ex)
            {
                cumulus.LogMessage(ex.Message);
                context.Response.StatusCode = 500;
                return(ex.Message);
            }
            return("success");
        }
예제 #26
0
        internal FOStation(Cumulus cumulus) : base(cumulus)
        {
            cumulus.Manufacturer = cumulus.EW;
            var data = new byte[32];

            tmrDataRead = new Timer();

            calculaterainrate = true;

            hasSolar = cumulus.StationType == StationTypes.FineOffsetSolar;

            if (hasSolar)
            {
                FOentrysize       = 0x14;
                FOMaxAddr         = 0xFFEC;
                maxHistoryEntries = 3264;
            }
            else
            {
                FOentrysize       = 0x10;
                FOMaxAddr         = 0xFFF0;
                maxHistoryEntries = 4080;
            }

            devicelist = DeviceList.Local;

            int VID = (cumulus.VendorID < 0 ? defaultVID : cumulus.VendorID);
            int PID = (cumulus.ProductID < 0 ? defaultPID : cumulus.ProductID);

            cumulus.LogMessage("Looking for Fine Offset station, VendorID=0x" + VID.ToString("X4") + " ProductID=0x" + PID.ToString("X4"));
            Console.WriteLine("Looking for Fine Offset station, VendorID=0x" + VID.ToString("X4") + " ProductID=0x" + PID.ToString("X4"));

            hidDevice = devicelist.GetHidDeviceOrNull(vendorID: VID, productID: PID);

            if (hidDevice != null)
            {
                cumulus.LogMessage("Fine Offset station found");
                Console.WriteLine("Fine Offset station found");

                if (hidDevice.TryOpen(out stream))
                {
                    cumulus.LogMessage("Stream opened");
                    Console.WriteLine("Connected to station");
                    // Get the block of data containing the abs and rel pressures
                    cumulus.LogMessage("Reading pressure offset");
                    ReadAddress(0x20, data);
                    double relpressure = ((data[1] * 256) + data[0]) / 10.0f;
                    double abspressure = ((data[3] * 256) + data[2]) / 10.0f;
                    pressureOffset = relpressure - abspressure;
                    cumulus.LogMessage("Rel pressure = " + relpressure);
                    cumulus.LogMessage("Abs pressure = " + abspressure);
                    cumulus.LogMessage("Offset       = " + pressureOffset);

                    // Read the data from the logger
                    startReadingHistoryData();
                }
                else
                {
                    cumulus.LogMessage("Stream open failed");
                    Console.WriteLine("Unable to connect to station");
                }
            }
            else
            {
                cumulus.LogMessage("Fine Offset station not found");
                Console.WriteLine("Fine Offset station not found");
            }
        }
예제 #27
0
        //public string UpdateInternetConfig(HttpListenerContext context)
        public string UpdateInternetConfig(IHttpContext context)
        {
            try
            {
                var data = new StreamReader(context.Request.InputStream).ReadToEnd();

                // Start at char 5 to skip the "json:" prefix
                var json = WebUtility.UrlDecode(data.Substring(5));

                // de-serialize it to the settings structure
                //JsonInternetSettingsData settings = new JavaScriptSerializer().Deserialize<JsonInternetSettingsData>(json);
                var settings = JSON.ToObject <JsonInternetSettingsData>(json);
                // process the settings
                cumulus.LogMessage("Updating internet settings");

                // website settings
                cumulus.ftp_directory = settings.website.directory ?? string.Empty;
                cumulus.ForumURL      = settings.website.forumurl ?? string.Empty;
                cumulus.ftp_port      = settings.website.ftpport;
                cumulus.ftp_host      = settings.website.hostname ?? string.Empty;
                cumulus.ftp_password  = settings.website.password ?? string.Empty;
                cumulus.ftp_user      = settings.website.username ?? string.Empty;
                cumulus.WebcamURL     = settings.website.webcamurl ?? string.Empty;

                // web settings
                cumulus.ActiveFTPMode         = settings.websettings.activeftp;
                cumulus.Sslftp                = settings.websettings.sslftp;
                cumulus.WebAutoUpdate         = settings.websettings.autoupdate;
                cumulus.RealtimeEnabled       = settings.websettings.enablerealtime;
                cumulus.RealtimeFTPEnabled    = settings.websettings.enablerealtimeftp;
                cumulus.RealtimeTxtFTP        = settings.websettings.realtimetxtftp;
                cumulus.RealtimeGaugesTxtFTP  = settings.websettings.realtimegaugestxtftp;
                cumulus.RealtimeInterval      = settings.websettings.realtimeinterval * 1000;
                cumulus.DeleteBeforeUpload    = settings.websettings.ftpdelete;
                cumulus.UpdateInterval        = settings.websettings.ftpinterval;
                cumulus.FTPRename             = settings.websettings.ftprename;
                cumulus.IncludeStandardFiles  = settings.websettings.includestdfiles;
                cumulus.IncludeGraphDataFiles = settings.websettings.includegraphdatafiles;
                cumulus.UTF8encode            = settings.websettings.utf8encode;
                if (settings.websettings.ftplogging != cumulus.FTPlogging)
                {
                    cumulus.FTPlogging = settings.websettings.ftplogging;
                    cumulus.SetFtpLogging(cumulus.FTPlogging);
                }

                // external programs
                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;

                // twitter
                cumulus.TwitterEnabled      = settings.twitter.enabled;
                cumulus.TwitterInterval     = settings.twitter.interval;
                cumulus.TwitterPW           = settings.twitter.password ?? string.Empty;
                cumulus.TwitterSendLocation = settings.twitter.sendlocation;
                cumulus.Twitteruser         = settings.twitter.user ?? string.Empty;

                cumulus.SynchronisedTwitterUpdate = (60 % cumulus.TwitterInterval == 0);

                // wunderground
                cumulus.WundCatchUp          = settings.wunderground.catchup;
                cumulus.WundEnabled          = settings.wunderground.enabled;
                cumulus.SendIndoorToWund     = settings.wunderground.includeindoor;
                cumulus.SendSRToWund         = settings.wunderground.includesolar;
                cumulus.SendUVToWund         = settings.wunderground.includeuv;
                cumulus.WundInterval         = settings.wunderground.interval;
                cumulus.WundPW               = settings.wunderground.password ?? string.Empty;
                cumulus.WundRapidFireEnabled = settings.wunderground.rapidfire;
                cumulus.WundSendAverage      = settings.wunderground.sendavgwind;
                cumulus.WundID               = settings.wunderground.stationid ?? string.Empty;

                cumulus.SynchronisedWUUpdate = (!cumulus.WundRapidFireEnabled) && (60 % cumulus.WundInterval == 0);

                // Awekas
                cumulus.AwekasEnabled        = settings.awekas.enabled;
                cumulus.AwekasInterval       = settings.awekas.interval;
                cumulus.AwekasLang           = settings.awekas.lang;
                cumulus.AwekasPW             = settings.awekas.password ?? string.Empty;
                cumulus.AwekasUser           = settings.awekas.user ?? string.Empty;
                cumulus.SendSolarToAwekas    = settings.awekas.includesolar;
                cumulus.SendUVToAwekas       = settings.awekas.includeuv;
                cumulus.SendSoilTempToAwekas = settings.awekas.includesoiltemp;

                cumulus.SynchronisedAwekasUpdate = (60 % cumulus.AwekasInterval == 0);

                // WeatherCloud
                cumulus.WCloudWid         = settings.weathercloud.wid ?? string.Empty;
                cumulus.WCloudKey         = settings.weathercloud.key ?? string.Empty;
                cumulus.WCloudEnabled     = settings.weathercloud.enabled;
                cumulus.SendSolarToWCloud = settings.weathercloud.includesolar;
                cumulus.SendUVToWCloud    = settings.weathercloud.includeuv;

                cumulus.SynchronisedWCloudUpdate = (60 % cumulus.WCloudInterval == 0);

                // PWS weather
                cumulus.PWSCatchUp  = settings.pwsweather.catchup;
                cumulus.PWSEnabled  = settings.pwsweather.enabled;
                cumulus.PWSInterval = settings.pwsweather.interval;
                cumulus.SendSRToPWS = settings.pwsweather.includesolar;
                cumulus.SendUVToPWS = settings.pwsweather.includeuv;
                cumulus.PWSPW       = settings.pwsweather.password ?? string.Empty;
                cumulus.PWSID       = settings.pwsweather.stationid ?? string.Empty;

                cumulus.SynchronisedPWSUpdate = (60 % cumulus.PWSInterval == 0);

                // WOW
                cumulus.WOWCatchUp  = settings.wow.catchup;
                cumulus.WOWEnabled  = settings.wow.enabled;
                cumulus.SendSRToWOW = settings.wow.includesolar;
                cumulus.SendUVToWOW = settings.wow.includeuv;
                cumulus.WOWInterval = settings.wow.interval;
                cumulus.WOWPW       = settings.wow.password ?? string.Empty;;
                cumulus.WOWID       = settings.wow.stationid ?? string.Empty;;

                cumulus.SynchronisedWOWUpdate = (60 % cumulus.WOWInterval == 0);

                // Weatherbug
                cumulus.WeatherbugCatchUp  = settings.weatherbug.catchup;
                cumulus.WeatherbugEnabled  = settings.weatherbug.enabled;
                cumulus.SendSRToWeatherbug = settings.weatherbug.includesolar;
                cumulus.SendUVToWeatherbug = settings.weatherbug.includeuv;
                cumulus.WeatherbugInterval = settings.weatherbug.interval;
                cumulus.WeatherbugNumber   = settings.weatherbug.number ?? string.Empty;;
                cumulus.WeatherbugPW       = settings.weatherbug.password ?? string.Empty;;
                cumulus.WeatherbugID       = settings.weatherbug.publisherid ?? string.Empty;;

                cumulus.SynchronisedWBUpdate = (60 % cumulus.WeatherbugInterval == 0);

                // CWOP
                cumulus.APRSenabled  = settings.cwop.enabled;
                cumulus.APRSID       = settings.cwop.id ?? string.Empty;;
                cumulus.APRSinterval = settings.cwop.interval;
                cumulus.SendSRToAPRS = settings.cwop.includesolar;
                cumulus.APRSpass     = settings.cwop.password ?? string.Empty;;
                cumulus.APRSport     = settings.cwop.port;
                cumulus.APRSserver   = settings.cwop.server ?? string.Empty;;

                cumulus.SynchronisedAPRSUpdate = (60 % cumulus.APRSinterval == 0);

                // HTTP proxy
                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;

                // Custom HTTP
                // custom seconds
                cumulus.CustomHttpSecondsString         = settings.customhttp.customseconds.url ?? string.Empty;
                cumulus.CustomHttpSecondsEnabled        = settings.customhttp.customseconds.enabled;
                cumulus.CustomHttpSecondsInterval       = settings.customhttp.customseconds.interval;
                cumulus.CustomHttpSecondsTimer.Interval = cumulus.CustomHttpSecondsInterval * 1000;
                cumulus.CustomHttpSecondsTimer.Enabled  = cumulus.CustomHttpSecondsEnabled;
                // custom minutes
                cumulus.CustomHttpMinutesString        = settings.customhttp.customminutes.url ?? string.Empty;
                cumulus.CustomHttpMinutesEnabled       = settings.customhttp.customminutes.enabled;
                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 rollover
                cumulus.CustomHttpRolloverString  = settings.customhttp.customrollover.url ?? string.Empty;
                cumulus.CustomHttpRolloverEnabled = settings.customhttp.customrollover.enabled;

                // Save the settings
                cumulus.WriteIniFile();

                cumulus.SetUpHttpProxy();
                //cumulus.SetFtpLogging(cumulus.FTPlogging);

                context.Response.StatusCode = 200;
            }
            catch (Exception ex)
            {
                cumulus.LogMessage(ex.Message);
                context.Response.StatusCode = 500;
                return(ex.Message);
            }
            return("success");
        }
예제 #28
0
        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);
        }
예제 #29
0
        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);
        }
예제 #30
0
        //public string UpdateStationConfig(HttpListenerContext context)
        public string UpdateStationConfig(IHttpContext context)
        {
            var ErrorMsg = "";

            context.Response.StatusCode = 200;
            // get the response
            try
            {
                cumulus.LogMessage("Updating station settings");

                var data = new StreamReader(context.Request.InputStream).ReadToEnd();

                // Start at char 5 to skip the "json:" prefix
                var json = WebUtility.UrlDecode(data.Substring(5));

                // de-serialize it to the settings structure
                var settings = JsonConvert.DeserializeObject <JsonStationSettingsData>(json);
                // process the settings

                // Graph Config
                try
                {
                    cumulus.GraphHours = settings.Graphs.graphhours;
                    cumulus.GraphDays  = settings.Graphs.graphdays;
                    cumulus.GraphOptions.TempVisible      = settings.Graphs.graphTempVis;
                    cumulus.GraphOptions.InTempVisible    = settings.Graphs.graphInTempVis;
                    cumulus.GraphOptions.HIVisible        = settings.Graphs.graphHeatIndexVis;
                    cumulus.GraphOptions.DPVisible        = settings.Graphs.graphDewPointVis;
                    cumulus.GraphOptions.WCVisible        = settings.Graphs.graphWindChillVis;
                    cumulus.GraphOptions.AppTempVisible   = settings.Graphs.graphAppTempVis;
                    cumulus.GraphOptions.FeelsLikeVisible = settings.Graphs.graphFeelsLikeVis;
                    cumulus.GraphOptions.HumidexVisible   = settings.Graphs.graphHumidexVis;
                    cumulus.GraphOptions.OutHumVisible    = settings.Graphs.graphHumVis;
                    cumulus.GraphOptions.InHumVisible     = settings.Graphs.graphInHumVis;
                    cumulus.GraphOptions.UVVisible        = settings.Graphs.graphUvVis;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Graph hours: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // Annual Rainfall
                try
                {
                    cumulus.RainSeasonStart = settings.AnnualRainfall.rainseasonstart;
                    cumulus.YTDrain         = settings.AnnualRainfall.ytdamount;
                    cumulus.YTDrainyear     = settings.AnnualRainfall.ytdyear;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Rainfall settings: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // Solar
                try
                {
                    cumulus.SolarMinimum   = settings.Solar.solarmin;
                    cumulus.RStransfactor  = settings.Solar.transfactor;
                    cumulus.SunThreshold   = settings.Solar.sunthreshold;
                    cumulus.UseBlakeLarsen = settings.Solar.useblakelarsen;
                    cumulus.SolarCalc      = settings.Solar.solarcalc;
                    cumulus.BrasTurbidity  = settings.Solar.turbidity;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Solar settings: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // Forecast
                try
                {
                    cumulus.FChighpress        = settings.Forecast.highpressureextreme;
                    cumulus.FClowpress         = settings.Forecast.lowpressureextreme;
                    cumulus.HourlyForecast     = settings.Forecast.updatehourly;
                    cumulus.UseCumulusForecast = settings.Forecast.usecumulusforecast;
                    cumulus.FCpressinMB        = (settings.Forecast.pressureunit == "mb/hPa");
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Forecast 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.degrees + (settings.Location.Latitude.minutes / 60.0) + (settings.Location.Latitude.seconds / 3600.0);
                    if (settings.Location.Latitude.hemisphere == "South")
                    {
                        cumulus.Latitude = -cumulus.Latitude;
                    }

                    cumulus.LatTxt = String.Format("{0}&nbsp;{1:D2}&deg;&nbsp;{2:D2}&#39;&nbsp;{3:D2}&quot;", settings.Location.Latitude.hemisphere[0], settings.Location.Latitude.degrees, settings.Location.Latitude.minutes,
                                                   settings.Location.Latitude.seconds);

                    cumulus.Longitude = settings.Location.Longitude.degrees + (settings.Location.Longitude.minutes / 60.0) + (settings.Location.Longitude.seconds / 3600.0);
                    if (settings.Location.Longitude.hemisphere == "West")
                    {
                        cumulus.Longitude = -cumulus.Longitude;
                    }

                    cumulus.LonTxt = String.Format("{0}&nbsp;{1:D2}&deg;&nbsp;{2:D2}&#39;&nbsp;{3:D2}&quot;", settings.Location.Longitude.hemisphere[0], settings.Location.Longitude.degrees, settings.Location.Longitude.minutes,
                                                   settings.Location.Longitude.seconds);
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Location settings: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // Options
                try
                {
                    cumulus.UseZeroBearing           = settings.Options.usezerobearing;
                    cumulus.UseWind10MinAve          = settings.Options.calcwindaverage;
                    cumulus.UseSpeedForAvgCalc       = settings.Options.usespeedforavg;
                    cumulus.Humidity98Fix            = settings.Options.use100for98hum;
                    cumulus.CalculatedDP             = settings.Options.calculatedewpoint;
                    cumulus.CalculatedWC             = settings.Options.calculatewindchill;
                    cumulus.SyncTime                 = settings.Options.syncstationclock;
                    cumulus.UseCumulusPresstrendstr  = settings.Options.cumuluspresstrendnames;
                    cumulus.ForceVPBarUpdate         = settings.Options.vp1minbarupdate;
                    cumulus.LogExtraSensors          = settings.Options.extrasensors;
                    cumulus.WS2300IgnoreStationClock = settings.Options.ignorelacrosseclock;
                    cumulus.RoundWindSpeed           = settings.Options.roundwindspeeds;
                    cumulus.SyncFOReads              = settings.Options.synchroniseforeads;
                    cumulus.logging                 = settings.Options.debuglogging;
                    cumulus.DataLogging             = settings.Options.datalogging;
                    cumulus.WarnMultiple            = settings.Options.stopsecondinstance;
                    cumulus.DavisReadReceptionStats = settings.Options.readreceptionstats;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Options settings: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // Log rollover
                try
                {
                    if (settings.logrollover.time == "9am")
                    {
                        cumulus.RolloverHour = 9;
                    }
                    else
                    {
                        cumulus.RolloverHour = 0;
                    }

                    cumulus.Use10amInSummer = settings.logrollover.summer10am;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Log rollover settings: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // WLL
                try
                {
                    cumulus.WLLAutoUpdateIpAddress = settings.daviswll.network.autoDiscover;
                    cumulus.WllApiKey    = settings.daviswll.api.apiKey;
                    cumulus.WllApiSecret = settings.daviswll.api.apiSecret;
                    cumulus.WllStationId = settings.daviswll.api.apiStationId == "-1" ? "" : settings.daviswll.api.apiStationId;

                    cumulus.WllPrimaryRain    = settings.daviswll.primary.rain;
                    cumulus.WllPrimarySolar   = settings.daviswll.primary.solar;
                    cumulus.WllPrimaryTempHum = settings.daviswll.primary.temphum;
                    cumulus.WllPrimaryUV      = settings.daviswll.primary.uv;
                    cumulus.WllPrimaryWind    = settings.daviswll.primary.wind;

                    cumulus.WllExtraLeafTx1  = settings.daviswll.soilLeaf.extraLeaf.leafTx1;
                    cumulus.WllExtraLeafTx2  = settings.daviswll.soilLeaf.extraLeaf.leafTx2;
                    cumulus.WllExtraLeafIdx1 = settings.daviswll.soilLeaf.extraLeaf.leafIdx1;
                    cumulus.WllExtraLeafIdx2 = settings.daviswll.soilLeaf.extraLeaf.leafIdx2;

                    cumulus.WllExtraSoilMoistureIdx1 = settings.daviswll.soilLeaf.extraSoilMoist.soilMoistIdx1;
                    cumulus.WllExtraSoilMoistureIdx2 = settings.daviswll.soilLeaf.extraSoilMoist.soilMoistIdx2;
                    cumulus.WllExtraSoilMoistureIdx3 = settings.daviswll.soilLeaf.extraSoilMoist.soilMoistIdx3;
                    cumulus.WllExtraSoilMoistureIdx4 = settings.daviswll.soilLeaf.extraSoilMoist.soilMoistIdx4;
                    cumulus.WllExtraSoilMoistureTx1  = settings.daviswll.soilLeaf.extraSoilMoist.soilMoistTx1;
                    cumulus.WllExtraSoilMoistureTx2  = settings.daviswll.soilLeaf.extraSoilMoist.soilMoistTx2;
                    cumulus.WllExtraSoilMoistureTx3  = settings.daviswll.soilLeaf.extraSoilMoist.soilMoistTx3;
                    cumulus.WllExtraSoilMoistureTx4  = settings.daviswll.soilLeaf.extraSoilMoist.soilMoistTx4;

                    cumulus.WllExtraSoilTempIdx1 = settings.daviswll.soilLeaf.extraSoilTemp.soilTempIdx1;
                    cumulus.WllExtraSoilTempIdx2 = settings.daviswll.soilLeaf.extraSoilTemp.soilTempIdx2;
                    cumulus.WllExtraSoilTempIdx3 = settings.daviswll.soilLeaf.extraSoilTemp.soilTempIdx3;
                    cumulus.WllExtraSoilTempIdx4 = settings.daviswll.soilLeaf.extraSoilTemp.soilTempIdx4;
                    cumulus.WllExtraSoilTempTx1  = settings.daviswll.soilLeaf.extraSoilTemp.soilTempTx1;
                    cumulus.WllExtraSoilTempTx2  = settings.daviswll.soilLeaf.extraSoilTemp.soilTempTx2;
                    cumulus.WllExtraSoilTempTx3  = settings.daviswll.soilLeaf.extraSoilTemp.soilTempTx3;
                    cumulus.WllExtraSoilTempTx4  = settings.daviswll.soilLeaf.extraSoilTemp.soilTempTx4;

                    cumulus.WllExtraTempTx[0] = settings.daviswll.extraTemp.extraTempTx1;
                    cumulus.WllExtraTempTx[1] = settings.daviswll.extraTemp.extraTempTx2;
                    cumulus.WllExtraTempTx[2] = settings.daviswll.extraTemp.extraTempTx3;
                    cumulus.WllExtraTempTx[3] = settings.daviswll.extraTemp.extraTempTx4;
                    cumulus.WllExtraTempTx[4] = settings.daviswll.extraTemp.extraTempTx5;
                    cumulus.WllExtraTempTx[5] = settings.daviswll.extraTemp.extraTempTx6;
                    cumulus.WllExtraTempTx[6] = settings.daviswll.extraTemp.extraTempTx7;
                    cumulus.WllExtraTempTx[7] = settings.daviswll.extraTemp.extraTempTx8;

                    cumulus.WllExtraHumTx[0] = settings.daviswll.extraTemp.extraHumTx1;
                    cumulus.WllExtraHumTx[1] = settings.daviswll.extraTemp.extraHumTx2;
                    cumulus.WllExtraHumTx[2] = settings.daviswll.extraTemp.extraHumTx3;
                    cumulus.WllExtraHumTx[3] = settings.daviswll.extraTemp.extraHumTx4;
                    cumulus.WllExtraHumTx[4] = settings.daviswll.extraTemp.extraHumTx5;
                    cumulus.WllExtraHumTx[5] = settings.daviswll.extraTemp.extraHumTx6;
                    cumulus.WllExtraHumTx[6] = settings.daviswll.extraTemp.extraHumTx7;
                    cumulus.WllExtraHumTx[7] = settings.daviswll.extraTemp.extraHumTx8;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing WLL settings: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // log interval
                try
                {
                    cumulus.DataLogInterval = settings.loginterval;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Log interval setting: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }


                // com port
                try
                {
                    cumulus.ComportName = settings.comportname ?? string.Empty;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing COM port setting: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // Davis connection details
                try
                {
                    cumulus.VP2ConnectionType             = settings.davisconn.conntype;
                    cumulus.VP2IPAddr                     = settings.davisconn.tcpsettings.ipaddress ?? string.Empty;
                    cumulus.VP2TCPPort                    = settings.davisconn.tcpsettings.tcpport;
                    cumulus.VP2PeriodicDisconnectInterval = settings.davisconn.tcpsettings.disconperiod;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Davis settings: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // GW1000 connection details
                try
                {
                    cumulus.Gw1000IpAddress           = settings.gw1000.ipaddress;
                    cumulus.Gw1000AutoUpdateIpAddress = settings.gw1000.autoDiscover;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing GW1000 settings: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // Units
                try
                {
                    cumulus.WindUnit  = settings.units.wind;
                    cumulus.PressUnit = settings.units.pressure;
                    cumulus.TempUnit  = settings.units.temp;
                    cumulus.RainUnit  = settings.units.rain;
                    cumulus.SetupUnitText();
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Units settings: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // Station type
                try
                {
                    if (cumulus.StationType != settings.stationtype)
                    {
                        cumulus.LogMessage("Station type changed, restart required");
                        cumulus.LogConsoleMessage("*** Station type changed, restart required ***");
                    }
                    cumulus.StationType = settings.stationtype;
                }
                catch (Exception ex)
                {
                    var msg = "Error processing Station Type setting: " + ex.Message;
                    cumulus.LogMessage(msg);
                    ErrorMsg += msg + "\n\n";
                    context.Response.StatusCode = 500;
                }

                // Save the settings
                cumulus.WriteIniFile();
            }
            catch (Exception ex)
            {
                cumulus.LogMessage(ex.Message);
                context.Response.StatusCode = 500;
                return(ex.Message);
            }

            if (context.Response.StatusCode == 200)
            {
                return("success");
            }
            else
            {
                return(ErrorMsg);
            }
        }