示例#1
0
        public static void image_mqtt_ingest(
            [MqttTrigger("site/+/grids/+/sensors/image/#")] IMqttMessage message,
            ILogger logger,
            IBinder binder)
        {
            // topic structure: sites/xx/grids/dd/sensors/image/bin/#
            // topic structure: sites/xx/grids/dd/sensors/image/status/#
            var topicParts = message.Topic.Split('/');
            var siteid     = topicParts[1];
            var imagepath  = string.Join('/', topicParts.Skip(6).SkipLast(1));
            var blobname   = topicParts.Last();

            logger.LogInformation($"CreateBlobUsingBinder function processed: {message}");
            using (var writer = binder.Bind <Stream>(new BlobAttribute(
                                                         $"brc-images/sites/{siteid}/{imagepath}/{blobname}.jpg", FileAccess.Write)))
            {
                writer.Write(message.GetMessage());
            };

            using (var writer = binder.Bind <Stream>(new BlobAttribute(
                                                         $"brc-images/sites/{siteid}/{imagepath}/latest.jpg", FileAccess.Write)))
            {
                writer.Write(message.GetMessage());
            };
        }
        public static async Task Run([MqttTrigger("minicursoiot/+/#", ConnectionString = "MqttConnectionString")] IMqttMessage data, ILogger log, ExecutionContext context)
        {
            log.LogInformation($"Payload {Convert.ToBase64String(data.GetMessage())}");
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            if (IoTHub == null)
            {
                IoTHub = new IoTHubClient(config["IoTHubConnectionString"]);
            }
            await IoTHub.SendRaw(data.Topic, data.GetMessage());
        }
示例#3
0
        public async Task NewMessageIsProcessedWell()
        {
            // Arrange
            var mockManagedMqttClient        = new Mock <IManagedMqttClient>();
            var mockManagedMqttClientOptions = new Mock <IManagedMqttClientOptions>();
            var mockMqttClientFactory        = new Mock <IMqttClientFactory>();

            mockMqttClientFactory
            .Setup(m => m.CreateManagedMqttClient())
            .Returns(mockManagedMqttClient.Object);

            var config         = new MqttConfiguration("CustomConfig", mockManagedMqttClientOptions.Object);
            var mqttConnection = new MqttConnection(mockMqttClientFactory.Object, config, _mockLogger.Object);

            IMqttMessage receivedMessage = null;

            mqttConnection.OnMessageEventHandler += (MqttMessageReceivedEventArgs arg) =>
            {
                receivedMessage = arg.Message;
                return(Task.CompletedTask);
            };

            // Act
            await mqttConnection.StartAsync();

            mockManagedMqttClient.Raise(x => x.ApplicationMessageReceived += null, new MqttApplicationMessageReceivedEventArgs("ClientId", DefaultMessage));

            // Assert
            Assert.NotNull(receivedMessage);
            Assert.Equal(DefaultMessage.Topic, receivedMessage.Topic);
            Assert.Equal(DefaultMessage.Retain, receivedMessage.Retain);
            Assert.Equal(DefaultMessage.QualityOfServiceLevel.ToString(), receivedMessage.QosLevel.ToString());
            Assert.Equal(DefaultMessage.Payload, receivedMessage.GetMessage());
        }
        public static void AdvancedFunction(
            [MqttTrigger(typeof(ExampleMqttConfigProvider), "testtopic/#")] IMqttMessage message,
            ILogger log)
        {
            var body = Encoding.UTF8.GetString(message.GetMessage());

            log.LogInformation($"Advanced: message from topic {message.Topic} body: {body}");
        }
        public static void SimpleFunction(
            [MqttTrigger("test/#")] IMqttMessage message,
            [Mqtt] out IMqttMessage outMessage,
            ILogger logger)
        {
            var body       = message.GetMessage();
            var bodyString = Encoding.UTF8.GetString(body);

            logger.LogInformation($"Message for topic {message.Topic}: {bodyString}");
            outMessage = new MqttMessage("testtopic/out", Encoding.UTF8.GetBytes("Hi!"), MqttQualityOfServiceLevel.AtLeastOnce, true);
        }
示例#6
0
        public async Task ProcessTimeRace([MqttTrigger("ESP/TimeRace/ToDB", ConnectionString = "MqttConnection2")] IMqttMessage message, ILogger logger)
        {
            try
            {
                var body       = message.GetMessage();
                var bodyString = Encoding.UTF8.GetString(body);
                var records    = JsonConvert.DeserializeObject <timelogtodb>(bodyString);

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("tablestorageconnection"));
                CloudTableClient    tableClient    = storageAccount.CreateCloudTableClient(new Microsoft.Azure.Cosmos.Table.TableClientConfiguration());
                CloudTable          table          = tableClient.GetTableReference("LeaderboardTimeRace");

                TableQuery <timelogtodbEntity> getquery = new TableQuery <timelogtodbEntity>()
                                                          .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, records.name));

                var getQueryResult = await table.ExecuteQuerySegmentedAsync <timelogtodbEntity>(getquery, null);

                timelogtodbEntity entity = new timelogtodbEntity();

                if (getQueryResult.Results.Count == 0)
                {
                    entity.PartitionKey = records.name;
                    entity.RowKey       = Guid.NewGuid().ToString();
                    entity.isFinished   = records.isFinished;
                    entity.totalTime    = records.totalTime;
                }
                else
                {
                    entity.PartitionKey = records.name;
                    entity.RowKey       = getQueryResult.Results[0].RowKey;
                    if (records.totalTime == 0)
                    {
                        entity.isFinished = records.isFinished;
                        entity.totalTime  = getQueryResult.Results[0].totalTime;
                    }
                    else
                    {
                        entity.isFinished = records.isFinished;
                        entity.totalTime  = records.totalTime;
                    }
                }

                TableOperation insertOrMergeOperation = Microsoft.Azure.Cosmos.Table.TableOperation.InsertOrMerge(entity);
                TableResult    result = await table.ExecuteAsync(insertOrMergeOperation);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void SimpleFunction(
            [MqttTrigger(new[] { "owntracks/kees/kees01", "owntracks/marleen/marleen01" })]IMqttMessage message,
            ILogger log,
            [Table("Locations", Connection = "AzureWebJobsStorage")] out Trail trail)
        {
            var body = Encoding.UTF8.GetString(message.GetMessage());

            log.LogInformation($"Message from topic {message.Topic} body: {body}");

            trail = JsonConvert.DeserializeObject<Trail>(body);
            trail.PartitionKey = message.Topic.Replace("/", "_");
            trail.RowKey = DateTime.Now.Ticks.ToString();
            trail.QosLevel = message.QosLevel.ToString();
            trail.Retain = message.Retain;
        }
示例#8
0
        public static void MQTTFunctionsNoResend([MqttTrigger("/home/temperature")] IMqttMessage message, ILogger log)
        {
            //getting the message that has been sent
            var    body        = message.GetMessage();
            string bodyMessage = Encoding.UTF8.GetString(body);

            log.LogInformation($"MQTTFunctionsNoResend: {bodyMessage}");

            /*
             *
             * Do stuff with the message
             * for example Post to database, etc...
             *
             */
        }
示例#9
0
        public static void CloudToDeviceMessages(
            [MqttTrigger("devices/testdevice/messages/devicebound/#", "$iothub/methods/POST/#", ConnectionString = "IoTHubConnectionString"), Disable] IMqttMessage message,
            [Mqtt(ConnectionString = "IoTHubConnectionString"), Disable] out IMqttMessage response,
            ILogger logger)
        {
            var body       = message.GetMessage();
            var bodyString = Encoding.UTF8.GetString(body);

            logger.LogInformation($"{DateTime.Now:g} Message for topic {message.Topic}: {bodyString}");

            if (message.Topic.Contains("methods"))
            {
                response = CloudToDeviceMethodCall(message.Topic);
            }
            else
            {
                response = null;
            }
        }
示例#10
0
        public static void MQTTFunctionsWithResend([MqttTrigger("/home/temperature")] IMqttMessage message, [Mqtt] out IMqttMessage outMessage, ILogger log)
        {
            //getting the message that has been sent
            var    body        = message.GetMessage();
            string bodyMessage = Encoding.UTF8.GetString(body);

            log.LogInformation($"MQTTFunctionsWithResend: {bodyMessage}");

            //sending back a message to a topic
            var newMessage = $"{message} from server";

            outMessage = new MqttMessage("/out", Encoding.ASCII.GetBytes(newMessage),
                                         MqttQualityOfServiceLevel.AtLeastOnce, true);

            /*
             *
             * Do stuff with the message
             * for example Post to database, etc...
             *
             */
        }
        public static void Run(
            [MqttTrigger("/luemniro/id/request")] IMqttMessage message, [Mqtt] out IMqttMessage outMessage, ILogger logger)
        {
            // Creating Telemetry client for logging events!
            TelemetryClient telemetry = new TelemetryClient();

            // Getting connection string
            telemetry.InstrumentationKey = Environment.GetEnvironmentVariable("insightsString");
            // Receiving the message and creating an object from it
            var body       = message.GetMessage();
            var bodyString = Encoding.UTF8.GetString(body);

            // Logging with time
            logger.LogInformation($"{DateTime.Now:g} Message for topic {message.Topic}: {bodyString}");
            ID iD = JsonConvert.DeserializeObject <ID>(bodyString);

            // Checking if the ID isn't already in the database

            // Checking if the ID is exactly 6 digits long
            try
            {
                if (iD.Id.ToString().Length == 6)
                {
                    bool IDResponse = InsertGameID.InsertId(iD.Id);
                    // If it's 6 digits long and NOT in the database
                    if (IDResponse)
                    {
                        var response     = new { id = iD.Id, status = "OK" };
                        var jsonResponse = JsonConvert.SerializeObject(response);
                        outMessage = new MqttMessage("/luemniro/id/response", Encoding.ASCII.GetBytes(jsonResponse), MqttQualityOfServiceLevel.AtLeastOnce, true);
                        logger.LogInformation("ID {iD.Id} is OK", iD.Id);
                        telemetry.TrackEvent("ID_Given");
                        telemetry.TrackEvent("ID_OK");
                    }
                    // If the ID is already in the database
                    else
                    {
                        var response     = new { id = iD.Id, status = "NOK" };
                        var jsonResponse = JsonConvert.SerializeObject(response);
                        outMessage = new MqttMessage("/luemniro/id/response", Encoding.ASCII.GetBytes(jsonResponse), MqttQualityOfServiceLevel.AtLeastOnce, true);
                        logger.LogInformation("ID {iD.Id} is NOK, ID already in database", iD.Id);
                        telemetry.TrackEvent("ID_NOK");
                    }
                }
                // If the ID is NOT 6 digits long!
                else
                {
                    var response     = new { id = iD.Id, status = "NOK" };
                    var jsonResponse = JsonConvert.SerializeObject(response);
                    outMessage = new MqttMessage("/luemniro/id/response", Encoding.ASCII.GetBytes(jsonResponse), MqttQualityOfServiceLevel.AtLeastOnce, true);
                    logger.LogInformation("ID {iD.Id} is NOK, ID does not consist of exactly 6 digits", iD.Id);
                    telemetry.TrackEvent("ID_NOK");
                }
            }
            catch (Exception ex)
            {
                logger.LogInformation("ID {iD.Id} is NOK: " + ex);
                telemetry.TrackEvent("ID_NOK");

                throw ex;
            }
        }