Пример #1
0
        /// <summary>
        /// Executes 'Set Device Name' command.
        /// </summary>
        private string SetDeviceName(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                string name = context.Query.Get("name");
                if (String.IsNullOrWhiteSpace(name))
                {
                    throw new Exception("Parameter 'name' is missing or invalid");
                }

                _config.DeviceName = name;
                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    writer.WriteStartObject("output");
                    writer.WritePropertyValue("success", 1);
                    writer.WritePropertyValue("code", 0);
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
Пример #2
0
            public string ToJson()
            {
                StringBuilder sb = new StringBuilder();

                using (SimpleJsonWriter writer = new SimpleJsonWriter(sb, true))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyValue("serial", Serial);
                    writer.WritePropertyValue("name", Name);
                    writer.WritePropertyValue("version", Version);
                    writer.WritePropertyValue("httpPort", HttpPort);
                    writer.WritePropertyValue("runningSecs", (int)RunningTime.TotalSeconds);
                    writer.WritePropertyValue("serviceState", ServiceState);
                    writer.WriteStartArray("interfaces");
                    foreach (Interface i in Interfaces)
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyValue("name", i.Name);
                        writer.WritePropertyValue("physical", i.PhysicalAddress);
                        writer.WritePropertyValue("internet", i.InternetAddress);
                        writer.WriteEndObject();
                    }
                    writer.WriteEndArray();
                    writer.WriteEndObject();
                }
                return(sb.ToString());
            }
Пример #3
0
        /// <summary>
        /// Executes 'Read' command.
        /// </summary>
        private string Read(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                string input1 = _gpio.GetBank(BankType.Input1);
                string input2 = _gpio.GetBank(BankType.Input2);
                string output = _gpio.GetBank(BankType.Output);

                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    writer.WriteStartObject("output");
                    writer.WritePropertyValue("success", 1);
                    writer.WritePropertyValue("input1", input1);
                    writer.WritePropertyValue("input2", input2);
                    writer.WritePropertyValue("output", output);
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
Пример #4
0
        /// <summary>
        /// Executes 'Write' command.
        /// </summary>
        private string Write(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                string output = context.Query.Get("output");
                if (String.IsNullOrWhiteSpace(output))
                {
                    throw new Exception("Parameter 'output' missing or invalid");
                }
                _gpio.SetBank(BankType.Output, output);

                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    writer.WriteStartObject("output");
                    writer.WritePropertyValue("success", 1);
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
Пример #5
0
        /// <summary>
        /// Saves entries file.
        /// </summary>
        private static void WriteEntriesFile()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                using (SimpleJsonWriter writer = new SimpleJsonWriter(sb))
                {
                    writer.WriteStartObject();
                    writer.WriteStartArray("entries");
                    foreach (Entry entry in _entries)
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyValue("ip", entry.IP);
                        writer.WritePropertyValue("host", entry.Host);
                        writer.WritePropertyValue("mac", entry.Mac);
                        writer.WriteEndObject();
                    }
                    writer.WriteEndArray();
                    writer.WriteEndObject();
                }

                Console.WriteLine($"Writing file {EntriesFile}");
                File.WriteAllText(EntriesFile, sb.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception($"Unable to save file {EntriesFile}", ex);
            }
        }
Пример #6
0
        /// <summary>
        /// Writes fatal error response as JSON if command execution failed completely.
        /// </summary>
        protected string WriteFatalResponse(SimpleHttpContext context, Exception ex)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    writer.WriteStartObject("output");
                    writer.WritePropertyValue("success", 0);
                    writer.WritePropertyValue("code", 1);
                    writer.WritePropertyValue("message", ex.Message ?? "A fatal error occurred");
                    writer.WriteEndObject();
                    WriteErrorsObject(writer, new List <Exception>()
                    {
                        ex
                    });
                    writer.WriteEndObject();
                }
            }
            catch (Exception exx)
            {
                _errorHandler?.LogError(exx);
            }
            return(json.ToString());
        }
Пример #7
0
        /// <summary>
        /// Writes runtime statistics.
        /// </summary>
        public void WriteRuntimeStatistics(SimpleJsonWriter writer)
        {
            try
            {
                var          now    = DateTime.Now;
                var          state  = ServiceStateType.Up;
                var          health = ServiceHealthType.Good;
                List <Alert> alerts = null;
                lock (_lock)
                {
                    state = _state;
                    foreach (Alert a in _alerts)
                    {
                        if (a.Type > health)
                        {
                            health = a.Type;
                        }
                    }
                    if (health > ServiceHealthType.Good)
                    {
                        alerts = new List <Alert>();
                        foreach (Alert a in _alerts)
                        {
                            alerts.Add(a);
                        }
                    }
                }

                writer.WriteStartObject("serviceState");
                writer.WritePropertyValue("state", ((Int32)state) + "-" + state.ToString());
                writer.WritePropertyValue("health", ((Int32)health) + "-" + health.ToString());
                if (alerts != null)
                {
                    writer.WriteStartArray("alerts");
                    foreach (Alert a in alerts)
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyValue("type", ((Int32)a.Type) + "-" + a.Type.ToString());
                        writer.WritePropertyValue("message", a.Message ?? "");
                        writer.WritePropertyValue("time", a.Time.ToString());
                        writer.WritePropertyValue("expiration", a.Expiration == DateTime.MaxValue ? "max" : ((Int32)(((TimeSpan)(a.Expiration - now)).TotalMinutes)).ToString());
                        writer.WriteEndObject();
                    }
                    writer.WriteEndArray();
                }
                writer.WriteEndObject();
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
            }
        }
Пример #8
0
        /// <summary>
        /// Executes 'GetStats' command.
        /// </summary>
        private string GetStats(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    foreach (IStatsWriter stats in _statsWriters)
                    {
                        stats.WriteRuntimeStatistics(writer);
                    }
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
Пример #9
0
        /// <summary>
        /// Writes runtime statistics.
        /// </summary>
        public void WriteRuntimeStatistics(SimpleJsonWriter writer)
        {
            try
            {
                List <ErrorCacheItem> errorStats = GetErrorReport();

                writer.WriteStartArray("errorStats");
                foreach (ErrorCacheItem errorItem in errorStats)
                {
                    writer.WriteStartObject();
                    writer.WritePropertyValue("count", errorItem.Count);
                    writer.WritePropertyValue("cpm", Math.Round(errorItem.CountPerMinute, 1));
                    writer.WritePropertyValue("type", errorItem.Error.Type ?? "");
                    writer.WritePropertyValue("message", errorItem.Error.Message ?? "");
                    writer.WritePropertyValue("stackTrace", errorItem.Error.StackTrace ?? "");
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
            }
            catch (Exception ex)
            {
                if (_errorHandler != null)
                {
                    _errorHandler.LogError(ex);
                }
            }
        }
Пример #10
0
        /// <summary>
        /// Writes runtime stats.
        /// </summary>
        public void WriteRuntimeStatistics(SimpleJsonWriter writer)
        {
            if (!_config.IsLinux)
            {
                return;
            }

            writer.WriteStartObject("pi");
            writer.WritePropertyValue("boardModel", Pi.Info.BoardModel.ToString());
            writer.WritePropertyValue("boardRevision", Pi.Info.BoardRevision);
            writer.WritePropertyValue("cpuArchitecture", Pi.Info.CpuArchitecture);
            writer.WritePropertyValue("cpuImplementer", Pi.Info.CpuImplementer);
            writer.WritePropertyValue("cpuPart", Pi.Info.CpuPart);
            writer.WritePropertyValue("cpuRevision", Pi.Info.CpuRevision);
            writer.WritePropertyValue("cpuVariant", Pi.Info.CpuVariant);
            writer.WritePropertyValue("features", String.Join(", ", Pi.Info.Features));
            writer.WritePropertyValue("hardware", Pi.Info.Hardware);
            writer.WritePropertyValue("installedRam", Pi.Info.InstalledRam);
            writer.WritePropertyValue("isLittleEndian", Pi.Info.IsLittleEndian ? 1 : 0);
            writer.WritePropertyValue("libraryVersion", Pi.Info.LibraryVersion?.ToString());
            writer.WritePropertyValue("manufacturer", Pi.Info.Manufacturer.ToString());
            writer.WritePropertyValue("memorySize", Pi.Info.MemorySize.ToString());
            writer.WritePropertyValue("modelName", Pi.Info.ModelName);
            writer.WritePropertyValue("operatingSystem", Pi.Info.OperatingSystem?.ToString());
            writer.WritePropertyValue("processorModel", Pi.Info.ProcessorModel.ToString());
            writer.WritePropertyValue("processorModel", Pi.Info.ProcessorModel.ToString());
            writer.WritePropertyValue("raspberryPiVersion", Pi.Info.RaspberryPiVersion.ToString());
            writer.WritePropertyValue("revision", Pi.Info.Revision);
            writer.WritePropertyValue("revisionNumber", Pi.Info.RevisionNumber);
            writer.WritePropertyValue("serial", Pi.Info.Serial);
            writer.WritePropertyValue("uptimeSecs", Pi.Info.Uptime);
            writer.WriteEndObject();
        }
Пример #11
0
        /// <summary>
        /// Executes 'Ping' command.
        /// </summary>
        private string Ping(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                using (var writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    _statsWriters
                    .Where(sw => sw is ServiceState)
                    .FirstOrDefault()?
                    .WriteRuntimeStatistics(writer);
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
Пример #12
0
 /// <summary>
 /// Writes the 'device' object for all commands.
 /// </summary>
 public void WriteDeviceObject(SimpleJsonWriter writer)
 {
     writer.WriteStartObject("device");
     writer.WritePropertyValue("serial", _config.DeviceSerial ?? "");
     writer.WritePropertyValue("name", _config.DeviceName ?? "");
     writer.WritePropertyValue("interfaceName", _config.PrimaryInterface?.Name ?? "");
     writer.WritePropertyValue("macAddress", _config.PrimaryInterface?.PhysicalAddress ?? "");
     writer.WritePropertyValue("ipAddress", _config.PrimaryInterface?.InternetAddress ?? "");
     writer.WritePropertyValue("os", _config.GetOS());
     writer.WriteEndObject();
 }
Пример #13
0
            public void SaveSettings()
            {
                StringBuilder sb = new StringBuilder();

                using (SimpleJsonWriter writer = new SimpleJsonWriter(sb))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyValue("deviceName", DeviceName);
                    writer.WriteEndObject();
                }
                File.WriteAllText(FilePath, sb.ToString(), Encoding.UTF8);
            }
Пример #14
0
 /// <summary>
 /// Writes the 'service' object for all commands.
 /// </summary>
 public void WriteServiceObject(SimpleJsonWriter writer, bool isStatistics = false)
 {
     writer.WriteStartObject("service");
     writer.WritePropertyValue("name", _config.ServiceName);
     writer.WritePropertyValue("version", _config.ServiceVersion);
     if (isStatistics)
     {
         writer.WritePropertyValue("now", DateTime.Now.ToString());
         writer.WritePropertyValue("runningTime", _config.RunningTime.ToShortString());
         writer.WritePropertyValue("memoryUsageMB", _config.GetMegabytesUsedByProcess());
     }
     writer.WriteEndObject();
 }
Пример #15
0
        /// <summary>
        /// Writes the 'request' object for all commands.
        /// </summary>
        public void WriteRequestObject(SimpleJsonWriter writer, SimpleHttpContext context)
        {
            IDictionary <string, string[]> qs = context.Query.GetAll();

            writer.WriteStartObject("request");
            writer.WritePropertyValue("handler", context.Handler);
            writer.WritePropertyValue("command", context.Command);
            foreach (string key in qs.Keys)
            {
                writer.WritePropertyValue(key, qs[key].Length > 0 ? qs[key][0] : null);
            }
            writer.WritePropertyValue("elapsedMS", context.Stopwatch.ElapsedMilliseconds);
            writer.WriteEndObject();
        }
Пример #16
0
 /// <summary>
 /// Writes the 'errors' object for all commands.
 /// </summary>
 public void WriteErrorsObject(SimpleJsonWriter writer, List <Exception> errors)
 {
     writer.WriteStartArray("errors");
     if ((errors != null) && (errors.Count > 0))
     {
         for (int i = 0; i < errors.Count; i++)
         {
             Exception ex = errors[i];
             if (!String.IsNullOrEmpty(ex.Message))
             {
                 writer.WriteStartObject();
                 writer.WritePropertyValue("type", ex.GetType().ToString());
                 writer.WritePropertyValue("message", CleanErrorString(ex.Message));
                 writer.WritePropertyValue("stack", CleanErrorString(ex.StackTrace ?? ""));
                 writer.WriteEndObject();
             }
         }
     }
     writer.WriteEndArray();
 }
Пример #17
0
        /// <summary>
        /// Writes runtime stats.
        /// </summary>
        public void WriteRuntimeStatistics(SimpleJsonWriter writer)
        {
            string input1, input2, output;

            _lock.EnterReadLock();
            try
            {
                input1 = BankToString(_input1);
                input2 = BankToString(_input2);
                output = BankToString(_outputRead);
            }
            finally
            {
                _lock.ExitReadLock();
            }

            writer.WriteStartObject("gpio");
            writer.WritePropertyValue("input1", input1);
            writer.WritePropertyValue("input2", input2);
            writer.WritePropertyValue("output", output);
            writer.WritePropertyValue("cps", _cps != null ? _cps.CPS.ToString("0.0") : "0.0");
            writer.WriteEndObject();
        }
Пример #18
0
        /// <summary>
        /// Writes runtime statistics.
        /// </summary>
        public void WriteRuntimeStatistics(SimpleJsonWriter writer)
        {
            try
            {
                GetSummary(
                    out List <OperationRollup> operations,
                    out List <OperationRollup> commands,
                    out List <TaskStats> runningTasks,
                    out List <TaskStats> completedTasks);

                writer.WriteStartObject("serviceStats");
                writer.WriteStartArray("operations");
                foreach (OperationRollup r in operations)
                {
                    writer.WriteStartObject();
                    writer.WritePropertyValue("name", r.Name ?? String.Empty);
                    writer.WritePropertyValue("count", r.Count);
                    writer.WritePropertyValue("elapsedAvg", Math.Round(r.ElapsedAvg, 1));
                    writer.WritePropertyValue("elapsedMin", r.ElapsedMin);
                    writer.WritePropertyValue("elapsedMax", r.ElapsedMax);
                    writer.WritePropertyValue("elapsedSum", r.ElapsedSum);
                    writer.WritePropertyValue("cps", Math.Round(r.CPS, 2));
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
                writer.WriteStartArray("commands");
                foreach (OperationRollup r in commands)
                {
                    writer.WriteStartObject();
                    writer.WritePropertyValue("name", r.Name ?? String.Empty);
                    writer.WritePropertyValue("count", r.Count);
                    writer.WritePropertyValue("elapsedAvg", Math.Round(r.ElapsedAvg, 1));
                    writer.WritePropertyValue("elapsedMin", r.ElapsedMin);
                    writer.WritePropertyValue("elapsedMax", r.ElapsedMax);
                    writer.WritePropertyValue("elapsedSum", r.ElapsedSum);
                    writer.WritePropertyValue("cps", Math.Round(r.CPS, 2));
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
                writer.WriteStartArray("completedTasks");
                foreach (TaskStats t in completedTasks)
                {
                    writer.WriteStartObject();
                    writer.WritePropertyValue("name", t.Name ?? String.Empty);
                    writer.WritePropertyValue("ips", Math.Round(t.IterationsPerSecond, 1));
                    writer.WritePropertyValue("elapsed", t.Elapsed.ToShortString());
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
                writer.WriteStartArray("runningTasks");
                foreach (TaskStats t in runningTasks)
                {
                    writer.WriteStartObject();
                    writer.WritePropertyValue("name", t.Name ?? String.Empty);
                    writer.WritePropertyValue("ips", Math.Round(t.IterationsPerSecond, 1));
                    writer.WritePropertyValue("percentComplete", Math.Round(t.PercentComplete, 1));
                    writer.WritePropertyValue("eta", t.ETA.ToShortString());
                    writer.WritePropertyValue("elapsed", t.Elapsed.ToShortString());
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
                writer.WriteEndObject();
            }
            catch (Exception ex)
            {
                if (_errorHandler != null)
                {
                    _errorHandler.LogError(ex);
                }
            }
        }