private void ProcessStats(IList <FeatureStatistics> stats)
        {
            Logger.LogDebugMessage("Creating ServerDensity payload");
            var payload = new MetricsPayload()
            {
                AgentKey = _AgentKey
            };
            bool hasData = false;

            foreach (var featureStat in stats.Where(x => x.Group == ServerDensityFeatureGroup))
            {
                hasData = true;

                var plugin = new ServerDensityPlugin(featureStat.Name);
                foreach (var reading in featureStat.Readings)
                {
                    plugin.Add(reading.Name, reading.GetValue());
                }
                payload.AddPlugin(plugin);
            }

            if (hasData)
            {
                Logger.LogDebugMessage(String.Format("Uploading {0} stats to ServerDensity", stats.Count));
                _api.Metrics.UploadPluginData(_deviceId, payload);
            }
            else
            {
                Logger.LogDebugMessage("No need to call server density");
            }
        }
        private async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
        {
            var eventHubReceiver = _eventHubClient.GetConsumerGroup(ConfigurationManager.AppSettings["ConsumerGroup"])
                                   .CreateReceiver(partition, DateTime.UtcNow);

            while (_hubContext != null && !ct.IsCancellationRequested)
            {
                try
                {
                    var eventData = await eventHubReceiver.ReceiveAsync();

                    if (eventData == null)
                    {
                        continue;
                    }

                    var data             = Encoding.UTF8.GetString(eventData.GetBytes());
                    var deviceId         = eventData.SystemProperties["iothub-connection-device-id"].ToString();
                    var fromDeviceObject = JsonConvert.DeserializeObject <MxPayload>(data);

                    var gForce = CalculateGForce(Convert.ToDouble(fromDeviceObject.AccelX),
                                                 Convert.ToDouble(fromDeviceObject.AccelY), Convert.ToDouble(fromDeviceObject.AccelZ));

                    var mgauss = CalculateSingleMGauss(fromDeviceObject.MagX, fromDeviceObject.MagY, fromDeviceObject.MagZ);

                    // We are just going to simulate a DB reading as the sound file is too large to be sent in a message
                    var decibel = 0.0;
                    if (fromDeviceObject.SoundRecorded)
                    {
                        decibel = GetRandomSpeakingDecibel(Constants.LowSpeakingDbValue, Constants.HighSpeakingDbValue);
                    }

                    var metricsPayload = new MetricsPayload
                    {
                        Id           = deviceId,
                        Gravity      = Math.Round(gForce, 3),
                        Temperature  = Math.Round(fromDeviceObject.Temperature, 2),
                        Humidity     = Math.Round(fromDeviceObject.Humidity, 2),
                        Pressure     = Math.Round(fromDeviceObject.Pressure, 2),
                        Magnetometer = mgauss,
                        Decibels     = decibel
                    };

                    var msg = JsonConvert.SerializeObject(metricsPayload);
                    Trace.TraceInformation($"Publishing message: {msg}");

                    _hubContext.Clients.All.Message(msg);
                }
                catch (Exception e)
                {
                    Trace.TraceError($"An error occurred while receiving messages: {e}");
                }
            }
        }
Exemple #3
0
        private void SendMetric(MetricType metricType, string metricName, string[] customTags, string value)
        {
            // Tags are used by datadog to allow metric aggregation across logical groups. (https://docs.datadoghq.com/tagging/)
            if (_MetricTagCache == null)
            {
                _MetricTagCache = new[] { $"env:{_Environment}", $"source:{_ApplicationName}" }
            }
            ;

            var tagsList = new List <string>();

            tagsList.AddRange(_MetricTagCache);

            if (customTags != null && customTags.Length > 0)
            {
                tagsList.AddRange(customTags);
            }

            var tags = tagsList.ToArray();

            var buffer = new MetricsPayload()
            {
                Series = new MetricData[]
                {
                    new MetricData()
                    {
                        Host       = Environment.MachineName,
                        MetricName = metricName,
                        Tags       = tags,
                        MetricType = metricType.ToString(),
                        DataPoints = new string[][]
                        {
                            new string[]
                            {
                                DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
                value
                            }
                        }
                    }
                }
            };

            if (_FullUrlCache == null)
            {
                _FullUrlCache = $"{_UrlEndpoint}?api_key={_ApiKey}";
            }

            // fire and forget task
            Task.Factory.StartNew(() => Post(_FullUrlCache, buffer));
        }