private async Task <DeviceFunctionModel> LoadFunctionFromStorageAsync(string functionId) { // first try to load the function file from the LocalFolder var localStorage = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var filePath = Path.Combine(localStorage, "function_" + functionId + ".json"); DeviceFunctionModel function = null; if (File.Exists(filePath)) // file exists, continue to deserialize into actual object { // local file content var configFileContent = File.ReadAllText(filePath); function = JsonConvert.DeserializeObject <DeviceFunctionModel>(configFileContent); if (function == null) { _log.LogError("Invalid function file for function " + functionId); return(function); } } else { _log.LogError("Function file not found for function " + functionId); return(function); } return(function); }
public async Task <IActionResult> CreateNew(string deviceId, string functionId, [FromBody] DeviceFunctionModel functionModel) { await _deviceFunctionService.SaveFunctionAsync(deviceId, functionId, functionModel.Name, functionModel.TriggerType.ToString(), functionModel.Interval, functionModel.CronSchedule, functionModel.QueueName, functionModel.Enabled, functionModel.Script); await _deviceManagementService.UpdateFunctionsAndVersionsTwinPropertyAsync(deviceId); return(Ok()); }
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); } } } } }