public override async Task InitializeAsync(DevicePluginConfigurationModel configuration)
        {
            await base.InitializeAsync(configuration);

            _connectionString = configuration.Properties["ConnectionString"];

            // get all devices
            var httpClient    = new LocalHttpClient();
            var resultDevices = await httpClient.Client.GetAsync(_connectionString + "devicelist.cgi");

            if (resultDevices.IsSuccessStatusCode)
            {
                var xmlContent = await resultDevices.Content.ReadAsStringAsync();

                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xmlContent);
                foreach (XmlNode deviceNode in xmlDocument.DocumentElement.ChildNodes)
                {
                    var deviceType = deviceNode.Attributes.Cast <XmlAttribute>().Single(n => n.Name == "device_type");
                    var address    = deviceNode.Attributes.Cast <XmlAttribute>().Single(n => n.Name == "address");
                    var id         = deviceNode.Attributes.Cast <XmlAttribute>().Single(n => n.Name == "ise_id");

                    //.Value == "HM-LC-Bl1-FM")
                }
            }

            MessageReceiverLoop(_cancellationTokenSource.Token);
        }
        private async Task CheckVersionsAndUpdateAsync(string functionsAndVersions)
        {
            string[] functionVersionPairs = functionsAndVersions.Split(',');
            var      iotHub   = ServiceLocator.Current.GetService <IAzureIoTHubPlugin>();
            var      baseUrl  = iotHub.ServiceBaseUrl;
            var      deviceId = iotHub.DeviceId;

            var apiKey = ServiceLocator.Current.GetService <IPluginRegistry>().GetPlugin <IAzureIoTHubPlugin>("iothub").ApiKey;

            // create client token
            var tokenClient     = new LocalHttpClient();
            var tokenRequestUrl = baseUrl + "ApiAuthentication/";

            _log.LogDebug("Get api token");
            tokenClient.Client.DefaultRequestHeaders.Add("apikey", apiKey);
            tokenClient.Client.DefaultRequestHeaders.Add("deviceid", deviceId);
            var tokenResponse = await tokenClient.Client.PostAsync(new Uri(tokenRequestUrl), null);

            if (!tokenResponse.IsSuccessStatusCode)
            {
                throw new HttpRequestException(tokenResponse.ReasonPhrase);
            }
            // get token from response
            var tokenReponseContent = await tokenResponse.Content.ReadAsStringAsync();

            dynamic tokenJsonObj = JsonConvert.DeserializeObject(tokenReponseContent);
            string  token        = tokenJsonObj.token;

            foreach (var functionVersionPair in functionVersionPairs)
            {
                var functionId      = functionVersionPair.Split(':')[0];
                var functionVersion = int.Parse(functionVersionPair.Split(':')[1]);

                var localFunctionVersion = await LoadFunctionFromStorageAsync(functionId);

                if (localFunctionVersion == null || (localFunctionVersion.Version < functionVersion))
                {
                    // download function code from webserver
                    var client = new LocalHttpClient();
                    client.Client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                    var functionContent = await client.Client.GetStringAsync(new Uri(baseUrl + "DeviceFunction/" + deviceId + "/" + functionId));

                    // store function file to disk
                    var localStorage = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                    var filePath     = Path.Combine(localStorage, "function_" + functionId + ".json");
                    File.WriteAllText(filePath, functionContent);

                    // (re)load function
                    await ReloadFunction(functionId);
                }
            }
        }
Example #3
0
        public override async Task InitializeAsync(DevicePluginConfigurationModel configuration)
        {
            await base.InitializeAsync(configuration);

            var connectionString = configuration.Properties["ConnectionString"];
            var username         = configuration.Properties["Username"];
            var password         = configuration.Properties["Password"];

            // create default HttpClient used by all channels
            _httpClient = new LocalHttpClient();
            _httpClient.Client.DefaultRequestHeaders.Add("Authorization", "Basic " + Base64.EncodeTo64(username + ":" + password));

            _devices.Add(new SecvestDevice(_httpClient.Client, connectionString));
        }
Example #4
0
        public UserProfileDialog(UserState userState,
                                 IConfiguration config,
                                 ILogger <UserProfileDialog> logger,
                                 CogServicesHttp cogServicesHttp,
                                 LocalHttpClient localService,
                                 InventoryHttp inventoryService)
            : base(nameof(UserProfileDialog))
        {
            _logger           = logger;
            _cogServices      = cogServicesHttp;
            _localService     = localService;
            _inventoryService = inventoryService;

            _config = config;
            _userProfileAccessor = userState.CreateProperty <UserProfile>("UserProfile");

            PreparePipeline();
            _settings = JsonConvert.DeserializeObject <BotSettings>(_config["botSettings"]);
        }
        private async Task <string> DownloadFileAsync(string url, string pathToSavedFile)
        {
            try
            {
                var stream = await LocalHttpClient.GetStreamAsync(url).ConfigureAwait(false);

                using (var fileStream = new FileStream(pathToSavedFile, System.IO.FileMode.Create))
                {
                    await stream.CopyToAsync(fileStream).ConfigureAwait(false);
                }

                return(pathToSavedFile);
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"Error downloading file ({url}).");
                return(string.Empty);
            }
        }
        public object GetDatapointValue(string datapointId)
        {
            var httpClient = new LocalHttpClient();
            var task       = httpClient.Client.GetStringAsync(new Uri(_connectionString + "state.cgi?datapoint_id=" + datapointId));

            Task.WaitAll(task);
            var result      = task.Result;
            var xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(result);
            var   value = xmlDocument.DocumentElement.FirstChild.Attributes["value"].Value;
            float floatResult;

            if (float.TryParse(value, out floatResult))
            {
                return(floatResult);
            }
            return(value);
        }
Example #7
0
        private async Task <string> DownloadFileAsync(string url, string pathToSavedFile)
        {
            try
            {
                var stream = await LocalHttpClient.GetStreamAsync(url).ConfigureAwait(false);

                using (var fileStream = new FileStream(pathToSavedFile, System.IO.FileMode.Create))
                {
                    await stream.CopyToAsync(fileStream).ConfigureAwait(false);
                }

                return(pathToSavedFile);
            }
            catch (Exception ex)
            {
                //Trace.WriteLine($"Error downloading file ({url}).{Environment.NewLine}{ex}");
                App.WriteToErrorLog($"Error downloading file ({url}).", ex.Message, ex.StackTrace);
                return(string.Empty);
            }
        }
        public async Task <string> GetTokenAsync()
        {
            // create client token
            var tokenRequestUrl = _iotHub.ServiceBaseUrl + "ApiAuthentication/";

            _log.LogDebug("GetTokenAsync|Get api token");
            var httpClient = new LocalHttpClient();

            httpClient.Client.DefaultRequestHeaders.Add("apikey", _iotHub.ApiKey);
            httpClient.Client.DefaultRequestHeaders.Add("deviceid", _iotHub.DeviceId);
            var tokenResponse = await httpClient.Client.PostAsync(new Uri(tokenRequestUrl), null);

            if (!tokenResponse.IsSuccessStatusCode)
            {
                throw new HttpRequestException(tokenResponse.ReasonPhrase);
            }
            // get token from response
            var tokenReponseContent = await tokenResponse.Content.ReadAsStringAsync();

            dynamic tokenJsonObj = JsonConvert.DeserializeObject(tokenReponseContent);
            string  token        = tokenJsonObj.token;

            return(token);
        }
Example #9
0
        private async void MqttServerOnApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs mqttApplicationMessageReceivedEventArgs)
        {
            var message   = mqttApplicationMessageReceivedEventArgs.ApplicationMessage;
            var body      = Encoding.UTF8.GetString(message.Payload);
            var queue     = ServiceLocator.Current.GetService <IMessageQueue>();
            var rootTopic = message.Topic.Split('/').First();

            // simple approach, forward to message queue by root topic
            queue.Enqueue(rootTopic, new QueueMessage(message.Topic, body, null));
            _log.LogTrace("{0}|{1}", message.Topic, body);

            var functionsEngine = ServiceLocator.Current.GetService <FunctionsEngine>();

            lock (_lockObj)
            {
                if (functionsEngine.Functions.All(f => f.Name != rootTopic) && _requestedFunctions.All(f => f != rootTopic))
                {
                    var iotHub = ServiceLocator.Current.GetService <IAzureIoTHubPlugin>();
                    if (String.IsNullOrEmpty(iotHub.ServiceBaseUrl))
                    {
                        return;
                    }

                    string deviceScript   = "";
                    bool   deviceDetected = false;
                    // find out, if the message tells us, which device we have here
                    if (message.Topic.Contains("INFO1") && body.Contains("S20 Socket"))
                    {
                        _log.LogInformation("No function found for topic " + rootTopic + ". Creating function.");
                        deviceScript =
                            @"function run(message)
    print('Key: '..message.Key);
    if(string.match(message.Key, 'stat/POWER') != nil) then
        print('Match!');
        print('Value: '..message.Value);
        message.Tag = 'onoffswitch';
        message.Key = string.gsub(message.Key, '/stat/POWER', '');
        queue.enqueue('iothub', message); --simply forward to iot hub message queue
    end;
    return 0;
end;";
                        var tokenTask = _apiAuthenticationService.GetTokenAsync();
                        Task.WaitAll(tokenTask);
                        var token      = tokenTask.Result;
                        var httpClient = new LocalHttpClient(token);

                        var configuration = new
                        {
                            ChannelType = ChannelType.OnOffSwitch.ToString(),
                            OnOffTopic  = rootTopic + "/cmnd/POWER",
                            OnMessage   = "ON",
                            OffMessage  = "OFF"
                        };
                        string configBody = JsonConvert.SerializeObject(configuration, Formatting.Indented);
                        var    task       = httpClient.Client.PostAsync(iotHub.ServiceBaseUrl + "DeviceConfiguration/" + iotHub.DeviceId + "/" + Name + "/channel:" + rootTopic, new StringContent(configBody, Encoding.UTF8, "application/json"));
                        Task.WaitAll(task);
                        var result = task.Result;
                        if (!result.IsSuccessStatusCode)
                        {
                            _log.LogError("Error creating device configuration: " + result.ReasonPhrase);
                        }
                        deviceDetected = true;
                    }

                    if (deviceDetected) // only create a function if device was detected correctly. TODO create a setting for mqttbrokerplugin whether functions should be created automatically or not.
                    {
                        var tokenTask = _apiAuthenticationService.GetTokenAsync();
                        Task.WaitAll(tokenTask);
                        var token      = tokenTask.Result;
                        var httpClient = new LocalHttpClient(token);

                        var model = new DeviceFunctionModel()
                        {
                            DeviceId    = iotHub.DeviceId,
                            FunctionId  = Guid.NewGuid().ToString(),
                            Name        = rootTopic,
                            TriggerType = FunctionTriggerType.MessageQueue,
                            Interval    = 0,
                            QueueName   = rootTopic,
                            Enabled     = true,
                            Script      = deviceScript
                        };
                        string functionBody = JsonConvert.SerializeObject(model, Formatting.Indented);
                        var    task         = httpClient.Client.PostAsync(iotHub.ServiceBaseUrl + "DeviceFunction/" + iotHub.DeviceId + "/" + Guid.NewGuid().ToString(), new StringContent(functionBody, Encoding.UTF8, "application/json"));
                        Task.WaitAll(task);
                        var result = task.Result;
                        if (result.IsSuccessStatusCode)
                        {
                            _requestedFunctions.Add(rootTopic);
                        }
                        else
                        {
                            _log.LogError("Error creating device function: " + result.ReasonPhrase);
                        }
                    }
                }
            }
        }
 private async Task RunProgram(string programId)
 {
     var httpClient      = new LocalHttpClient();
     var functionContent = await httpClient.Client.GetStringAsync(new Uri(_connectionString + "runprogram.cgi?program_id=" + programId));
 }