private async Task receiveMessageAsync(String iotHubUri, String iotHubConnectString)
        {
            while (true)
            {
                if (ctsForStart.IsCancellationRequested)
                {
                    return;
                }

                Microsoft.Azure.Devices.Client.Message message = await iotClient.ReceiveC2dAsync();

                if (message == null)
                {
                    continue;
                }
                Debug.WriteLine("Received message: " + Encoding.ASCII.GetString(message.GetBytes()));
            }
        }
        public DeserializableCommand(Microsoft.Azure.Devices.Client.Message message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            Debug.Assert(
                !string.IsNullOrEmpty(message.LockToken),
                "message.LockToken is a null reference or empty string.");
            _lockToken = message.LockToken;

            byte[] messageBytes = message.GetBytes(); // this needs to be saved if needed later, because it can only be read once from the original Message

            string jsonData = Encoding.UTF8.GetString(messageBytes);

            _commandHistory = JsonConvert.DeserializeObject <CommandHistory>(jsonData);
        }
        public static async Task StoreMessageAsync([EdgeHubTrigger("input1")] DeviceMessage input, ILogger logger)
        {
            var inputMessage = Encoding.UTF8.GetString(input.GetBytes());

            if (string.IsNullOrEmpty(inputMessage))
            {
                logger.LogInformation("Received empty message!");

                return;
            }

            logger.LogInformation($"Received message: {inputMessage}");

            var message = ParseMessage(inputMessage);

            var messageData = ParseData(message.Data);

            var measurementData = new List <string>();

            foreach (var measurement in messageData.Contents)
            {
                foreach (var data in measurement.Data)
                {
                    foreach (var value in data.Values)
                    {
                        measurementData.Add($"('{message.Id}','{message.Source}','{message.Type}','{message.SpecVersion}','{message.DataContentType}','{measurement.HwId}','{value.Address}','{value.Value}','{data.SourceTimestamp}')");
                    }
                }
            }

            var insertStatement = $"INSERT INTO dbo.PowerMeasurements VALUES {String.Join(",", measurementData)};";

            using (var connection = new SqlConnection(DatabaseConnection))
            {
                connection.Open();

                using (var cmd = new SqlCommand(insertStatement, connection))
                {
                    var rows = await cmd.ExecuteNonQueryAsync();

                    logger.LogInformation($"{rows} rows were updated");
                }
            }
        }
Exemple #4
0
        public DeserializableCommand(Microsoft.Azure.Devices.Client.Message message, JsonSerialize serializer)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            Debug.Assert(
                !string.IsNullOrEmpty(message.LockToken),
                "message.LockToken is a null reference or empty string.");
            _lockToken = message.LockToken;

            byte[] messageBytes = message.GetBytes(); // this needs to be saved if needed later, because it can only be read once from the original Message

            _command = serializer.DeserializeObject <dynamic>(messageBytes);
        }
Exemple #5
0
        private async Task sendMessage(string deviceId,
                                       string commonKey,
                                       string iotHub,
                                       int messageCount,
                                       JObject payLoad,
                                       int messageDelaySeconds,
                                       Boolean randomize)
        {
            Microsoft.Azure.Devices.Client.DeviceClient deviceClient;
            string connectionString = "HostName=" + iotHub + ";DeviceId=" + deviceId + ";SharedAccessKey=" + commonKey;

            deviceClient = Microsoft.Azure.Devices.Client.DeviceClient.CreateFromConnectionString(connectionString);

            //Command timeout. Default is 240 seconds
            deviceClient.OperationTimeoutInMilliseconds = 30000; //30 second timeout
            //Set retry policy for sending messages (default is NoRetry)
            deviceClient.SetRetryPolicy(new Microsoft.Azure.Devices.Client.ExponentialBackoff(
                                            retryCount: int.MaxValue,
                                            minBackoff: TimeSpan.FromSeconds(1),
                                            maxBackoff: TimeSpan.FromSeconds(60),
                                            deltaBackoff: TimeSpan.FromSeconds(2)));

            Random random         = new Random();
            int    messageCounter = 1;

            while (messageCounter <= messageCount)
            {
                if (randomize)
                {
                    int delaySeconds = random.Next(messageDelaySeconds * 1000);
                    payLoad["LOADTEST-delaySeconds"] = delaySeconds / 1000;
                    System.Threading.Thread.Sleep(delaySeconds);
                }
                else
                {
                    System.Threading.Thread.Sleep(messageDelaySeconds * 1000);
                }

                payLoad["LOADTEST-counter"]           = messageCounter;
                payLoad["LOADTEST-generationTimeUTC"] = DateTime.UtcNow.ToString();
                payLoad["LOADTEST-origionatingHost"]  = Environment.MachineName;

                Byte[] messageByte = System.Text.Encoding.UTF8.GetBytes(payLoad.ToString());
                Microsoft.Azure.Devices.Client.Message message = new Microsoft.Azure.Devices.Client.Message(messageByte);
                message.ContentEncoding = "utf-8";
                message.ContentType     = "application/json";

                try {
                    await deviceClient.SendEventAsync(message);

                    Console.WriteLine("Device: " + deviceId + " sent msg " + payLoad.ToString());

                    Microsoft.Azure.Devices.Client.Message receivedMessage = await deviceClient.ReceiveAsync(new TimeSpan(0, 0, 1));

                    if (receivedMessage != null)
                    {
                        string jsonMessage = System.Text.Encoding.ASCII.GetString(receivedMessage.GetBytes());
                        Console.WriteLine("Device: " + deviceId + " received msg " + jsonMessage);
                    }
                    messageCounter++;
                }
                catch (Exception) { }
            }
            await deviceClient.CloseAsync();
        }