Ejemplo n.º 1
0
        public void CheckRegistriesLimit(string projectId, string regionId)
        {
            List <DeviceRegistry> listRegistries = (List <DeviceRegistry>)CloudIotMqttExample.GetRegistries(projectId, regionId);

            if (listRegistries != null && listRegistries.Count > 90)
            {
                //Clean 20 oldest registries with testing prefix in the project.
                Console.WriteLine("The maximum number of registries is about to exceed.");
                Console.WriteLine("Deleting the oldest 20 registries with IoT Test prefix");
                var count = 20;
                var index = 0;
                while (count > 0)
                {
                    if (listRegistries[index].Id.Contains("iot-test-"))
                    {
                        CloudIotSample.UnbindAllDevices(projectId, regionId, listRegistries[index].Id);
                        CloudIotSample.ClearRegistry(projectId, regionId, listRegistries[index].Id);
                        count--;
                    }
                    index++;
                }
            }
        }
Ejemplo n.º 2
0
        // [END iot_detach_device]

        /// <summary>
        /// Listens for configuration and system error messages on the gateway and
        /// bound devices.
        /// </summary>
        // [START listen_for_config_messages]
        public static object ListenForConfigMessages(string projectId, string cloudRegion,
                                                     string registryId, string deviceId, string gatewayId, int numMessages,
                                                     string privateKeyFile, string algorithm, string caCerts, string mqttBridgeHostname,
                                                     int mqttBridgePort, int jwtExpiresMinutes, int duration)
        {
            var clientId = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}" +
                           $"/devices/{gatewayId}";
            var jwtIatTime = SystemClock.Instance.GetCurrentInstant();
            // Create a duration
            Duration durationExp = Duration.FromMinutes(jwtExpiresMinutes);
            var      jwtExpTime  = SystemClock.Instance.GetCurrentInstant().Plus(durationExp);
            var      pass        = "";

            if (algorithm == "RS256")
            {
                pass = CloudIotMqttExample.CreateJwtRsa(projectId, privateKeyFile);
            }
            else if (algorithm == "ES256")
            {
                Console.WriteLine("Currently, we do not support this algorithm.");
                return(0);
            }

            // Use gateway to connect server
            var mqttClient = GetClient(
                projectId,
                cloudRegion,
                registryId,
                gatewayId,
                caCerts,
                mqttBridgeHostname,
                mqttBridgePort);

            double initialConnectIntervalMillis     = 0.5;
            double maxConnectIntervalMillis         = 6;
            double maxConnectRetryTimeElapsedMillis = 900;
            double intervalMultiplier = 1.5;

            double retryIntervalMs  = initialConnectIntervalMillis;
            double totalRetryTimeMs = 0;

            // Both connect and publish operations may fail. If they do,
            // allow retries but with an exponential backoff time period.
            while (!mqttClient.IsConnected &&
                   totalRetryTimeMs < maxConnectRetryTimeElapsedMillis)
            {
                try
                {
                    // Connect to the Google MQTT bridge.
                    mqttClient.Connect(clientId, "unused", pass);
                }
                catch (AggregateException aggExceps)
                {
                    printExceptions(aggExceps);
                    Console.WriteLine("Retrying in " + retryIntervalMs
                                      + " seconds.");

                    System.Threading.Thread.Sleep((int)retryIntervalMs);
                    totalRetryTimeMs += retryIntervalMs;
                    retryIntervalMs  *= intervalMultiplier;
                    if (retryIntervalMs > maxConnectIntervalMillis)
                    {
                        retryIntervalMs = maxConnectIntervalMillis;
                    }
                }
            }

            SetupMqttTopics(mqttClient, gatewayId);
            AttachDevice(mqttClient, deviceId, "{}");

            // Wait for about a minute for config messages.
            Console.WriteLine("Listening...");
            for (int i = 0; i < duration; ++i)
            {
                Console.Write(".");
                var secSinceIssue = SystemClock.Instance.GetCurrentInstant().Minus(jwtIatTime);
                if (secSinceIssue.TotalSeconds > (60 * jwtExpiresMinutes))
                {
                    Console.WriteLine("Refreshing token after {0}s", secSinceIssue);
                    jwtIatTime = SystemClock.Instance.GetCurrentInstant();
                    // refresh token and reconnect.
                    pass       = CloudIotMqttExample.CreateJwtRsa(projectId, privateKeyFile);
                    mqttClient = GetClient(
                        projectId,
                        cloudRegion,
                        registryId,
                        gatewayId,
                        caCerts,
                        mqttBridgeHostname,
                        mqttBridgePort);
                }
                System.Threading.Thread.Sleep(1000);
            }

            DetachDevice(mqttClient, deviceId);
            // wait for the device get detached.
            System.Threading.Thread.Sleep(2000);
            mqttClient.Disconnect();
            Console.WriteLine("Finished.");
            return(0);
        }
Ejemplo n.º 3
0
 private void StartMqtt(string deviceId, string privateKeyPath)
 {
     CloudIotMqttExample.StartMqtt(_fixture.ProjectId, _fixture.RegionId, _fixture.RegistryId,
                                   deviceId, privateKeyPath, "RS256", _fixture.CertPath, 1, "events", "mqtt.googleapis.com", 443, 1, 20);
 }