Add send action http in device controller

This commit is contained in:
Fransolet Thomas 2022-04-06 18:59:27 +02:00
parent 372cbd3759
commit cf85feb33f
5 changed files with 153 additions and 89 deletions

View File

@ -11,6 +11,8 @@ using MongoDB.Bson;
using Mqtt.Client.AspNetCore.Services; using Mqtt.Client.AspNetCore.Services;
using MyCore.Interfaces.DTO; using MyCore.Interfaces.DTO;
using MyCore.Interfaces.Models; using MyCore.Interfaces.Models;
using MyCore.Service.Controllers.Helpers;
using MyCore.Service.Services;
using MyCore.Services; using MyCore.Services;
using MyCore.Services.Devices; using MyCore.Services.Devices;
using MyCore.Services.MyControlPanel; using MyCore.Services.MyControlPanel;
@ -24,17 +26,21 @@ namespace MyCore.Controllers
{ {
private DeviceDatabaseService _DeviceDatabaseService; private DeviceDatabaseService _DeviceDatabaseService;
private ProviderDatabaseService _ProviderDatabaseService; private ProviderDatabaseService _ProviderDatabaseService;
private GroupDatabaseService _GroupDatabaseService;
private RoomDatabaseService _RoomDatabaseService; private RoomDatabaseService _RoomDatabaseService;
private HomeDatabaseService _HomeDatabaseService; private HomeDatabaseService _HomeDatabaseService;
private AutomationService _automationService;
private readonly IMqttClientService _mqttClientService; private readonly IMqttClientService _mqttClientService;
//private readonly IMqttOnlineClientService _mqttOnlineClientService; //private readonly IMqttOnlineClientService _mqttOnlineClientService;
public DeviceController(DeviceDatabaseService DeviceDatabaseService, ProviderDatabaseService ProviderDatabaseService, RoomDatabaseService RoomDatabaseService, HomeDatabaseService HomeDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) public DeviceController(DeviceDatabaseService DeviceDatabaseService, ProviderDatabaseService ProviderDatabaseService, GroupDatabaseService GroupDatabaseService, RoomDatabaseService RoomDatabaseService, HomeDatabaseService HomeDatabaseService, AutomationService AutomationService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider)
{ {
this._DeviceDatabaseService = DeviceDatabaseService; this._DeviceDatabaseService = DeviceDatabaseService;
this._ProviderDatabaseService = ProviderDatabaseService; this._ProviderDatabaseService = ProviderDatabaseService;
this._GroupDatabaseService = GroupDatabaseService;
this._RoomDatabaseService = RoomDatabaseService; this._RoomDatabaseService = RoomDatabaseService;
this._HomeDatabaseService = HomeDatabaseService; this._HomeDatabaseService = HomeDatabaseService;
this._automationService = AutomationService;
this._mqttClientService = provider.MqttClientService; this._mqttClientService = provider.MqttClientService;
//this._mqttOnlineClientService = onlineProvider.MqttOnlineClientService; //this._mqttOnlineClientService = onlineProvider.MqttOnlineClientService;
} }
@ -175,6 +181,61 @@ namespace MyCore.Controllers
} }
} }
/// <summary>
/// Send action to device
/// </summary>
/// <param name="action">Action to sent</param>
[ProducesResponseType(typeof(string), 202)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost("action")]
public ObjectResult SendAction([FromBody] Interfaces.Models.Action action)
{
try
{
if (action == null)
throw new ArgumentNullException("Incorrect parameters");
if (action.DeviceId == null || action.GroupId == null)
throw new ArgumentNullException("Incorrect parameters");
Device device = null;
Group group = null;
string homeId;
if (action.DeviceId != null) {
device = _DeviceDatabaseService.GetById(action.DeviceId);
homeId= device?.HomeId;
}
else
{
group = _GroupDatabaseService.GetById(action.GroupId);
homeId= group?.HomeId;
}
if (device == null || group == null)
throw new KeyNotFoundException("Device or group does not exist");
AutomationService.HandleAction(homeId, action, _ProviderDatabaseService, _DeviceDatabaseService, _GroupDatabaseService);
return new ObjectResult("Action has been sent successfully") { StatusCode = 202 }; // To test with accepted result
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary> /// <summary>
/// Create devices from provider /// Create devices from provider
/// </summary> /// </summary>

View File

@ -247,7 +247,6 @@ namespace MyCore.Service.Controllers.Helpers
try try
{ {
switch (device.Type) switch (device.Type)
{ {
case DeviceType.Light: case DeviceType.Light:

View File

@ -172,7 +172,7 @@ namespace Mqtt.Client.AspNetCore.Services
lastTopic = topic; lastTopic = topic;
} }
return null; return new Task(null);
} }
public async Task HandleConnectedAsync(MqttClientConnectedEventArgs eventArgs) public async Task HandleConnectedAsync(MqttClientConnectedEventArgs eventArgs)

View File

@ -88,7 +88,6 @@ namespace MyCore.Service.Services
validTrigger = false; validTrigger = false;
} }
if (validTrigger && automationTrigger.StateValue.ToLower() == triggerStateValueCheck.ToString().ToLower()) if (validTrigger && automationTrigger.StateValue.ToLower() == triggerStateValueCheck.ToString().ToLower())
{ {
// Correct trigger ! // Correct trigger !
@ -106,91 +105,7 @@ namespace MyCore.Service.Services
foreach (var action in automation.Actions) foreach (var action in automation.Actions)
{ {
HandleAction(homeId, action, _ProviderDatabaseService, _DeviceDatabaseService, _GroupDatabaseService) ;
var DeviceNameForAction = "";
Device actionDeviceToTest = new Device();
// Retrieve action type
switch (action.Type)
{
case ActionType.DEVICE:
var deviceAction = _DeviceDatabaseService.GetById(action.DeviceId);
var providerActionTest = _ProviderDatabaseService.GetById(homeId, action.ProviderId);
DeviceNameForAction = deviceAction.Name;
actionDeviceToTest = deviceAction;
System.Console.WriteLine($"We get a device action ! Name={deviceAction.Name} Type={deviceAction.Type}");
System.Console.WriteLine($"Check action provider type ! Type={providerActionTest.Type} Name={providerActionTest.Name}");
break;
case ActionType.GROUP:
var groupAction = _GroupDatabaseService.GetById(action.GroupId);
DeviceNameForAction = groupAction.Name;
System.Console.WriteLine($"We get a group action ! Name={groupAction.Name} Type={groupAction.Type}");
System.Console.WriteLine($"Check action zigbeeGroupAction type ! Type={groupAction.Type}");
// Check state of first device of a group
actionDeviceToTest = _DeviceDatabaseService.GetByGroup(groupAction.Id).FirstOrDefault(); // TODO : Send error if no device found !
break;
case ActionType.MQTT:
// take raw request and send it !
RawRequestMQTT rawRequestMQTT = JsonConvert.DeserializeObject<RawRequestMQTT>(action.RawRequest);
if (rawRequestMQTT != null)
{
// SEND REQUEST
System.Console.WriteLine($"Send raw request mqtt! topic:{rawRequestMQTT.topic} - message: {rawRequestMQTT.message}");
MqttClientService.PublishMessage(rawRequestMQTT.topic, rawRequestMQTT.message);
}
break;
case ActionType.HTTP: // Correct way ?
// TODO
break;
}
var providerAction = _ProviderDatabaseService.GetById(homeId, action.ProviderId);
// Check if device exist
if (actionDeviceToTest != null && providerAction != null)
{
switch (providerAction.Type)
{
case ProviderType.zigbee2mqtt:
try
{
DevicesHelper.ActionOnZigbee2Mqtt(actionDeviceToTest, action, DeviceNameForAction);
}
catch (Exception ex)
{
System.Console.WriteLine($"ActionOnZigbee2Mqtt result in error: {ex}");
}
break;
case ProviderType.meross:
try
{
DevicesHelper.ActionOnMeross(_DeviceDatabaseService, actionDeviceToTest, action, DeviceNameForAction);
}
catch (Exception ex)
{
System.Console.WriteLine($"ActionOnMeross result in error: {ex}");
}
break;
case ProviderType.yeelight:
try
{
DevicesHelper.ActionOnYeelight(_DeviceDatabaseService, actionDeviceToTest, action);
}
catch (Exception ex)
{
System.Console.WriteLine($"ActionOnYeelight result in error: {ex}");
}
break;
}
}
else
{
System.Console.WriteLine($"Device or group found in action incorrect");
}
} }
} }
else else
@ -205,6 +120,94 @@ namespace MyCore.Service.Services
} }
} }
public static void HandleAction(string homeId, Interfaces.Models.Action action, ProviderDatabaseService providerDatabaseService, DeviceDatabaseService deviceDatabaseService, GroupDatabaseService groupDatabaseService)
{
var DeviceNameForAction = "";
Device actionDeviceToTest = new Device();
// Retrieve action type
switch (action.Type)
{
case ActionType.DEVICE:
var deviceAction = deviceDatabaseService.GetById(action.DeviceId);
var providerActionTest = providerDatabaseService.GetById(homeId, action.ProviderId);
DeviceNameForAction = deviceAction.Name;
actionDeviceToTest = deviceAction;
System.Console.WriteLine($"We get a device action ! Name={deviceAction.Name} Type={deviceAction.Type}");
System.Console.WriteLine($"Check action provider type ! Type={providerActionTest.Type} Name={providerActionTest.Name}");
break;
case ActionType.GROUP:
var groupAction = groupDatabaseService.GetById(action.GroupId);
DeviceNameForAction = groupAction.Name;
System.Console.WriteLine($"We get a group action ! Name={groupAction.Name} Type={groupAction.Type}");
System.Console.WriteLine($"Check action zigbeeGroupAction type ! Type={groupAction.Type}");
// Check state of first device of a group
actionDeviceToTest = deviceDatabaseService.GetByGroup(groupAction.Id).FirstOrDefault(); // TODO : Send error if no device found !
break;
case ActionType.MQTT:
// take raw request and send it !
RawRequestMQTT rawRequestMQTT = JsonConvert.DeserializeObject<RawRequestMQTT>(action.RawRequest);
if (rawRequestMQTT != null)
{
// SEND REQUEST
System.Console.WriteLine($"Send raw request mqtt! topic:{rawRequestMQTT.topic} - message: {rawRequestMQTT.message}");
MqttClientService.PublishMessage(rawRequestMQTT.topic, rawRequestMQTT.message);
}
break;
case ActionType.HTTP: // Correct way ?
// TODO
break;
}
var providerAction = providerDatabaseService.GetById(homeId, action.ProviderId);
// Check if device exist
if (actionDeviceToTest != null && providerAction != null)
{
switch (providerAction.Type)
{
case ProviderType.zigbee2mqtt:
try
{
DevicesHelper.ActionOnZigbee2Mqtt(actionDeviceToTest, action, DeviceNameForAction);
}
catch (Exception ex)
{
System.Console.WriteLine($"ActionOnZigbee2Mqtt result in error: {ex}");
}
break;
case ProviderType.meross:
try
{
DevicesHelper.ActionOnMeross(deviceDatabaseService, actionDeviceToTest, action, DeviceNameForAction);
}
catch (Exception ex)
{
System.Console.WriteLine($"ActionOnMeross result in error: {ex}");
}
break;
case ProviderType.yeelight:
try
{
DevicesHelper.ActionOnYeelight(deviceDatabaseService, actionDeviceToTest, action);
}
catch (Exception ex)
{
System.Console.WriteLine($"ActionOnYeelight result in error: {ex}");
}
break;
}
}
else
{
System.Console.WriteLine($"Device or group found in action incorrect");
}
}
public static List<bool> CheckConditions(List<Condition> conditions) public static List<bool> CheckConditions(List<Condition> conditions)
{ {
var isConditionsRespected = conditions.Count <= 0 ? new List<bool>() { true } : new List<bool>(new bool[conditions.Count]); var isConditionsRespected = conditions.Count <= 0 ? new List<bool>() { true } : new List<bool>(new bool[conditions.Count]);

View File

@ -161,6 +161,7 @@ namespace MyCore
services.AddScoped<RoomDatabaseService>(); services.AddScoped<RoomDatabaseService>();
services.AddScoped<AutomationDatabaseService>(); services.AddScoped<AutomationDatabaseService>();
services.AddScoped<ActionService>(); services.AddScoped<ActionService>();
services.AddScoped<AutomationService>();
services.AddScoped<AlarmDatabaseService>(); services.AddScoped<AlarmDatabaseService>();
services.AddScoped<EventDatabaseService>(); services.AddScoped<EventDatabaseService>();