Пример #1
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            try
            {
                var body = JsonConvert.DeserializeObject <Request>(request.Body);

                AmazonIotDataClient client = new AmazonIotDataClient(_accessKey, _secretKey, new AmazonIotDataConfig
                {
                    RegionEndpoint = RegionEndpoint.EUWest1,
                    ServiceURL     = _serviceUrl
                });

                var response = await client.PublishAsync(new Amazon.IotData.Model.PublishRequest()
                {
                    Topic   = _topic,
                    Payload = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(body.Message)),
                    Qos     = 0
                });

                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)response.HttpStatusCode,
                    Body = JsonConvert.SerializeObject(response.ResponseMetadata)
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = e.Message
                });
            }
        }
Пример #2
0
        public Publisher(bool ignoreProxy)
        {
            string awsAccessKey = ConfigurationManager.AppSettings["AWSAccessKey"];
            string awsSecretKey = ConfigurationManager.AppSettings["AWSSecretKey"];

            AWSCredentials      credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
            AmazonIotDataConfig config      = new AmazonIotDataConfig();
            string endPoint = ConfigurationManager.AppSettings["AWSIoTEndPoint"];

            config.ServiceURL = "https://" + endPoint;

            string proxyHost     = ConfigurationManager.AppSettings["ProxyHost"];
            string proxyPort     = ConfigurationManager.AppSettings["ProxyPort"];
            string proxyUser     = ConfigurationManager.AppSettings["ProxyUser"];
            string proxyPassword = ConfigurationManager.AppSettings["ProxyPassword"];

            if (!ignoreProxy && !string.IsNullOrEmpty(proxyHost))
            {
                config.ProxyHost = proxyHost;
                config.ProxyPort = int.Parse(proxyPort);
                if (!string.IsNullOrEmpty(proxyUser))
                {
                    config.ProxyCredentials = new NetworkCredential(proxyUser, proxyPassword);
                }
                _usingProxy = true;
            }
            client = new AmazonIotDataClient(credentials, config);

            topic = ConfigurationManager.AppSettings["AWSIoTTopic"];
        }
Пример #3
0
        public static void Main(string[] args)
        {
            IAmazonIotData client = new AmazonIotDataClient(
                serviceUrl: "https://data.iot.us-east-1.amazonaws.com/"
                );

            Publish(client, topic: "test/123");
            Publish(client, topic: "test,123");
        }
Пример #4
0
        public AWSClientsService(IConfiguration config)
        {
            _config = config;
            var awsCredentials = new BasicAWSCredentials(_config["AWS:ApiAccessKey"], _config["AWS:ApiSecretKey"]);

            IoTClient     = new AmazonIoTClient(awsCredentials, RegionEndpoint.GetBySystemName(_config["AWS:Region"]));
            IoTDataClient = new AmazonIotDataClient("https://" + _config["AWS:IoTEndpoint"], awsCredentials);
            IoTJobClient  = new AmazonIoTJobsDataPlaneClient("https://" + _config["AWS:IoTEndpoint"], awsCredentials);
            S3Client      = new AmazonS3Client(awsCredentials, RegionEndpoint.GetBySystemName(_config["AWS:Region"]));
        }
        public async void AmazonIotStreamer([FromQuery] int messageToSend = 10, [FromQuery] int delayBtwMessageInMs = 50)
        {
            var rd = new Random(100);

            var histogram = new LongHistogram(TimeStamp.Hours(1), 3);

            var writer = new StringWriter();

            var messages = messageToSend;

            string[] currencyPairs = new string[] { "EUR/USD", "EUR/JPY", "EUR/GBP", "USD/JPY", "USD/GBP" };
            for (int currIndex = 0; currIndex < currencyPairs.Length; currIndex++)
            {
                var pair = currencyPairs[currIndex];

                Task.Run(async() =>
                {
                    var publisher = new AmazonIotDataClient(IotEndpoint, new BasicAWSCredentials(IotAccessKey, IotSecret));
                    for (var i = 1; i <= messages; i++)
                    {
                        long startTimestamp = Stopwatch.GetTimestamp();
                        long timestamp      = DateTimeOffset.Now.ToUnixTimeMilliseconds();

                        var currency = new Currency()
                        {
                            Id           = i,
                            CurrencyType = pair,
                            Price        = rd.NextDouble(),
                            Timestamp    = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString(),
                            Ladders      = new LadderFactory().Build(10)
                        };

                        var cur = JsonConvert.SerializeObject(currency);

                        publisher.PublishAsync(new Amazon.IotData.Model.PublishRequest()
                        {
                            Topic   = pair,
                            Payload = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cur)),
                            Qos     = 0
                        });

                        long elapsed = Stopwatch.GetTimestamp() - startTimestamp;
                        histogram.RecordValue(elapsed);
                        await Task.Delay(delayBtwMessageInMs).ConfigureAwait(false);
                    }

                    var scalingRatio = OutputScalingFactor.TimeStampToMilliseconds;
                    histogram.OutputPercentileDistribution(
                        writer,
                        outputValueUnitScalingRatio: scalingRatio);
                    System.IO.File.WriteAllText(@"d:\cloud\appsync.txt", writer.ToString());
                });
            }
        }
    public Thing(string thingName)
    {
        var fileText            = Resources.Load <TextAsset>("accesskeys").text;
        var lines               = fileText.Split('\n');
        var secrets             = lines[1].Split(',');
        var awsAccessKeyId      = secrets[0].Trim();
        var awsSecretAccessKey  = secrets[1].Trim();
        var amazonIotDataConfig = new AmazonIotDataConfig
        {
            ServiceURL = "https://a2soq6ydozn6i0-ats.iot.us-west-2.amazonaws.com/"
        };

        _thingName  = thingName;
        _dataClient = new AmazonIotDataClient(awsAccessKeyId, awsSecretAccessKey, amazonIotDataConfig);
    }
Пример #7
0
        static void Main(string[] devices)
        {
            //if (devices != null)
            //    _devices = devices;
            //else
            _devices = new string[] { "store1_aisle1", "store1_aisle2", "store1_aisle3", "store1_aisle4" };

            _responses            = new Dictionary <string, string>(_devices.Length);
            _iotClient            = new AmazonIotDataClient("https://data.iot.us-east-1.amazonaws.com/");
            _dynamoDbClient       = new AmazonDynamoDBClient();
            _recommendationsTable = Table.LoadTable(_dynamoDbClient, tableName);

            Thread thread = new Thread(KeepGettingShadows);

            thread.Start();

            // Keep the main thread alive for the event receivers to get invoked
            KeepConsoleAppRunning(() => {
                Console.WriteLine("Disconnecting client..");
            });
        }
Пример #8
0
        public static void ClassInitialize(TestContext testContext)
        {
            Client = new AmazonIotDataClient("https://data.iot.us-east-1.amazonaws.com/");

            using (var iotClient = new AmazonIoTClient())
            {
                var things     = iotClient.ListThings().Things;
                var firstThing = things.FirstOrDefault();
                if (firstThing == null)
                {
                    THING_NAME = "dotnettest" + DateTime.UtcNow.ToFileTime();
                    iotClient.CreateThing(new CreateThingRequest
                    {
                        ThingName = THING_NAME
                    });
                    CREATED_THING_NAME = THING_NAME;
                }
                else
                {
                    THING_NAME = firstThing.ThingName;
                }
            }
        }
Пример #9
0
        static void Main(string[] args)
        {
            Credentials credentials = null;
            string      accountId   = null;
            string      roleName    = null;

            if (args.Length == 2)
            {
                Console.WriteLine("Account ID and role name specified, publishing cross-account");
                accountId   = args[0];
                roleName    = args[1];
                credentials = GetCrossAccountCredentials(accountId, roleName);
            }
            else
            {
                Console.WriteLine("An invalid number of options was specified, cannot continue");
                Environment.Exit(1);
            }

            Console.WriteLine("Setting region to us-east-1");
            var myRegion = Amazon.RegionEndpoint.USEast1;

            Console.WriteLine("Creating IoT client");
            AmazonIoTClient myIotClient = new AmazonIoTClient(credentials, myRegion);

            Console.WriteLine(("Obtaining customer specific endpoint information for publishing messages to IoT Core"));

            try
            {
                var describeEndpointResponse = myIotClient.DescribeEndpointAsync(new DescribeEndpointRequest()).Result;
                var endpointAddress          = "https://" + describeEndpointResponse.EndpointAddress;

                Console.WriteLine("Starting infinite publish loop");

                Console.WriteLine("Creating IoT data client for message publishing");
                AmazonIotDataClient myIotDataClient = new AmazonIotDataClient(endpointAddress, credentials);

                while (true)
                {
                    if (credentials != null)
                    {
                        Console.WriteLine("Refreshing cross-account credentials and IoT data client");
                        credentials     = GetCrossAccountCredentials(accountId, roleName);
                        myIotDataClient = new AmazonIotDataClient(endpointAddress, credentials);
                    }

                    Console.WriteLine("Creating a publish request with a test message");

                    // This is done inside the loop because re-using publish requests does not work on Mono on Linux
                    var publishRequest = new PublishRequest();
                    publishRequest.Qos     = 0;
                    publishRequest.Topic   = Constants.Topic;
                    publishRequest.Payload = new MemoryStream(Encoding.UTF8.GetBytes(Constants.Payload ?? ""));

                    var publishResponse = myIotDataClient.PublishAsync(publishRequest).Result;
                    Console.WriteLine("Published message, sleeping...");
                    Console.WriteLine(publishResponse.HttpStatusCode.ToString());
                    Thread.Sleep(Constants.SleepTime);
                }
            }
            catch (AggregateException e)
            {
                // Simple check to see if the error looks like a missing role
                if (e.Message.Contains("does not indicate success"))
                {
                    Console.WriteLine(
                        "Failed to obtain the customer endpoint information or publish a message, is a role attached to this EC2 instance?");
                }
                else if (e.Message.Contains("is not authorized"))
                {
                    Console.WriteLine(
                        "Access denied when obtaining the customer endpoint information or when publishing a message, does the role attached to this EC2 instance have the correct permissions?");
                }
                else
                {
                    Console.WriteLine("FAIL Main");
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                }

                Environment.Exit(1);
            }
        }
Пример #10
0
        public void Start()
        {
            AmazonIotDataConfig amazonIotDataConfig = new AmazonIotDataConfig();

            amazonIotDataConfig.RegionEndpoint = RegionEndpoint.EUWest1;
            //amazonIotDataConfig.UseHttp = false;
            //amazonIotDataConfig.SignatureVersion = "4";
            amazonIotDataConfig.ServiceURL = amazonIotDataConfig.DetermineServiceURL();

            Client = new AmazonIotDataClient(awsAccessKeyId, awsSecretAccessKey, amazonIotDataConfig);


            Monitorings = new List <Monitoring>();


            HardDriveSmartMonitoring hardDriveSmartMonitoring = new HardDriveSmartMonitoring((data) =>
            {
                var payload = new
                {
                    state = new
                    {
                        reported = new
                        {
                            Monitoring = new
                            {
                                HardDriveSmart = data
                            }
                        }
                    }
                };


                var request       = new UpdateThingShadowRequest();
                request.ThingName = thingName;
                request.Payload   = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload)));

                var response = Client.UpdateThingShadow(request);
            });

            Monitorings.Add(hardDriveSmartMonitoring);


            HardDriveSpaceMonitoring hardDriveSpaceMonitoring = new HardDriveSpaceMonitoring((data) =>
            {
                var payload = new
                {
                    state = new
                    {
                        reported = new
                        {
                            Monitoring = new
                            {
                                HardDriveSpace = data
                            }
                        }
                    }
                };


                var request       = new UpdateThingShadowRequest();
                request.ThingName = thingName;
                request.Payload   = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload)));

                var response = Client.UpdateThingShadow(request);
            });

            Monitorings.Add(hardDriveSpaceMonitoring);


            Monitorings.ForEach((monitoring) => monitoring.Start());
        }
        public Function()
        {
            _client = new AmazonIotDataClient("https://data.iot.us-east-1.amazonaws.com/");

            InitializeTestData();
        }
Пример #12
0
 public ThingShadowProvider(IConfiguration config)
 {
     this.thingName = config["ThingName"];
     this.client    = new AmazonIotDataClient(config["IotServiceUrl"]);
 }
Пример #13
0
 public static void ClassInitialize(TestContext testContext)
 {
     Client = new AmazonIotDataClient("https://data.iot.us-east-1.amazonaws.com/");
 }