public static async Task OnTTNDeviceEvent([MqttTrigger(typeof(TTNConfigProvider), "%TTNAppID%/devices/+/events/#")] IMqttMessage message, ILogger logger) { logger.LogInformation($"{DateTime.Now:g} Message for topic {message.Topic}"); var messageParts = message.Topic.Split('/'); var deviceId = messageParts[2]; var deviceEvent = messageParts[4]; using (var registryManager = RegistryManager.CreateFromConnectionString(AzureConfigProvider.GetIoTHubConnectionString())) { // TODO: This is a workaround for https://github.com/chkr1011/MQTTnet/issues/569. To be implemented in the correct way once this is fixed. switch (deviceEvent) { case "create": { await registryManager.AddDeviceAsync(new Device(deviceId)); logger.LogInformation($"{DateTime.Now:g} Added device {deviceId} to IoT Hub"); } break; case "delete": { await registryManager.RemoveDeviceAsync(deviceId); logger.LogInformation($"{DateTime.Now:g} Removed device {deviceId} from IoT Hub"); } break; default: break; } } }
public static async Task OnTTNDeviceDeleted([MqttTrigger(typeof(TTNConfigProvider), "%TTNAppID%/devices/+/events/delete")] IMqttMessage message, ILogger logger) { logger.LogInformation($"{DateTime.Now:g} Device deletion message for topic {message.Topic}"); var messageParts = message.Topic.Split('/'); var deviceId = messageParts[2]; using (var registryManager = RegistryManager.CreateFromConnectionString(AzureConfigProvider.GetIoTHubConnectionString())) { await registryManager.RemoveDeviceAsync(deviceId); logger.LogInformation($"{DateTime.Now:g} Removed device {deviceId} from IoT Hub"); } }
public static async Task OnTTNUplinkMessage([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest request, ILogger logger) { logger.LogInformation($"{DateTime.Now:g} Device to Cloud message received"); var requestBody = await new StreamReader(request.Body).ReadToEndAsync(); var jsonData = JObject.Parse(requestBody); var appId = jsonData["app_id"].ToString(); var deviceId = jsonData["dev_id"].ToString(); if (appId.Equals(TTNConfigProvider.GetTTNAppId())) { using (var registryManager = RegistryManager.CreateFromConnectionString(AzureConfigProvider.GetIoTHubConnectionString())) { var device = await registryManager.GetDeviceAsync(deviceId); using (var deviceClient = DeviceClient.CreateFromConnectionString(AzureConfigProvider.GetDeviceConnectionString(deviceId, device.Authentication.SymmetricKey.PrimaryKey))) { var eventMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(jsonData.ToString())); await deviceClient.SendEventAsync(eventMessage); } logger.LogInformation($"{DateTime.Now:g} Sent event from device {deviceId} to IoT Hub"); } } }