locked
Iot Operations Monitoring RRS feed

  • Question

  • Hi,

    I have an Azure IoT Hub. It's a Free Trial version.

    I have enabled IoT Operations Monitoring for Device Identity Operations and Connections, I am seeing DeviceIdentity Operations events being raised but none for Connections. i.e. when Devices connect and disconnect to the hub.

    I can see my devices as connected / disconnected in Device Explorer. I can also view the devices as enabled.

    However, when devices are connecting and disconnecting, I am seeing no events being raised by the Operations Monitoring on IoT hub.

    Both stream analytics and Azure function is seeing the Device Identity Operations, but not Connections.

    Is this feature working?

    Thanks,


    Stuart


    • Edited by Stuart876 Wednesday, April 19, 2017 10:53 AM
    Wednesday, April 19, 2017 10:52 AM

All replies

  • Hi Stuart,

    - I have tested on my IoT Hub - S1 and it's working very well. My Azure Function generates a message on Service Bus Topic when the MQTT device is connected/disconnected to/from Azure IoT Hub.

    The following screen snippet shows these messages on my Service Bus Tester:

    - your issue looks like your device is Http, but in this case you will not see a connection state (Connected/Disconnected) in the Device Explorer, also your Azure Function (AFN) integration to the Operations EventHub of the IoT Hub looks OK, otherwise you will not see the Device Identity events in the AFN.

    - anyway, could you show your AFN (code, bindings, integration)?

    Thanks

    Roman

     



    • Edited by Roman Kiss Wednesday, April 19, 2017 6:48 PM
    Wednesday, April 19, 2017 6:47 PM
  • Thanks for the reply.

    My device is connecting over AMQP. I can see it as connected in DeviceExplorer and when I kill it via Task Manager I can see it as disconnected within seconds and then Connected when i start it up again.

    My Azure Function:

    using System;

        

    using System.Configuration;
    using System.Data.SqlClient;
    using Newtonsoft.Json;

    public static void Run(string myEventHubMessage, TraceWriter log)
    {
        log.Info(myEventHubMessage);

        try
        {
            var connectionString = ConfigurationManager.ConnectionStrings["iotAzureSQLDb"].ConnectionString;

            log.Info(connectionString);
            var message = JsonConvert.DeserializeObject<MonitoringMessage>(myEventHubMessage);

            using (var connection = new SqlConnection(connectionString))
            {
                var sqlStatement = "insert into [dbo].[DeviceStatuses] " +
                                    "(DeviceId, ConnectionStatus, ConnectionUpdateTime, OperationName, Category, StatusCode, StatusType, StatusDescription)" +
                                    "values " +
                                    "(@DeviceId, @ConnectionStatus, @ConnectionUpdateTime, @OperationName, @Category, @StatusCode, @StatusType, @StatusDescription)";
                using (var dataCommand = new SqlCommand(sqlStatement, connection))
                {
                    dataCommand.Parameters.AddWithValue("@ConnectionStatus", message.operationName);
                    dataCommand.Parameters.AddWithValue("@DeviceId", message.deviceId);
                    dataCommand.Parameters.AddWithValue("@ConnectionUpdateTime", message.time);
                    dataCommand.Parameters.AddWithValue("@Category", message.category);
                    dataCommand.Parameters.AddWithValue("@StatusCode", message.statusCode);
                    dataCommand.Parameters.AddWithValue("@StatusType", message.statusType);
                    dataCommand.Parameters.AddWithValue("@StatusDescription", message.statusDescription);
                    dataCommand.Parameters.AddWithValue("@OperationName", message.operationName);

                    connection.Open();
                    dataCommand.ExecuteNonQuery();
                    connection.Close();

                    log.Info($"Device {message.deviceId} changed state: {message.operationName}");
                }
            }
        }
        catch (Exception ex)
        {
            log.Info(ex.Message);
        }
    }

    public class MonitoringMessage
    {
        public string deviceId { get; set; }
        public string operationName { get; set; }
        public int? durationMs { get; set; }
        public string authType { get; set; }
        public string protocol { get; set; }
        public DateTimeOffset? time { get; set; }
        public string category { get; set; }
        public string level { get; set; }
        public int? statusCode { get; set; }
        public int? statusType { get; set; }
        public string statusDescription { get; set; }
    }

    My project.json:

    {
      "frameworks": {
        "net46":{
          "dependencies": {
            "Newtonsoft.Json": "9.0.1",
            "System.Data.SqlClient":"4.1.0"
          }
        }
       }
    }

    Bindings

    {
      "bindings": [
        {
          "type": "eventHubTrigger",
          "name": "myEventHubMessage",
          "direction": "in",
          "path": "iothub-ehub-iotsentila-140253-3515b9e803",
          "connection": "iotmon99",
          "consumerGroup": "$Default"
        }
      ],
      "disabled": false
    }

    My device connection code:

    public static async Task ConnectToHubAndListenForMessagesAsync(string hostName, string deviceId, string sharedAccessKey, Microsoft.Azure.Devices.Client.TransportType transportType = Microsoft.Azure.Devices.Client.TransportType.Amqp_WebSocket_Only)
    {
    _logger.Info("Connect to hub and listen for messages.");

    if (String.IsNullOrWhiteSpace(hostName))
    throw new Exception("No connection string established.");
    if (String.IsNullOrWhiteSpace(deviceId))
    throw new Exception("No device Name provided.");
    if (String.IsNullOrWhiteSpace(sharedAccessKey))
    throw new Exception("No Shared Access Key provided.");

    _hostName = hostName;
    _deviceId = deviceId;
    TransportType = transportType;
    _sharedAccessKey = sharedAccessKey;

    _connectionString = string.Format("HostName={0};SharedAccessKeyName=iothubowner;SharedAccessKey={1}", hostName, sharedAccessKey);
    _logger.Trace("Add device.");

    await AddDeviceAsync().ConfigureAwait(false);

    _logger.Info("About to receive cloud to device message async.");

    try
    {
    ReceiveCloudToDeviceMessageAsync();
    }
    catch (Exception)
    {
    // wait 2 mins and try to reconnect to hub.
    await Task.Delay(120000).ConfigureAwait(false);
    await ConnectToHubAndListenForMessagesAsync(hostName, deviceId, sharedAccessKey, TransportType);
    }
    }

    private static async Task AddDeviceAsync()
    {
    Device device = null;
    try
    {
    _registryManager = RegistryManager.CreateFromConnectionString(_connectionString);

    device = await _registryManager.AddDeviceAsync(new Device(_deviceId));
    }
    catch (DeviceAlreadyExistsException)
    {
    device = await _registryManager.GetDeviceAsync(_deviceId);
    _logger.Info("Device already exists on IoT Hub");
    }
    catch (TimeoutException)
    {
    _deviceClient.Dispose();

    if (TransportType == TransportType.Amqp_WebSocket_Only)
    {
    TransportType = TransportType.Amqp_Tcp_Only;
    _logger.Info("TimedOut: changing to AMQP_TCP_ONLY From AMQP_WebSockets");
    device = await _registryManager.AddDeviceAsync(new Device(_deviceId));
    }
    else
    {
    _logger.Error("We can't connect over AMQP_WebSockets or AMQP_TCPOnly. Need to enable IotUsesHttps in registry.");
    }
    }
    catch (Exception ex)
    {
    var eventArgs = new IotConnectionDownEventArgs();
    AzureDeviceDisconnectionAlert?.Invoke(new object(), eventArgs);
    }

    if (device == null)
    {
    var eventArgs = new IotConnectionDownEventArgs();
    AzureDeviceDisconnectionAlert?.Invoke(new object(), eventArgs);
    }
    else
    {
    _deviceClient = DeviceClient.Create(_hostName, new DeviceAuthenticationWithRegistrySymmetricKey(_deviceId, device.Authentication.SymmetricKey.PrimaryKey), TransportType);
    _connected = true;
    _logger.Info("Successfully connected device to to IoT");
    }
    }

    When I connect, I've tried specifying the connection as AMQP, AMQPWebSockets, HTTP, AMQP TCP and neither end up with me getting these connection / disconnection events. Only the create events.

    I've changed it to use MQTT and now I am receiving the messages about connection / disconnection. Unfortunately I can't use MQTT in production. Are these event messages only available for MQTT?

    Thanks,




    • Edited by Stuart876 Thursday, April 20, 2017 7:40 AM
    Thursday, April 20, 2017 7:14 AM
  • Hi Stuart,

    - you should see all Connected/Disconnected events from the connection-oriented devices to the Azure IoT Hub, such as all supported protocols except Http. You can watch number of connected devices in the  Monitoring/Metrics of the IoT Hub.

    Thanks

    Roman




    • Edited by Roman Kiss Thursday, April 20, 2017 11:15 PM
    Thursday, April 20, 2017 11:14 PM