示例#1
0
        /// <summary>
        /// Processes the message.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns>
        /// The Task
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public async Task ProcessMessage(EventData data)
        {
            if (!data.Properties.ContainsKey(Constants.DeviceIdKey))
            {
                throw new Exception("Device Id is missing");
            }

            var deviceId         = data.Properties[Constants.DeviceIdKey].ToString();
            var actor            = this.GetActor(deviceId);
            var telemetryMessage = new TelemetryMessage()
            {
                Body       = data.GetBytes(),
                Properties = data.Properties,
                DeviceId   = deviceId
            };

            if (data.Properties.ContainsKey(Constants.MessageIdKey))
            {
                telemetryMessage.MessageId = data.Properties[Constants.MessageIdKey].ToString();
            }

            await actor.ProcessMessage(telemetryMessage);
        }
示例#2
0
        /// <summary>
        /// The main method to invoke TLC, with some high level configuration options set.
        /// </summary>
        /// <param name="env">The environment used in this run of TLC, for the purpose of returning outputs.</param>
        /// <param name="args">The command line arguments.</param>
        /// <param name="alwaysPrintStacktrace">"Marked" exceptions are assumed to be sufficiently descriptive, so we
        /// do not print stack traces for them to the console, and instead print these only to a log file.
        /// However, throwing unmarked exceptions is considered a bug in TLC (even if due to bad user input),
        /// so we always write . If set to true though, this executable will also print stack traces from the
        /// marked exceptions as well.</param>
        /// <returns></returns>
        internal static int MainCore(TlcEnvironment env, string args, bool alwaysPrintStacktrace)
        {
            // REVIEW: How should extra dlls, tracking, etc be handled? Should the args objects for
            // all commands derive from a common base?
            var mainHost = env.Register("Main");

            using (var telemetryPipe = mainHost.StartPipe <TelemetryMessage>("TelemetryPipe"))
                using (var ch = mainHost.Start("Main"))
                {
                    int result;
                    try
                    {
                        if (!CmdParser.TryGetFirstToken(args, out string kind, out string settings))
                        {
                            telemetryPipe.Send(TelemetryMessage.CreateCommand("ArgumentParsingFailure", args));
                            Usage();
                            return(-1);
                        }

                        var cmdDef = new SubComponent <ICommand, SignatureCommand>(kind, settings);

                        if (!ComponentCatalog.TryCreateInstance(mainHost, out ICommand cmd, cmdDef))
                        {
                            // Telemetry: Log
                            telemetryPipe.Send(TelemetryMessage.CreateCommand("UnknownCommand", settings));
                            ch.Error("Unknown command: '{0}'", kind);
                            Usage();
                            return(-1);
                        }

                        // Telemetry: Log the command and settings.
                        telemetryPipe.Send(TelemetryMessage.CreateCommand(kind.ToUpperInvariant(), settings));
                        cmd.Run();

                        result = 0;
                    }
                    catch (Exception ex)
                    {
                        var dumpFileDir = Path.Combine(
                            Path.GetTempPath(),
                            "TLC");
                        var dumpFilePath = Path.Combine(dumpFileDir,
                                                        string.Format(CultureInfo.InvariantCulture, "Error_{0:yyyyMMdd_HHmmss}_{1}.log", DateTime.UtcNow, Guid.NewGuid()));
                        bool isDumpSaved = false;
                        try
                        {
                            Directory.CreateDirectory(dumpFileDir);
                            // REVIEW: Should specify the encoding.
                            using (var sw = new StreamWriter(new FileStream(dumpFilePath, FileMode.Create, FileAccess.Write)))
                            {
                                sw.WriteLine("--- Command line args ---");
                                sw.WriteLine(args);
                                sw.WriteLine("--- Exception message ---");
                                PrintFullExceptionDetails(sw, ex);
                            }

                            isDumpSaved = true;
                        }
                        catch (Exception)
                        {
                            // Don't throw an exception if we failed to write to the dump file.
                        }

                        // Process exceptions that we understand.
                        int count = 0;
                        for (var e = ex; e != null; e = e.InnerException)
                        {
                            // Telemetry: Log the exception
                            telemetryPipe.Send(TelemetryMessage.CreateException(e));
                            if (e.IsMarked())
                            {
                                ch.Error(e.Sensitivity(), e.Message);
                                PrintExceptionData(ch, e, false);
                                count++;
                            }
                        }

                        if (count == 0)
                        {
                            // Didn't recognize any of the exceptions.
                            ch.Error(MessageSensitivity.None, "***** Unexpected failure. Please go to https://aka.ms/MLNetIssue and register the error details *****");
                            if (isDumpSaved)
                            {
                                ch.Error(MessageSensitivity.None, "***** Error log has been saved to '{0}', please register the error at https://aka.ms/MLNetIssue *****",
                                         dumpFilePath);
                            }
                        }
                        else if (isDumpSaved)
                        {
                            ch.Error(MessageSensitivity.None, "Error log has been saved to '{0}'. please register the error at https://aka.ms/MLNetIssue",
                                     dumpFilePath);
                        }

                        if (count == 0 || alwaysPrintStacktrace)
                        {
                            ch.Error(MessageSensitivity.None, "===== Begin detailed dump =====");
                            PrintFullExceptionDetails(ch, ex);
                            ch.Error(MessageSensitivity.None, "====== End detailed dump =====");
                        }

                        // Return a negative result code so AEther recognizes this as a failure.
                        result = count > 0 ? -1 : -2;
                    }
                    finally
                    {
                    }
                    telemetryPipe.Done();
                    return(result);
                }
        }
        private static async Task SimulateData(CancellationToken ct)
        {
            bool atLeastOneSensorMatchFound = false;
            var  serializer = new DataContractJsonSerializer(typeof(TelemetryMessage));

            foreach (Sensor sensor in DeviceInfo.Sensors)
            {
                if (SensorInfosByDataType.ContainsKey(sensor.DataType))
                {
                    atLeastOneSensorMatchFound = true;
                    break;
                }
            }

            if (!atLeastOneSensorMatchFound)
            {
                throw new Exception(
                          $"No preconfigured Sensor found for any of the following datatypes: {string.Join( ", ", SensorInfosByDataType.Keys )}");
            }

            Console.WriteLine();
            Console.WriteLine("Beginning to simulate data...");
            Console.WriteLine();

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }

                foreach (Sensor sensor in DeviceInfo.Sensors)
                {
                    if (!SensorInfosByDataType.TryGetValue(sensor.DataType, out SensorInfo sensorInfo))
                    {
                        continue;
                    }

                    if (sensorInfo.IsCurrentValueDifferent())
                    {
                        sensorInfo.UpdateLastValueSentWithCurrentValue();
                        var currentValue     = sensorInfo.GetCurrentValue();
                        var telemetryMessage = new TelemetryMessage()
                        {
                            SensorId       = sensor.Id,
                            SensorReading  = currentValue.ToString(),
                            EventTimestamp = DateTime.UtcNow.ToString("o"),
                            SensorType     = sensor.Type,
                            SensorDataType = sensor.DataType,
                            SpaceId        = sensor.SpaceId,
                            IoTHubDeviceId = IoTHubDeviceId
                        };

                        try
                        {
                            List <Task> tasks = new List <Task>();

                            using (var stream = new MemoryStream())
                            {
                                serializer.WriteObject(stream, telemetryMessage);
                                var     binaryMessage = stream.ToArray();
                                Message eventMessage  = new Message(binaryMessage);
                                eventMessage.Properties.Add("Sensor", "");
                                eventMessage.Properties.Add("MessageVersion", "1.0");
                                eventMessage.Properties.Add("x-ms-flighting-udf-execution-manually-enabled", "true");
                                Console.WriteLine(
                                    $"\t{DateTime.UtcNow.ToLocalTime()}> Sending message: {Encoding.ASCII.GetString( binaryMessage )}");

                                tasks.Add(TopologyDeviceClient.SendEventAsync(eventMessage));
                            }

                            await Task.WhenAll(tasks);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Error occurred in {nameof( SimulateData )}: {ex}");
                        }
                    }
                }

                await Task.Delay(int.Parse(Configuration[MessageIntervalInMilliSecondsSetting]), ct);
            }
        }
示例#4
0
        public void Telemetry()
        {
            TelemetryMessage tm = new TelemetryMessage();

            Console.WriteLine(TelemetryMessage.DefaultMachineID);
        }
示例#5
0
        private static async Task SimulateData(CancellationToken ct)
        {
            var serializer = new DataContractJsonSerializer(typeof(TelemetryMessage));

            var sensor = DeviceInfo.Sensors.FirstOrDefault(x => (x.DataType == Configuration[SensorDataTypeSetting]));

            if (sensor == null)
            {
                throw new Exception($"No preconfigured Sensor for DataType '{Configuration[SensorDataTypeSetting]}' found.");
            }

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }

                int newTemperature = _currentTemperature + _offsetModifier;

                if (newTemperature != _lastCurrentTemperatureSent)
                {
                    _lastCurrentTemperatureSent = newTemperature;
                    var telemetryMessage = new TelemetryMessage()
                    {
                        SensorId       = sensor.Id,
                        SensorReading  = newTemperature.ToString(CultureInfo.InvariantCulture),
                        EventTimestamp = DateTime.UtcNow.ToString("o"),
                        SensorType     = sensor.Type,
                        SensorDataType = sensor.DataType,
                        SpaceId        = sensor.SpaceId
                    };

                    try
                    {
                        List <Task> tasks = new List <Task>();

                        using (var stream = new MemoryStream())
                        {
                            serializer.WriteObject(stream, telemetryMessage);
                            var     binaryMessage = stream.ToArray();
                            Message eventMessage  = new Message(binaryMessage);
                            eventMessage.Properties.Add("Sensor", "");
                            eventMessage.Properties.Add("MessageVersion", "1.0");
                            eventMessage.Properties.Add("x-ms-flighting-udf-execution-manually-enabled", "true");
                            Console.WriteLine(
                                $"\t{DateTime.UtcNow.ToLocalTime()}> Sending message: {Encoding.ASCII.GetString( binaryMessage )}");

                            tasks.Add(TopologyDeviceClient.SendEventAsync(eventMessage));
                        }

                        await Task.WhenAll(tasks);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error occurred in {nameof( SimulateData )}: {ex}");
                    }
                }

                await Task.Delay(int.Parse(Configuration[MessageIntervalInMilliSecondsSetting]), ct);
            }
        }
 public void Publish(TelemetryMessage message)
 {
     _deviceDataController.PublishData(message);
 }
示例#7
0
 public bool SendTelemetry(TelemetryMessage telemetryMessage)
 {
     throw new NotImplementedException();
 }
示例#8
0
        private async Task ListenAsync()
        {
            uint headerSize = (uint)Marshal.SizeOf(typeof(MessageHeader));

            byte[] headerBuffer = new byte[headerSize];

            DataReader reader = new DataReader(_stream.InputStream);

            while (true)
            {
                await reader.LoadAsync(headerSize);

                reader.ReadBytes(headerBuffer);

                MessageHeader header = StructSerializer.DeserializeStruct <MessageHeader>(headerBuffer);

                if (header.Type == MessageType.Telemetry)
                {
                    uint   telemetrySize   = (uint)Marshal.SizeOf(typeof(TelemetryMessage));
                    byte[] telemetryBuffer = new byte[telemetrySize - headerSize];
                    await reader.LoadAsync(telemetrySize - headerSize);

                    reader.ReadBytes(telemetryBuffer);

                    var z = new byte[headerBuffer.Length + telemetryBuffer.Length];
                    headerBuffer.CopyTo(z, 0);
                    telemetryBuffer.CopyTo(z, headerBuffer.Length);

                    TelemetryMessage telemetry = StructSerializer.DeserializeStruct <TelemetryMessage>(z);
                    CurrentValues.Update(telemetry);

                    Debug.WriteLine("Telemetry");
                    for (int i = 0; i < TelemetryMessage.EntryLength; i++)
                    {
                        Debug.WriteLine("  {0} = {1},{2}", telemetry.Devices[i].Hash, telemetry.Devices[i].IValue, telemetry.Devices[i].DValue);
                    }
                    Debug.WriteLine("");

                    for (int i = 0; i < TelemetryMessage.EntryLength; i++)
                    {
                        if (telemetry.Devices[i].Hash == 0)
                        {
                            continue;
                        }

                        //If we are not watching this hash, ignore it
                        if (!_telemetry.ContainsKey(telemetry.Devices[i].Hash))
                        {
                            continue;
                        }

                        ObservableCollection <Data> collection = _telemetry[telemetry.Devices[i].Hash];

                        object   value;
                        TypeCode type = _telemetryHashToType[telemetry.Devices[i].Hash];
                        switch (type)
                        {
                        case TypeCode.Int32:
                            value = telemetry.Devices[i].IValue;
                            break;

                        case TypeCode.Single:
                            value = telemetry.Devices[i].DValue;
                            break;

                        default:
                            throw new NotImplementedException();
                        }

                        Data data = new Data {
                            DateTime = DateTime.Now, Value = value
                        };
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            collection.Add(data);
                        });
                    }
                }
            }
        }