From 479ef5784d7da436f922ad3c2a9ebf35d7819045 Mon Sep 17 00:00:00 2001 From: Thomas Fransolet Date: Fri, 5 Nov 2021 09:38:04 +0100 Subject: [PATCH] Updated version - include scoped services in mqtt service + fix bugs for group (groupIds update for device) + add Home Id + Home controller + Alarm controller (wip) + remove location and place => Room (and RoomId for device) --- .../DTO/MyControlPanel/AlarmModeDTO.cs | 21 ++ .../DTO/MyControlPanel/AutomationDTO.cs | 2 +- .../DTO/MyControlPanel/DeviceDTO.cs | 6 +- .../DTO/MyControlPanel/GroupDTO.cs | 2 +- .../DTO/MyControlPanel/HomeDTO.cs | 40 +++ .../DTO/MyControlPanel/PlaceDTO.cs | 16 -- .../DTO/MyControlPanel/ProviderDTO.cs | 7 +- .../DTO/MyControlPanel/RoomDTO.cs | 2 +- .../MyControlPanel/Database/AlarmMode.cs | 55 ++++ .../MyControlPanel/Database/Automation.cs | 11 +- .../Models/MyControlPanel/Database/Device.cs | 16 +- .../Models/MyControlPanel/Database/Group.cs | 12 +- .../Models/MyControlPanel/Database/Home.cs | 94 +++++++ .../Models/MyControlPanel/Database/Place.cs | 29 -- .../MyControlPanel/Database/Provider.cs | 16 +- .../Models/MyControlPanel/Database/Room.cs | 8 +- .../MyControlPanel/Database/UserInfo.cs | 21 +- .../IoThomas/Energy/ElectricityProduction.cs | 4 +- .../Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs | 16 ++ MyCore.Interfaces/MyCore.Interfaces.csproj | 1 + MyCore/Controllers/AlarmController.cs | 40 +++ .../Controllers/AuthenticationController.cs | 9 +- MyCore/Controllers/AutomationController.cs | 38 +-- .../Controllers/Devices/DeviceController.cs | 104 ++++---- .../Devices/IoThomas/EnergyController.cs | 8 +- .../Controllers/Devices/ProviderController.cs | 50 ++-- MyCore/Controllers/GroupController.cs | 82 +++--- MyCore/Controllers/HomeController.cs | 251 ++++++++++++++++++ .../MyControlPanel/UserController.cs | 7 +- MyCore/Controllers/RoomController.cs | 53 ++-- MyCore/Extensions/MqttClientService.cs | 171 ++++++++++-- .../Extensions/ServiceCollectionExtension.cs | 12 +- MyCore/Services/AutomationService.cs | 5 +- MyCore/Services/Devices/ActionService.cs | 163 +++++------- MyCore/Services/Devices/DeviceService.cs | 190 +++++++++---- .../Devices/IoThomas/EnergyService.cs | 24 +- MyCore/Services/GroupService.cs | 22 +- .../Database/AlarmDatabaseService.cs | 58 ++++ .../Database/AutomationDatabaseService.cs | 15 +- .../Database/DeviceDatabaseService.cs | 27 +- .../Database/GroupDatabaseService.cs | 19 +- .../Database/HomeDatabaseService.cs | 54 ++++ .../Database/LocationDatabaseService.cs | 53 ---- .../Database/ProviderDatabaseService.cs | 21 +- .../Database/RoomDatabaseService.cs | 10 +- .../Database/UserDatabaseService.cs | 20 +- MyCore/Services/MyControlPanel/HomeService.cs | 46 ++++ .../MyControlPanel/ProviderService.cs | 39 +-- MyCore/Services/MyControlPanel/UserService.cs | 16 -- MyCore/Services/RoomService.cs | 9 +- MyCore/Startup.cs | 22 +- 51 files changed, 1400 insertions(+), 617 deletions(-) create mode 100644 MyCore.Interfaces/DTO/MyControlPanel/AlarmModeDTO.cs create mode 100644 MyCore.Interfaces/DTO/MyControlPanel/HomeDTO.cs delete mode 100644 MyCore.Interfaces/DTO/MyControlPanel/PlaceDTO.cs create mode 100644 MyCore.Interfaces/Models/MyControlPanel/Database/AlarmMode.cs create mode 100644 MyCore.Interfaces/Models/MyControlPanel/Database/Home.cs delete mode 100644 MyCore.Interfaces/Models/MyControlPanel/Database/Place.cs create mode 100644 MyCore/Controllers/AlarmController.cs create mode 100644 MyCore/Controllers/HomeController.cs create mode 100644 MyCore/Services/MyControlPanel/Database/AlarmDatabaseService.cs create mode 100644 MyCore/Services/MyControlPanel/Database/HomeDatabaseService.cs delete mode 100644 MyCore/Services/MyControlPanel/Database/LocationDatabaseService.cs create mode 100644 MyCore/Services/MyControlPanel/HomeService.cs delete mode 100644 MyCore/Services/MyControlPanel/UserService.cs diff --git a/MyCore.Interfaces/DTO/MyControlPanel/AlarmModeDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/AlarmModeDTO.cs new file mode 100644 index 0000000..642d560 --- /dev/null +++ b/MyCore.Interfaces/DTO/MyControlPanel/AlarmModeDTO.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace MyCore.Interfaces.DTO +{ + /// + /// Alarm mode DTO + /// + public class AlarmModeDTO + { + public string Id { get; set; } + public string HomeId { get; set; } + public string Name { get; set; } + public bool IsDefault { get; set; } + public DateTime CreatedDate { get; set; } + public DateTime UpdatedDate { get; set; } + public List DevicesIds { get; set; } // Check if ok + } +} diff --git a/MyCore.Interfaces/DTO/MyControlPanel/AutomationDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/AutomationDTO.cs index ad0fa8e..51af82e 100644 --- a/MyCore.Interfaces/DTO/MyControlPanel/AutomationDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/AutomationDTO.cs @@ -11,7 +11,7 @@ namespace MyCore.Interfaces.DTO public string Id { get; set; } public string Name { get; set; } public bool Active { get; set; } - public string UserId { get; set; } + public string HomeId { get; set; } public DateTime CreatedDate { get; set; } public DateTime UpdatedDate { get; set; } } diff --git a/MyCore.Interfaces/DTO/MyControlPanel/DeviceDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/DeviceDTO.cs index edc02f0..12499ed 100644 --- a/MyCore.Interfaces/DTO/MyControlPanel/DeviceDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/DeviceDTO.cs @@ -9,7 +9,7 @@ namespace MyCore.Interfaces.DTO { public string Id { get; set; } - public string UserId { get; set; } + public string HomeId { get; set; } public string Description { get; set; } @@ -23,14 +23,12 @@ namespace MyCore.Interfaces.DTO public ConnectionStatus ConnectionStatus { get; set; } - public string LocationId { get; set; } + public string RoomId { get; set; } public string ProviderId { get; set; } public string ProviderName { get; set; } - public PlaceDTO Location { get; set; } - public DateTime LastStateDate { get; set; } public bool Battery { get; set; } diff --git a/MyCore.Interfaces/DTO/MyControlPanel/GroupDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/GroupDTO.cs index aebe437..14e519b 100644 --- a/MyCore.Interfaces/DTO/MyControlPanel/GroupDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/GroupDTO.cs @@ -8,7 +8,7 @@ namespace MyCore.Interfaces.DTO public class GroupSummaryDTO { public string Id { get; set; } - public string UserId { get; set; } + public string HomeId { get; set; } public string Name { get; set; } public string Type { get; set; } public bool IsAlarm { get; set; } diff --git a/MyCore.Interfaces/DTO/MyControlPanel/HomeDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/HomeDTO.cs new file mode 100644 index 0000000..8ff5b57 --- /dev/null +++ b/MyCore.Interfaces/DTO/MyControlPanel/HomeDTO.cs @@ -0,0 +1,40 @@ +using MyCore.Interfaces.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace MyCore.Interfaces.DTO +{ + /// + /// Home DTO + /// + public class HomeDTO + { + public string Id { get; set; } + public string Name { get; set; } + public bool IsAlarm { get; set; } + public bool IsDefault { get; set; } + public AlarmModeDTO CurrentAlarmMode { get; set; } + public DateTime CreatedDate { get; set; } + public DateTime UpdatedDate { get; set; } + public List UsersIds { get; set; } + } + + public class HomeDetailDTO : HomeDTO + { + + public List Users { get; set; } + public List Devices { get; set; } + public List Automations { get; set; } + public List Providers { get; set; } + public List Groups { get; set; } + //public List ScreenConfigurations { get; set; } TODO + //public List ScreenDevices { get; set; } TODO + } + + public class CreateOrUpdateHomeDTO : HomeDTO + { + public List UsersIds { get; set; } + } +} diff --git a/MyCore.Interfaces/DTO/MyControlPanel/PlaceDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/PlaceDTO.cs deleted file mode 100644 index 79e3060..0000000 --- a/MyCore.Interfaces/DTO/MyControlPanel/PlaceDTO.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace MyCore.Interfaces.DTO -{ - /// - /// Place DTO - /// - public class PlaceDTO - { - public string Id { get; set; } - public string Name { get; set; } - } -} diff --git a/MyCore.Interfaces/DTO/MyControlPanel/ProviderDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/ProviderDTO.cs index 13cda7d..30e92f3 100644 --- a/MyCore.Interfaces/DTO/MyControlPanel/ProviderDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/ProviderDTO.cs @@ -1,4 +1,5 @@ -using System; +using MyCore.Interfaces.Models; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -9,8 +10,8 @@ namespace MyCore.Interfaces.DTO { public string Id { get; set; } public string Name { get; set; } - public string Type { get; set; } - public string UserId { get; set; } + public ProviderType Type { get; set; } + public string HomeId { get; set; } public string Endpoint { get; set; } public string Username { get; set; } public string Password { get; set; } // TODO ENCRYPTED diff --git a/MyCore.Interfaces/DTO/MyControlPanel/RoomDTO.cs b/MyCore.Interfaces/DTO/MyControlPanel/RoomDTO.cs index ca2b686..f6e7a37 100644 --- a/MyCore.Interfaces/DTO/MyControlPanel/RoomDTO.cs +++ b/MyCore.Interfaces/DTO/MyControlPanel/RoomDTO.cs @@ -9,7 +9,7 @@ namespace MyCore.Interfaces.DTO { public string Id { get; set; } - public string UserId { get; set; } + public string HomeId { get; set; } public string Name { get; set; } } diff --git a/MyCore.Interfaces/Models/MyControlPanel/Database/AlarmMode.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/AlarmMode.cs new file mode 100644 index 0000000..ec6d5c6 --- /dev/null +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/AlarmMode.cs @@ -0,0 +1,55 @@ +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace MyCore.Interfaces.Models +{ + /// + /// Group of alarms + /// + public class AlarmMode + { + [BsonId] + [BsonRepresentation(BsonType.ObjectId)] + public string Id { get; set; } + + [BsonElement("HomeId")] + [BsonRequired] + public string HomeId { get; set; } + + [BsonElement("Name")] + [BsonRequired] + public string Name { get; set; } + + [BsonElement("IsDefault")] + [BsonRequired] + public bool IsDefault { get; set; } + + [BsonElement("CreatedDate")] + public DateTime CreatedDate { get; set; } + + [BsonElement("UpdatedDate")] + public DateTime UpdatedDate { get; set; } + + [BsonElement("DevicesIds")] + public List DevicesIds { get; set; } + + public AlarmModeDTO ToDTO() + { + return new AlarmModeDTO() + { + Id = Id, + HomeId = HomeId, + Name = Name, + IsDefault = IsDefault, + CreatedDate = CreatedDate, + UpdatedDate = UpdatedDate, + DevicesIds = DevicesIds, + }; + } + } +} diff --git a/MyCore.Interfaces/Models/MyControlPanel/Database/Automation.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Automation.cs index c524173..4ed2a38 100644 --- a/MyCore.Interfaces/Models/MyControlPanel/Database/Automation.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Automation.cs @@ -15,9 +15,9 @@ namespace MyCore.Interfaces.Models [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } - [BsonElement("UserId")] + [BsonElement("HomeId")] [BsonRequired] - public string UserId { get; set; } + public string HomeId { get; set; } [BsonElement("Name")] [BsonRequired] @@ -52,7 +52,7 @@ namespace MyCore.Interfaces.Models Id = Id, Name = Name, Active = Active, - UserId = UserId, + HomeId = HomeId, CreatedDate = CreatedDate, UpdatedDate = UpdatedDate, //Triggers = Triggers @@ -68,7 +68,7 @@ namespace MyCore.Interfaces.Models Id = Id, Name = Name, Active = Active, - UserId = UserId, + HomeId = HomeId, CreatedDate = CreatedDate, UpdatedDate = UpdatedDate, Triggers = Triggers, @@ -128,7 +128,8 @@ namespace MyCore.Interfaces.Models public List States { get; set; } public string RawRequest { get; set; } // http, mqtt public string ProviderId { get; set; } - public ActionType Type { get; set; } + public ActionType Type { get; set; } + public bool IsForce { get; set; } } public class RawRequestMQTT{ diff --git a/MyCore.Interfaces/Models/MyControlPanel/Database/Device.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Device.cs index 8df7a00..fa65db1 100644 --- a/MyCore.Interfaces/Models/MyControlPanel/Database/Device.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Device.cs @@ -17,9 +17,9 @@ namespace MyCore.Interfaces.Models [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } - [BsonElement("UserId")] + [BsonElement("HomeId")] [BsonRequired] - public string UserId { get; set; } + public string HomeId { get; set; } [BsonElement("Name")] [BsonRequired] @@ -52,8 +52,8 @@ namespace MyCore.Interfaces.Models [BsonElement("ConnectionStatus")] public ConnectionStatus ConnectionStatus { get; set; } - [BsonElement("LocationId")] - public string LocationId { get; set; } + [BsonElement("RoomId")] + public string RoomId { get; set; } [BsonElement("MeansOfCommunications")] public List MeansOfCommunications { get; set; } @@ -104,14 +104,14 @@ namespace MyCore.Interfaces.Models return new DeviceSummaryDTO() { Id = Id, - UserId = UserId, + HomeId = HomeId, Name = Name, Model = Model, Type = Type, Status = Status, ConnectionStatus = ConnectionStatus, ProviderId = ProviderId, - LocationId = LocationId, // Include room id + RoomId = RoomId, // Include room id LastStateDate = LastStateDate, Battery = Battery, BatteryStatus = BatteryStatus @@ -123,7 +123,7 @@ namespace MyCore.Interfaces.Models return new DeviceDetailDTO() { Id = Id, - UserId = UserId, + HomeId = HomeId, Name = Name, Model = Model, Type = Type, @@ -131,7 +131,7 @@ namespace MyCore.Interfaces.Models Port = Port, FirmwareVersion = FirmwareVersion, ConnectionStatus = ConnectionStatus, - LocationId = LocationId, // Include room id + RoomId = RoomId, // Include room id MeansOfCommunications = MeansOfCommunications, CreatedDate = CreatedDate, UpdatedDate = UpdatedDate, diff --git a/MyCore.Interfaces/Models/MyControlPanel/Database/Group.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Group.cs index e1eb4af..de92c3c 100644 --- a/MyCore.Interfaces/Models/MyControlPanel/Database/Group.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Group.cs @@ -14,9 +14,9 @@ namespace MyCore.Interfaces.Models [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } - [BsonElement("UserId")] + [BsonElement("HomeId")] [BsonRequired] - public string UserId { get; set; } + public string HomeId { get; set; } [BsonElement("Name")] [BsonRequired] @@ -49,10 +49,9 @@ namespace MyCore.Interfaces.Models return new GroupSummaryDTO() { Id = Id, - UserId = UserId, + HomeId = HomeId, Name = Name, - Type = Type, - IsAlarm = IsAlarm + Type = Type }; } @@ -61,10 +60,9 @@ namespace MyCore.Interfaces.Models return new GroupDetailDTO() { Id = Id, - UserId = UserId, + HomeId = HomeId, Name = Name, Type = Type, - IsAlarm = IsAlarm, CreatedDate = CreatedDate, UpdatedDate = UpdatedDate, Devices = devicesDetail diff --git a/MyCore.Interfaces/Models/MyControlPanel/Database/Home.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Home.cs new file mode 100644 index 0000000..73aa177 --- /dev/null +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Home.cs @@ -0,0 +1,94 @@ +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using MyCore.Interfaces.DTO; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace MyCore.Interfaces.Models +{ + /// + /// Home (list of devices, list of users, main element of a house) + /// + public class Home + { + [BsonId] + [BsonRepresentation(BsonType.ObjectId)] + public string Id { get; set; } + + [BsonElement("Name")] + [BsonRequired] + public string Name { get; set; } + + [BsonElement("IsDefault")] + [BsonRequired] + public bool IsDefault { get; set; } + + [BsonElement("IsAlarm")] + public bool IsAlarm { get; set; } + + [BsonElement("CurrentAlarmMode")] + public AlarmMode CurrentAlarmMode { get; set; } + + [BsonElement("CreatedDate")] + public DateTime CreatedDate { get; set; } + + [BsonElement("UpdatedDate")] + public DateTime UpdatedDate { get; set; } + + [BsonElement("UsersIds")] + public string[] UsersIds { get; set; } + + /*[BsonElement("Automations")] + public Automation[] Automations { get; set; } + + [BsonElement("Devices")] + public Device[] Devices { get; set; } + + [BsonElement("Providers")] + public Provider[] Providers { get; set; } + + [BsonElement("Groups")] + public Group[] Groups { get; set; } + + [BsonElement("ScreenConfigurationIds")] + public ScreenConfiguration[] ScreenConfigurations { get; set; } + + [BsonElement("DeviceIds")] + public ScreenDevice[] DeviceIds { get; set; }*/ + + public HomeDTO ToDTO() + { + return new HomeDTO() + { + Id = Id, + Name = Name, + IsAlarm = IsAlarm, + IsDefault = IsDefault, + CurrentAlarmMode = CurrentAlarmMode != null ? CurrentAlarmMode.ToDTO(): null, + UsersIds = UsersIds.ToList(), + CreatedDate = CreatedDate, + UpdatedDate = UpdatedDate + }; + } + + public HomeDetailDTO ToDetailDTO(List users, List devices, List automations, List providers, List groups) + { + return new HomeDetailDTO() + { + Id = Id, + Name = Name, + Users = users.Select(u => u.ToDTO()).ToList(), + IsAlarm = IsAlarm, + IsDefault = IsDefault, + CurrentAlarmMode = CurrentAlarmMode.ToDTO(), + CreatedDate = CreatedDate, + UpdatedDate = UpdatedDate, + Devices = devices.Select(d => d.ToSummaryDTO()).ToList(), + Automations = automations.Select(a => a.ToDTO()).ToList(), + Providers = providers.Select(p => p.ToDTO()).ToList(), + Groups = groups.Select(g => g.ToSummaryDTO()).ToList(), + }; + } + } +} \ No newline at end of file diff --git a/MyCore.Interfaces/Models/MyControlPanel/Database/Place.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Place.cs deleted file mode 100644 index ca5b8f8..0000000 --- a/MyCore.Interfaces/Models/MyControlPanel/Database/Place.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using MyCore.Interfaces.DTO; - -namespace MyCore.Interfaces.Models -{ - /// - /// Location of a device (Room name, garden, ..) - /// - public class Place - { - [BsonId] - [BsonRepresentation(BsonType.ObjectId)] - public string Id { get; set; } - - [BsonElement("Name")] - [BsonRequired] - public string Name { get; set; } - - public PlaceDTO ToDTO() - { - return new PlaceDTO() - { - Id = Id, - Name = Name - }; - } - } -} \ No newline at end of file diff --git a/MyCore.Interfaces/Models/MyControlPanel/Database/Provider.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Provider.cs index b8cb0fe..00e4629 100644 --- a/MyCore.Interfaces/Models/MyControlPanel/Database/Provider.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Provider.cs @@ -15,9 +15,9 @@ namespace MyCore.Interfaces.Models [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } - [BsonElement("UserId")] + [BsonElement("HomeId")] [BsonRequired] - public string UserId { get; set; } + public string HomeId { get; set; } [BsonElement("Name")] [BsonRequired] @@ -25,7 +25,7 @@ namespace MyCore.Interfaces.Models [BsonElement("Type")] [BsonRequired] - public string Type { get; set; } + public ProviderType Type { get; set; } [BsonElement("Username")] [BsonRequired] @@ -57,7 +57,7 @@ namespace MyCore.Interfaces.Models Id = Id, Type = Type, Name = Name, - UserId = UserId, + HomeId = HomeId, Endpoint = Endpoint, /*Username = Username, Password = Password, @@ -66,4 +66,12 @@ namespace MyCore.Interfaces.Models }; } } + + public enum ProviderType + { + arlo, + meross, + yeelight, + zigbee2mqtt + } } diff --git a/MyCore.Interfaces/Models/MyControlPanel/Database/Room.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/Room.cs index 259a2bb..d546af3 100644 --- a/MyCore.Interfaces/Models/MyControlPanel/Database/Room.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/Room.cs @@ -17,9 +17,9 @@ namespace MyCore.Interfaces.Models [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } - [BsonElement("UserId")] + [BsonElement("HomeId")] [BsonRequired] - public string UserId { get; set; } + public string HomeId { get; set; } [BsonElement("Name")] [BsonRequired] @@ -39,7 +39,7 @@ namespace MyCore.Interfaces.Models return new RoomSummaryDTO() { Id = Id, - UserId = UserId, + HomeId = HomeId, Name = Name }; } @@ -49,7 +49,7 @@ namespace MyCore.Interfaces.Models return new RoomDetailDTO() { Id = Id, - UserId = UserId, + HomeId = HomeId, Name = Name, CreatedDate = CreatedDate, UpdatedDate = UpdatedDate, diff --git a/MyCore.Interfaces/Models/MyControlPanel/Database/UserInfo.cs b/MyCore.Interfaces/Models/MyControlPanel/Database/UserInfo.cs index dde280e..575f38d 100644 --- a/MyCore.Interfaces/Models/MyControlPanel/Database/UserInfo.cs +++ b/MyCore.Interfaces/Models/MyControlPanel/Database/UserInfo.cs @@ -44,6 +44,9 @@ namespace MyCore.Interfaces.Models [BsonElement("Birthday")] public DateTime Birthday { get; set; } + [BsonElement("HomeIds")] + public List HomeIds { get; set; } + [BsonElement("DateCreation")] public DateTime DateCreation { get; set; } @@ -69,24 +72,6 @@ namespace MyCore.Interfaces.Models [BsonElement("PostalCode")] public int PostalCode { get; set; } - [BsonElement("Automations")] - public Automation[] Automations { get; set; } - - [BsonElement("Devices")] - public Device[] Devices { get; set; } - - [BsonElement("Providers")] - public Provider[] Providers { get; set; } - - [BsonElement("Groups")] - public Group[] Groups { get; set; } - - [BsonElement("ScreenConfigurationIds")] - public ScreenConfiguration[] ScreenConfigurationIds { get; set; } - - [BsonElement("DeviceIds")] - public ScreenDevice[] DeviceIds { get; set; } - public UserInfoDetailDTO ToDTO() { return new UserInfoDetailDTO() diff --git a/MyCore.Interfaces/Models/Providers/IoThomas/Energy/ElectricityProduction.cs b/MyCore.Interfaces/Models/Providers/IoThomas/Energy/ElectricityProduction.cs index 105d3b7..3f55598 100644 --- a/MyCore.Interfaces/Models/Providers/IoThomas/Energy/ElectricityProduction.cs +++ b/MyCore.Interfaces/Models/Providers/IoThomas/Energy/ElectricityProduction.cs @@ -16,8 +16,8 @@ namespace MyCore.Interfaces.Models [BsonElement("DeviceId")] public string DeviceId { get; set; } - [BsonElement("UserId")] - public string UserId { get; set; } + [BsonElement("HomeId")] + public string HomeId { get; set; } [BsonElement("Watt")] public double Watt { get; set; } diff --git a/MyCore.Interfaces/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs b/MyCore.Interfaces/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs index 75bce7b..f2c325a 100644 --- a/MyCore.Interfaces/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs +++ b/MyCore.Interfaces/Models/Providers/Zigbee/Zigbee2Mqtt/Zigbee2MqttDevice.cs @@ -24,6 +24,22 @@ namespace MyCore.Interfaces.Models public string dateCode { get; set; } public long lastSeen { get; set; } }*/ + public class Zigbee2MqttDeviceConfig + { + public string description { get; set; } + public string dateCode { get; set; } + public string friendly_name { get; set; } + public string ieeeAddr { get; set; } + public long lastSeen { get; set; } + public string manufacturerID { get; set; } + public string manufacturerName { get; set; } + public string model { get; set; } + public string modelID { get; set; } + public string type { get; set; } + public int networkAddress { get; set; } + public string powerSource { get; set; } + public string vendor { get; set; } + } public class Zigbee2MqttDevice { diff --git a/MyCore.Interfaces/MyCore.Interfaces.csproj b/MyCore.Interfaces/MyCore.Interfaces.csproj index 6df2fe4..e7726d8 100644 --- a/MyCore.Interfaces/MyCore.Interfaces.csproj +++ b/MyCore.Interfaces/MyCore.Interfaces.csproj @@ -5,6 +5,7 @@ + diff --git a/MyCore/Controllers/AlarmController.cs b/MyCore/Controllers/AlarmController.cs new file mode 100644 index 0000000..250a110 --- /dev/null +++ b/MyCore/Controllers/AlarmController.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Security.Authentication; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using MongoDB.Bson; +using Mqtt.Client.AspNetCore.Services; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; +using MyCore.Services; +using MyCore.Services.Devices; +using MyCore.Services.MyControlPanel; + +namespace MyCore.Service.Controllers +{ + [Authorize] // TODO Add ROLES (Roles = "Admin") + [Route("api/alarm")] + [ApiController] + public class AlarmController : ControllerBase + { + private UserDatabaseService _UserDatabaseService; + private RoomDatabaseService _RoomDatabaseService; + private DeviceDatabaseService _DeviceDatabaseService; + private readonly IMqttClientService _mqttClientService; + //private readonly IMqttOnlineClientService _mqttOnlineClientService; + + public AlarmController(UserDatabaseService userDatabaseService, RoomDatabaseService roomDatabaseService, DeviceDatabaseService deviceDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) + { + this._UserDatabaseService = userDatabaseService; + this._RoomDatabaseService = roomDatabaseService; + this._DeviceDatabaseService = deviceDatabaseService; + this._mqttClientService = provider.MqttClientService; + //this._mqttOnlineClientService = onlineProvider.MqttOnlineClientService; + } + } +} diff --git a/MyCore/Controllers/AuthenticationController.cs b/MyCore/Controllers/AuthenticationController.cs index c583041..94d703d 100644 --- a/MyCore/Controllers/AuthenticationController.cs +++ b/MyCore/Controllers/AuthenticationController.cs @@ -31,21 +31,21 @@ namespace MyCore.Service.Controllers private readonly DeviceDatabaseService _DeviceDatabaseService; private readonly GroupDatabaseService _GroupDatabaseService; private readonly ProviderDatabaseService _ProviderDatabaseService; - private readonly LocationDatabaseService _LocationDatabaseService; + private readonly RoomDatabaseService _RoomDatabaseService; private readonly UserDatabaseService _UserDatabaseService; private readonly ActionService _ActionService; private readonly AutomationDatabaseService _AutomationDatabaseService; private readonly IMqttClientService _mqttClientService; //private readonly IMqttOnlineClientService _mqttOnlineClientService; - public AuthenticationController(ILogger logger, TokensService tokensService, DeviceDatabaseService DeviceDatabaseService, GroupDatabaseService GroupDatabaseService, ProviderDatabaseService ProviderDatabaseService, LocationDatabaseService LocationDatabaseService, UserDatabaseService UserDatabaseService, ActionService ActionService, AutomationDatabaseService AutomationDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) + public AuthenticationController(ILogger logger, TokensService tokensService, DeviceDatabaseService DeviceDatabaseService, GroupDatabaseService GroupDatabaseService, ProviderDatabaseService ProviderDatabaseService, RoomDatabaseService RoomDatabaseService, UserDatabaseService UserDatabaseService, ActionService ActionService, AutomationDatabaseService AutomationDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) { _logger = logger; _tokensService = tokensService; _DeviceDatabaseService = DeviceDatabaseService; _GroupDatabaseService = GroupDatabaseService; _ProviderDatabaseService = ProviderDatabaseService; - _LocationDatabaseService = LocationDatabaseService; + _RoomDatabaseService = RoomDatabaseService; _UserDatabaseService = UserDatabaseService; _ActionService = ActionService; _AutomationDatabaseService = AutomationDatabaseService; @@ -74,8 +74,7 @@ namespace MyCore.Service.Controllers if (user == null) throw new KeyNotFoundException("User not found"); - System.Console.WriteLine($"Init userId for MqttClientService ! {user.Email}"); - MqttClientService.SetServices(_DeviceDatabaseService, _GroupDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, _ActionService, _AutomationDatabaseService, user.Id); + System.Console.WriteLine($"{user.Email} is connected"); return new OkObjectResult(token); } diff --git a/MyCore/Controllers/AutomationController.cs b/MyCore/Controllers/AutomationController.cs index cebfe00..5578d89 100644 --- a/MyCore/Controllers/AutomationController.cs +++ b/MyCore/Controllers/AutomationController.cs @@ -23,31 +23,31 @@ namespace MyCore.Service.Controllers [ApiController] public class AutomationController : ControllerBase { - private UserDatabaseService _UserDatabaseService; + private HomeDatabaseService _HomeDatabaseService; private AutomationDatabaseService _AutomationDatabaseService; private readonly IMqttClientService _mqttClientService; //private readonly IMqttOnlineClientService _mqttOnlineClientService; - public AutomationController(UserDatabaseService userDatabaseService, AutomationDatabaseService automationDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) + public AutomationController(HomeDatabaseService homeDatabaseService, AutomationDatabaseService automationDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) { - this._UserDatabaseService = userDatabaseService; + this._HomeDatabaseService = homeDatabaseService; this._AutomationDatabaseService = automationDatabaseService; this._mqttClientService = provider.MqttClientService; //this._mqttOnlineClientService = onlineProvider.MqttOnlineClientService; } /// - /// Get all automations for the specified user + /// Get all automations for the specified home /// - /// Id of user + /// Home Id [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("{userId}")] - public ObjectResult GetAll(string userId) + [HttpGet("{homeId}")] + public ObjectResult GetAll(string homeId) { try { - List Automations = _AutomationDatabaseService.GetAll(userId); + List Automations = _AutomationDatabaseService.GetAll(homeId); List automationDTO = Automations.Select(d => d.ToDTO()).ToList(); @@ -112,7 +112,7 @@ namespace MyCore.Service.Controllers if (automationCreateOrUpdateDetail == null) throw new ArgumentNullException("Incorrect parameters"); - AutomationDTO automationCreated = AutomationService.CreateOrUpdate(this._AutomationDatabaseService, automationCreateOrUpdateDetail.UserId, automationCreateOrUpdateDetail, true); + AutomationDTO automationCreated = AutomationService.CreateOrUpdate(this._AutomationDatabaseService, automationCreateOrUpdateDetail.HomeId, automationCreateOrUpdateDetail, true); return new OkObjectResult(automationCreated); } @@ -146,7 +146,7 @@ namespace MyCore.Service.Controllers if (!_AutomationDatabaseService.IsExist(automationCreateOrUpdateDetail.Id)) throw new KeyNotFoundException("Automation does not exist"); - AutomationDTO automationUpdated = AutomationService.CreateOrUpdate(this._AutomationDatabaseService, automationCreateOrUpdateDetail.UserId, automationCreateOrUpdateDetail, false); + AutomationDTO automationUpdated = AutomationService.CreateOrUpdate(this._AutomationDatabaseService, automationCreateOrUpdateDetail.HomeId, automationCreateOrUpdateDetail, false); return new OkObjectResult(automationUpdated); } @@ -202,27 +202,27 @@ namespace MyCore.Service.Controllers } /// - /// Delete all automation for a specified + /// Delete all automation for a specified home /// - /// Id of user + /// Home Id [ProducesResponseType(typeof(string), 202)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpDelete("user/{userId}")] - public ObjectResult DeleteAllForUser(string userId) + [HttpDelete("home/{homeId}")] + public ObjectResult DeleteAllForHome(string homeId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Incorrect parameters"); - if (!_UserDatabaseService.IsExist(userId)) - throw new KeyNotFoundException("User does not exist"); + if (!_HomeDatabaseService.IsExist(homeId)) + throw new KeyNotFoundException("Home does not exist"); - _AutomationDatabaseService.RemoveForUser(userId); + _AutomationDatabaseService.RemoveForHome(homeId); - return new ObjectResult("All automation linked with specified user has been successfully deleted") { StatusCode = 202 }; + return new ObjectResult("All automation linked with specified home has been successfully deleted") { StatusCode = 202 }; } catch (ArgumentNullException ex) { diff --git a/MyCore/Controllers/Devices/DeviceController.cs b/MyCore/Controllers/Devices/DeviceController.cs index 93eb4f2..4ad142a 100644 --- a/MyCore/Controllers/Devices/DeviceController.cs +++ b/MyCore/Controllers/Devices/DeviceController.cs @@ -24,17 +24,17 @@ namespace MyCore.Controllers { private DeviceDatabaseService _DeviceDatabaseService; private ProviderDatabaseService _ProviderDatabaseService; - private LocationDatabaseService _LocationDatabaseService; - private UserDatabaseService _UserDatabaseService; + private RoomDatabaseService _RoomDatabaseService; + private HomeDatabaseService _HomeDatabaseService; private readonly IMqttClientService _mqttClientService; //private readonly IMqttOnlineClientService _mqttOnlineClientService; - public DeviceController(DeviceDatabaseService DeviceDatabaseService, ProviderDatabaseService ProviderDatabaseService, LocationDatabaseService LocationDatabaseService, UserDatabaseService UserDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) + public DeviceController(DeviceDatabaseService DeviceDatabaseService, ProviderDatabaseService ProviderDatabaseService, RoomDatabaseService RoomDatabaseService, HomeDatabaseService HomeDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) { this._DeviceDatabaseService = DeviceDatabaseService; this._ProviderDatabaseService = ProviderDatabaseService; - this._LocationDatabaseService = LocationDatabaseService; - this._UserDatabaseService = UserDatabaseService; + this._RoomDatabaseService = RoomDatabaseService; + this._HomeDatabaseService = HomeDatabaseService; this._mqttClientService = provider.MqttClientService; //this._mqttOnlineClientService = onlineProvider.MqttOnlineClientService; } @@ -42,21 +42,21 @@ namespace MyCore.Controllers /// /// Get all devices summary /// - /// Id of user + /// Home Id [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("{userId}")] - public ObjectResult GetAll(string userId) + [HttpGet("{homeId}")] + public ObjectResult GetAll(string homeId) { try { - List Devices = _DeviceDatabaseService.GetAll(userId); + List Devices = _DeviceDatabaseService.GetAll(homeId); List devicesSummaryDTO = Devices.Select(d => d.ToSummaryDTO()).ToList(); foreach (var device in devicesSummaryDTO) { - device.ProviderName = _ProviderDatabaseService.GetById(userId, device.ProviderId).Name; + device.ProviderName = _ProviderDatabaseService.GetById(homeId, device.ProviderId).Name; } return new OkObjectResult(devicesSummaryDTO); @@ -107,20 +107,20 @@ namespace MyCore.Controllers /// /// Get list of devices from a type /// - /// user Id + /// Home Id /// device type [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("{userId}/type/{type}")] - public ObjectResult GetDevicesByType(string userId, DeviceType type) + [HttpGet("{homeId}/type/{type}")] + public ObjectResult GetDevicesByType(string homeId, DeviceType type) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Incorrect parameters"); - List devices = _DeviceDatabaseService.GetByType(userId, type); + List devices = _DeviceDatabaseService.GetByType(homeId, type); return new OkObjectResult(devices.Select(d => d.ToDTO())); @@ -152,7 +152,7 @@ namespace MyCore.Controllers if (deviceDetailDTO == null) throw new ArgumentNullException("Incorrect parameters"); - DeviceDetailDTO deviceCreated = DeviceService.CreateOrUpdate(this._DeviceDatabaseService, this._ProviderDatabaseService, this._LocationDatabaseService, deviceDetailDTO.UserId, deviceDetailDTO, true); + DeviceDetailDTO deviceCreated = DeviceService.CreateOrUpdate(this._DeviceDatabaseService, this._ProviderDatabaseService, this._RoomDatabaseService, deviceDetailDTO.HomeId, deviceDetailDTO, true); return new OkObjectResult(deviceCreated); @@ -178,7 +178,7 @@ namespace MyCore.Controllers /// /// Create devices from provider /// - /// User Id + /// Home Id /// Id of Provider [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 400)] @@ -186,22 +186,22 @@ namespace MyCore.Controllers [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 421)] [ProducesResponseType(typeof(string), 500)] - [HttpPost("{userId}/fromProvider/{providerId}")] - public async Task CreateDevicesFromProvider(string userId, string providerId) + [HttpPost("{homeId}/fromProvider/{providerId}")] + public async Task CreateDevicesFromProvider(string homeId, string providerId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Invalid paramaters"); - if (!UserService.IsExist(_UserDatabaseService, userId)) - throw new KeyNotFoundException("User not found"); + if (!HomeService.IsExist(_HomeDatabaseService, homeId)) + throw new KeyNotFoundException("Home not found"); - Provider provider = ProviderService.GetProviderById(this._ProviderDatabaseService, userId, providerId); + Provider provider = ProviderService.GetProviderById(this._ProviderDatabaseService, homeId, providerId); if (provider == null) throw new KeyNotFoundException("Provider not found"); - Dictionary> devices = await DeviceService.CreateFromProvider(this._DeviceDatabaseService, this._ProviderDatabaseService, this._LocationDatabaseService, userId, provider); + Dictionary> devices = await DeviceService.CreateFromProvider(this._DeviceDatabaseService, this._ProviderDatabaseService, this._RoomDatabaseService, homeId, provider); return new OkObjectResult(devices); } @@ -230,21 +230,21 @@ namespace MyCore.Controllers /// /// Get all zigbee2Mqtt devices /// - /// User Id + /// Home Id [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("zigbee2Mqtt/{userId}")] - public ObjectResult GetDevicesFromZigbee2Mqtt(string userId) + [HttpGet("zigbee2Mqtt/{homeId}")] + public ObjectResult GetDevicesFromZigbee2Mqtt(string homeId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Invalid paramaters"); - if (!UserService.IsExist(_UserDatabaseService, userId)) - throw new KeyNotFoundException("User not found"); + if (!HomeService.IsExist(_HomeDatabaseService, homeId)) + throw new KeyNotFoundException("Home not found"); // GET ALL LOCAL DEVICES var devices = MqttClientService.devices; // Be carefull, we only got the exact result after each connection @@ -268,22 +268,22 @@ namespace MyCore.Controllers /// /// Get devices from provider /// - /// User Id + /// Home Id /// Id of Provider [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("{userId}/fromProvider/{providerId}")] - public ObjectResult GetDevicesFromProvider(string userId, string providerId) + [HttpGet("{homeId}/fromProvider/{providerId}")] + public ObjectResult GetDevicesFromProvider(string homeId, string providerId) { try { - if (userId == null || providerId == null) + if (homeId == null || providerId == null) throw new ArgumentNullException("Invalid paramaters"); - if (!_UserDatabaseService.IsExist(userId)) - throw new KeyNotFoundException("User does not exist"); + if (!_HomeDatabaseService.IsExist(homeId)) + throw new KeyNotFoundException("Home does not exist"); if (!_ProviderDatabaseService.IsExist(providerId)) throw new KeyNotFoundException("Provider does not exist"); @@ -322,7 +322,7 @@ namespace MyCore.Controllers if (!_DeviceDatabaseService.IsExist(deviceDetailDTO.Id)) throw new KeyNotFoundException("Device does not exist"); - DeviceDetailDTO deviceUpdated = DeviceService.CreateOrUpdate(this._DeviceDatabaseService, this._ProviderDatabaseService, this._LocationDatabaseService, deviceDetailDTO.UserId, deviceDetailDTO, false); + DeviceDetailDTO deviceUpdated = DeviceService.CreateOrUpdate(this._DeviceDatabaseService, this._ProviderDatabaseService, this._RoomDatabaseService, deviceDetailDTO.HomeId, deviceDetailDTO, false); return new OkObjectResult(deviceUpdated); } @@ -378,22 +378,22 @@ namespace MyCore.Controllers /// /// Delete devices from provider /// - /// User Id + /// Home Id /// Id of Provider [ProducesResponseType(typeof(string), 202)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpDelete("{userId}/fromProvider/{providerId}")] - public ObjectResult DeleteDevicesFromProvider(string userId, string providerId) + [HttpDelete("{homeId}/fromProvider/{providerId}")] + public ObjectResult DeleteDevicesFromProvider(string homeId, string providerId) { try { - if (userId == null || providerId == null) + if (homeId == null || providerId == null) throw new ArgumentNullException("Invalid paramaters"); - if (!_UserDatabaseService.IsExist(userId)) - throw new KeyNotFoundException("User does not exist"); + if (!_HomeDatabaseService.IsExist(homeId)) + throw new KeyNotFoundException("Home does not exist"); if (!_ProviderDatabaseService.IsExist(providerId)) throw new KeyNotFoundException("Provider does not exist"); @@ -417,27 +417,27 @@ namespace MyCore.Controllers } /// - /// Delete all device for a specified user + /// Delete all device for a specified home /// - /// Id of user + /// Id of home [ProducesResponseType(typeof(string), 202)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpDelete("user/{userId}")] - public ObjectResult DeleteAllForUser(string userId) + [HttpDelete("home/{homeId}")] + public ObjectResult DeleteAllForHome(string homeId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Invalid paramaters"); - if (!_UserDatabaseService.IsExist(userId)) - throw new KeyNotFoundException("User does not exist"); + if (!_HomeDatabaseService.IsExist(homeId)) + throw new KeyNotFoundException("Home does not exist"); // TODO REMOVE DEVICE ID IN AUTOMATION and delete automation if none device ? - _DeviceDatabaseService.RemoveForUser(userId); - return new ObjectResult("User devices has been successfully deleted") { StatusCode = 202 }; + _DeviceDatabaseService.RemoveForHome(homeId); + return new ObjectResult("Home devices has been successfully deleted") { StatusCode = 202 }; } catch (ArgumentNullException ex) { diff --git a/MyCore/Controllers/Devices/IoThomas/EnergyController.cs b/MyCore/Controllers/Devices/IoThomas/EnergyController.cs index 4190eb3..e8743fc 100644 --- a/MyCore/Controllers/Devices/IoThomas/EnergyController.cs +++ b/MyCore/Controllers/Devices/IoThomas/EnergyController.cs @@ -32,20 +32,20 @@ namespace MyCore.Controllers /// Get summary production of Kwh/Year /// [HttpGet("electricity")] - public ActionResult> GetElectricityProduction(string userId, ViewBy viewBy) + public ActionResult> GetElectricityProduction(string homeId, ViewBy viewBy) { try { switch (viewBy) { case ViewBy.Year: - return _EnergyService.GetElectricityProductionForSpecifiedYear(userId, DateTime.Now.Year); + return _EnergyService.GetElectricityProductionForSpecifiedYear(homeId, DateTime.Now.Year); break; case ViewBy.Month: - return _EnergyService.GetElectricityProductionForSpecifiedMonth(userId, DateTime.Now.Month); + return _EnergyService.GetElectricityProductionForSpecifiedMonth(homeId, DateTime.Now.Month); break; case ViewBy.Day: - return _EnergyService.GetElectricityProductionForSpecifiedDay(userId, DateTime.Now.DayOfYear); + return _EnergyService.GetElectricityProductionForSpecifiedDay(homeId, DateTime.Now.DayOfYear); break; default: return new ObjectResult("Error - ViewBy incorrect") { StatusCode = 500 }; diff --git a/MyCore/Controllers/Devices/ProviderController.cs b/MyCore/Controllers/Devices/ProviderController.cs index 89b4142..ac899c5 100644 --- a/MyCore/Controllers/Devices/ProviderController.cs +++ b/MyCore/Controllers/Devices/ProviderController.cs @@ -22,37 +22,37 @@ namespace MyCore.Controllers { private DeviceDatabaseService _DeviceDatabaseService; private ProviderDatabaseService _ProviderDatabaseService; - private LocationDatabaseService _LocationDatabaseService; - private UserDatabaseService _UserDatabaseService; + private RoomDatabaseService _RoomDatabaseService; + private HomeDatabaseService _HomeDatabaseService; - public ProviderController(DeviceDatabaseService DeviceDatabaseService, ProviderDatabaseService ProviderDatabaseService, LocationDatabaseService LocationDatabaseService, UserDatabaseService UserDatabaseService) + public ProviderController(DeviceDatabaseService DeviceDatabaseService, ProviderDatabaseService ProviderDatabaseService, RoomDatabaseService RoomDatabaseService, HomeDatabaseService HomeDatabaseService) { this._DeviceDatabaseService = DeviceDatabaseService; this._ProviderDatabaseService = ProviderDatabaseService; - this._LocationDatabaseService = LocationDatabaseService; - this._UserDatabaseService = UserDatabaseService; + this._RoomDatabaseService = RoomDatabaseService; + this._HomeDatabaseService = HomeDatabaseService; } /// - /// Get all user providers + /// Get all home providers /// - /// Id of user + /// Home Id [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("{userId}")] - public ObjectResult GetAll(string userId) + [HttpGet("{homeId}")] + public ObjectResult GetAll(string homeId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Incorrect parameters"); - if (!UserService.IsExist(_UserDatabaseService, userId)) - throw new KeyNotFoundException("User not found"); + if (!HomeService.IsExist(_HomeDatabaseService, homeId)) + throw new KeyNotFoundException("Home not found"); - List providers = ProviderService.GetAll(this._ProviderDatabaseService, userId); + List providers = ProviderService.GetAll(this._ProviderDatabaseService, homeId); List providersDTO = providers.Select(p => p.ToDTO()).ToList(); @@ -90,16 +90,16 @@ namespace MyCore.Controllers if (providerDTO == null) throw new ArgumentNullException("Incorrect parameters"); - if (providerDTO.UserId == null) - throw new ArgumentNullException("User not found"); + if (providerDTO.HomeId == null) + throw new ArgumentNullException("Home not found"); - if (!UserService.IsExist(_UserDatabaseService, providerDTO.UserId)) - throw new KeyNotFoundException("User not found"); + if (!HomeService.IsExist(_HomeDatabaseService, providerDTO.HomeId)) + throw new KeyNotFoundException("Home not found"); - if (_ProviderDatabaseService.AlreadyExistForUser(providerDTO.UserId, providerDTO.Name)) + if (_ProviderDatabaseService.AlreadyExistForHome(providerDTO.HomeId, providerDTO.Name)) throw new InvalidOperationException("Provider already exists"); - ProviderDTO providerCreated = ProviderService.CreateOrUpdate(this._ProviderDatabaseService, providerDTO.UserId, providerDTO, true); + ProviderDTO providerCreated = ProviderService.CreateOrUpdate(this._ProviderDatabaseService, providerDTO.HomeId, providerDTO, true); return new OkObjectResult(providerCreated); @@ -138,16 +138,16 @@ namespace MyCore.Controllers if (providerDTO == null) throw new ArgumentNullException("Incorrect parameters"); - if (providerDTO.UserId == null) - throw new ArgumentNullException("User not found"); + if (providerDTO.HomeId == null) + throw new ArgumentNullException("Home not found"); - if (!UserService.IsExist(_UserDatabaseService, providerDTO.UserId)) - throw new KeyNotFoundException("User not found"); + if (!HomeService.IsExist(_HomeDatabaseService, providerDTO.HomeId)) + throw new KeyNotFoundException("Home not found"); - if (!ProviderService.IsExist(this._ProviderDatabaseService, providerDTO.UserId, providerDTO.Id)) + if (!ProviderService.IsExist(this._ProviderDatabaseService, providerDTO.HomeId, providerDTO.Id)) throw new KeyNotFoundException("Provider does not exist"); - ProviderDTO providerUpdated = ProviderService.CreateOrUpdate(this._ProviderDatabaseService, providerDTO.UserId, providerDTO, false); + ProviderDTO providerUpdated = ProviderService.CreateOrUpdate(this._ProviderDatabaseService, providerDTO.HomeId, providerDTO, false); return new OkObjectResult(providerUpdated); } diff --git a/MyCore/Controllers/GroupController.cs b/MyCore/Controllers/GroupController.cs index 6263169..93113fa 100644 --- a/MyCore/Controllers/GroupController.cs +++ b/MyCore/Controllers/GroupController.cs @@ -23,16 +23,16 @@ namespace MyCore.Service.Controllers [ApiController] public class GroupController : ControllerBase { - private UserDatabaseService _UserDatabaseService; + private HomeDatabaseService _HomeDatabaseService; private GroupDatabaseService _GroupDatabaseService; private DeviceDatabaseService _DeviceDatabaseService; private ProviderDatabaseService _ProviderDatabaseService; private readonly IMqttClientService _mqttClientService; //private readonly IMqttOnlineClientService _mqttOnlineClientService; - public GroupController(UserDatabaseService userDatabaseService, GroupDatabaseService groupDatabaseService, DeviceDatabaseService deviceDatabaseService, ProviderDatabaseService providerDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) + public GroupController(HomeDatabaseService homeDatabaseService, GroupDatabaseService groupDatabaseService, DeviceDatabaseService deviceDatabaseService, ProviderDatabaseService providerDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) { - this._UserDatabaseService = userDatabaseService; + this._HomeDatabaseService = homeDatabaseService; this._GroupDatabaseService = groupDatabaseService; this._DeviceDatabaseService = deviceDatabaseService; this._ProviderDatabaseService = providerDatabaseService; @@ -41,21 +41,21 @@ namespace MyCore.Service.Controllers } /// - /// Get all groups for the specified user + /// Get all groups for the specified home /// - /// Id of user + /// Home Id [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("{userId}")] - public ObjectResult GetAll(string userId) + [HttpGet("{homeId}")] + public ObjectResult GetAll(string homeId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Incorrect parameters"); - List Groups = _GroupDatabaseService.GetAll(userId); + List Groups = _GroupDatabaseService.GetAll(homeId); List groupsSummaryDTO = Groups.Select(d => d.ToSummaryDTO()).ToList(); @@ -91,7 +91,7 @@ namespace MyCore.Service.Controllers if (group == null) throw new KeyNotFoundException("Group not found"); - List devices = _DeviceDatabaseService.GetByLocation(group.UserId, groupId); + List devices = _DeviceDatabaseService.GetByLocation(group.HomeId, groupId); return new OkObjectResult(group.ToDTO(devices.Select(d => d.ToDTO()).ToList())); @@ -113,20 +113,20 @@ namespace MyCore.Service.Controllers /// /// Get list of group from a type /// - /// user Id + /// home Id /// group type [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("{userId}/type/{type}")] - public ObjectResult GetGroupsByType(string userId, string type) // Change string type to enum ? Lights etc ? + [HttpGet("{homeId}/type/{type}")] + public ObjectResult GetGroupsByType(string homeId, string type) // Change string type to enum ? Lights etc ? { try { - if (userId == null || type == null) + if (homeId == null || type == null) throw new ArgumentNullException("Incorrect parameters"); - List groups = _GroupDatabaseService.GetByType(userId, type); + List groups = _GroupDatabaseService.GetByType(homeId, type); return new OkObjectResult(groups.Select(d => d.ToSummaryDTO())); } @@ -143,21 +143,21 @@ namespace MyCore.Service.Controllers /// /// Get all zigbee2Mqtt groups /// - /// User Id + /// Home Id [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("zigbee2Mqtt/{userId}")] - public ObjectResult GetGroupsFromZigbee2Mqtt(string userId) + [HttpGet("zigbee2Mqtt/{homeId}")] + public ObjectResult GetGroupsFromZigbee2Mqtt(string homeId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Incorrect parameters"); - if (!UserService.IsExist(_UserDatabaseService, userId)) - throw new KeyNotFoundException("User not found"); + if (!HomeService.IsExist(_HomeDatabaseService, homeId)) + throw new KeyNotFoundException("Home not found"); // GET ALL LOCAL GROUPS var groups = MqttClientService.groups; // Be carefull, we only got the exact result after each connection @@ -193,7 +193,7 @@ namespace MyCore.Service.Controllers if (groupCreateOrUpdateDetail == null) throw new ArgumentNullException("Incorrect parameters"); - GroupDetailDTO groupCreated = GroupService.CreateOrUpdate(this._GroupDatabaseService, this._DeviceDatabaseService, groupCreateOrUpdateDetail.UserId, groupCreateOrUpdateDetail, true); + GroupDetailDTO groupCreated = GroupService.CreateOrUpdate(this._GroupDatabaseService, this._DeviceDatabaseService, groupCreateOrUpdateDetail.HomeId, groupCreateOrUpdateDetail, true); return new OkObjectResult(groupCreated); } @@ -210,30 +210,30 @@ namespace MyCore.Service.Controllers /// /// Create groups from provider /// - /// User Id + /// Home Id [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpPost("{userId}/fromZigbee")] - public ObjectResult CreateDevicesFromZigbee2Mqtt(string userId) + [HttpPost("{homeId}/fromZigbee")] + public ObjectResult CreateDevicesFromZigbee2Mqtt(string homeId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Incorrect parameters"); - if (!UserService.IsExist(_UserDatabaseService, userId)) - throw new KeyNotFoundException("User not found"); + if (!HomeService.IsExist(_HomeDatabaseService, homeId)) + throw new KeyNotFoundException("Home not found"); - Provider provider = _ProviderDatabaseService.GetByType("zigbee2mqtt"); + Provider provider = _ProviderDatabaseService.GetByType(ProviderType.zigbee2mqtt); if (provider == null) throw new KeyNotFoundException("Zigbee2mqtt provider not found"); // GET ALL LOCAL GROUPS var groups = MqttClientService.groups; // Be carefull, we only got the exact result after each connection - List groupsDetail= GroupService.CreateFromZigbeeAsync(_GroupDatabaseService, _DeviceDatabaseService, userId, groups); + List groupsDetail= GroupService.CreateFromZigbeeAsync(_GroupDatabaseService, _DeviceDatabaseService, homeId, groups); return new OkObjectResult(groupsDetail); } @@ -270,7 +270,7 @@ namespace MyCore.Service.Controllers if (!_GroupDatabaseService.IsExist(groupCreateOrUpdateDetail.Id)) throw new KeyNotFoundException("Group does not exist"); - GroupDetailDTO groupUpdated = GroupService.CreateOrUpdate(this._GroupDatabaseService, this._DeviceDatabaseService, groupCreateOrUpdateDetail.UserId, groupCreateOrUpdateDetail, false); + GroupDetailDTO groupUpdated = GroupService.CreateOrUpdate(this._GroupDatabaseService, this._DeviceDatabaseService, groupCreateOrUpdateDetail.HomeId, groupCreateOrUpdateDetail, false); return new OkObjectResult(groupUpdated); } @@ -360,7 +360,7 @@ namespace MyCore.Service.Controllers Group group = _GroupDatabaseService.GetById(groupId); // Delete group from all devices - List devices = _DeviceDatabaseService.GetByLocation(group.UserId, groupId); + List devices = _DeviceDatabaseService.GetByLocation(group.HomeId, groupId); foreach (var device in devices) { device.GroupIds = device.GroupIds.Where(g => g != groupId).ToList(); @@ -387,27 +387,27 @@ namespace MyCore.Service.Controllers } /// - /// Delete all group for a specified + /// Delete all group for a specified home /// - /// Id of user + /// Home Id [ProducesResponseType(typeof(string), 202)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpDelete("user/{userId}")] - public ObjectResult DeleteAllForUser(string userId) + [HttpDelete("home/{homeId}")] + public ObjectResult DeleteAllForHome(string homeId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Incorrect parameters"); - if (!_UserDatabaseService.IsExist(userId)) - throw new KeyNotFoundException("User does not exist"); + if (!_HomeDatabaseService.IsExist(homeId)) + throw new KeyNotFoundException("Home does not exist"); - _GroupDatabaseService.RemoveForUser(userId); + _GroupDatabaseService.RemoveForHome(homeId); - return new ObjectResult("All group linked with specified user has been successfully deleted") { StatusCode = 202 }; + return new ObjectResult("All group linked with specified home has been successfully deleted") { StatusCode = 202 }; } catch (ArgumentNullException ex) { diff --git a/MyCore/Controllers/HomeController.cs b/MyCore/Controllers/HomeController.cs new file mode 100644 index 0000000..d1f84ae --- /dev/null +++ b/MyCore/Controllers/HomeController.cs @@ -0,0 +1,251 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Security.Authentication; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using MongoDB.Bson; +using Mqtt.Client.AspNetCore.Services; +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; +using MyCore.Services; +using MyCore.Services.Devices; +using MyCore.Services.MyControlPanel; + +namespace MyCore.Service.Controllers +{ + [Authorize] // TODO Add ROLES (Roles = "Admin") + [Route("api/home")] + [ApiController] + public class HomeController : ControllerBase + { + private HomeDatabaseService _HomeDatabaseService; + private AlarmDatabaseService _AlarmDatabaseService; + private RoomDatabaseService _RoomDatabaseService; + private DeviceDatabaseService _DeviceDatabaseService; + private ProviderDatabaseService _ProviderDatabaseService; + private UserDatabaseService _UserDatabaseService; + private GroupDatabaseService _GroupDatabaseService; + private AutomationDatabaseService _AutomationDatabaseService; + private readonly IMqttClientService _mqttClientService; + //private readonly IMqttOnlineClientService _mqttOnlineClientService; + + public HomeController(HomeDatabaseService homeDatabaseService, RoomDatabaseService roomDatabaseService, DeviceDatabaseService deviceDatabaseService, ProviderDatabaseService providerDatabaseService, UserDatabaseService userDatabaseService, AutomationDatabaseService automationDatabaseService, GroupDatabaseService groupDatabaseService, AlarmDatabaseService alarmDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) + { + this._HomeDatabaseService = homeDatabaseService; + this._RoomDatabaseService = roomDatabaseService; + this._DeviceDatabaseService = deviceDatabaseService; + this._ProviderDatabaseService = providerDatabaseService; + this._UserDatabaseService = userDatabaseService; + this._AutomationDatabaseService = automationDatabaseService; + this._GroupDatabaseService = groupDatabaseService; + this._AlarmDatabaseService = alarmDatabaseService; + this._mqttClientService = provider.MqttClientService; + //this._mqttOnlineClientService = onlineProvider.MqttOnlineClientService; + } + + /// + /// Get all home for specified user + /// + /// User Id + [ProducesResponseType(typeof(List), 200)] + [ProducesResponseType(typeof(string), 400)] + [ProducesResponseType(typeof(string), 404)] + [ProducesResponseType(typeof(string), 500)] + [HttpGet("{userId}")] + public ObjectResult GetAll(string userId) + { + try + { + + if (userId == null) + throw new ArgumentNullException("Incorrect parameters"); + + UserInfo user = _UserDatabaseService.GetById(userId); + if (user == null) + throw new KeyNotFoundException("User does not exist"); + + List HomesResult = new List(); + foreach (var homeId in user.HomeIds) + { + Home home = _HomeDatabaseService.GetById(homeId); + HomesResult.Add(home.ToDTO()); + } + + return new OkObjectResult(HomesResult); + } + 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 }; + } + } + + /// + /// Get detail info of a specified home + /// + /// home id + [ProducesResponseType(typeof(HomeDetailDTO), 200)] + [ProducesResponseType(typeof(string), 400)] + [ProducesResponseType(typeof(string), 404)] + [ProducesResponseType(typeof(string), 500)] + [HttpGet("detail/{homeId}")] + public ObjectResult GetDetail(string homeId) + { + try + { + if (homeId == null) + throw new ArgumentNullException("Incorrect parameters"); + + Home home = _HomeDatabaseService.GetById(homeId); + if (home == null) + throw new KeyNotFoundException("Home does not exist"); + + List users = _UserDatabaseService.GetByHomeId(home.Id); + List devices = _DeviceDatabaseService.GetByHomeId(home.Id); + List automations = _AutomationDatabaseService.GetByHomeId(home.Id); + List providers = _ProviderDatabaseService.GetByHomeId(home.Id); + List groups = _GroupDatabaseService.GetByHomeId(home.Id); + + return new OkObjectResult(home.ToDetailDTO(users, devices, automations, providers, groups)); + } + 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 }; + } + } + + /// + /// Create a home + /// + /// Home to create + [ProducesResponseType(typeof(HomeDTO), 200)] + [ProducesResponseType(typeof(string), 400)] + [ProducesResponseType(typeof(string), 500)] + [HttpPost] + public ObjectResult Create([FromBody] CreateOrUpdateHomeDTO createOrUpdateHomeDTO) + { + try + { + if (createOrUpdateHomeDTO == null) + throw new ArgumentNullException("Incorrect parameters"); + + if (createOrUpdateHomeDTO.UsersIds.Count <= 0 && _UserDatabaseService.IsExistMultiple(createOrUpdateHomeDTO.UsersIds)) + throw new ArgumentNullException("To create an home, you need at least one user"); + + Home homeCreated = HomeService.CreateOrUpdate(this._HomeDatabaseService, this._AlarmDatabaseService, createOrUpdateHomeDTO, true); + + foreach (var userId in createOrUpdateHomeDTO.UsersIds) + { + UserInfo user = _UserDatabaseService.GetById(userId); + if (user.HomeIds == null) + user.HomeIds = new List(); + + if (!user.HomeIds.Contains(homeCreated.Id)) + user.HomeIds.Add(homeCreated.Id); + _UserDatabaseService.Update(user); + } + + return new OkObjectResult(homeCreated.ToDTO()); + } + catch (ArgumentNullException ex) + { + return new BadRequestObjectResult(ex.Message) { }; + } + catch (Exception ex) + { + return new ObjectResult(ex.Message) { StatusCode = 500 }; + } + } + + /// + /// Update a home + /// + /// Home to update + [ProducesResponseType(typeof(HomeDTO), 200)] + [ProducesResponseType(typeof(string), 404)] + [ProducesResponseType(typeof(string), 500)] + [HttpPut] + public ObjectResult Update([FromBody] CreateOrUpdateHomeDTO createOrUpdateHomeDTO) + { + try + { + if (!_HomeDatabaseService.IsExist(createOrUpdateHomeDTO.Id)) + throw new KeyNotFoundException("Home does not exist"); + + if (createOrUpdateHomeDTO.UsersIds.Count <= 0) + throw new ArgumentNullException("To create an home, you need at least one user"); + + Home homeUpdated = HomeService.CreateOrUpdate(this._HomeDatabaseService, this._AlarmDatabaseService, createOrUpdateHomeDTO, false); + + return new OkObjectResult(homeUpdated.ToDTO()); + } + catch (KeyNotFoundException ex) + { + return new NotFoundObjectResult(ex.Message) {}; + } + catch (Exception ex) + { + return new ObjectResult(ex.Message) { StatusCode = 500 }; + } + } + + /// + /// Delete a home + /// + /// Id of home to delete + [ProducesResponseType(typeof(string), 202)] + [ProducesResponseType(typeof(string), 400)] + [ProducesResponseType(typeof(string), 404)] + [ProducesResponseType(typeof(string), 500)] + [HttpDelete("{homeId}")] + public ObjectResult Delete(string homeId) + { + try + { + if (homeId == null) + throw new ArgumentNullException("Incorrect parameters"); + + if (!_HomeDatabaseService.IsExist(homeId)) + throw new KeyNotFoundException("Home does not exist"); + + Home home = _HomeDatabaseService.GetById(homeId); + // Check if something needs to be done.. (delete all devices related to home, all automations, all groups, etc) + // Delete home + _HomeDatabaseService.Remove(homeId); + + return new OkObjectResult("Home has been successfully deleted") { StatusCode = 202 }; + } + 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 }; + } + } + } +} diff --git a/MyCore/Controllers/MyControlPanel/UserController.cs b/MyCore/Controllers/MyControlPanel/UserController.cs index c41fdcf..49a8f1a 100644 --- a/MyCore/Controllers/MyControlPanel/UserController.cs +++ b/MyCore/Controllers/MyControlPanel/UserController.cs @@ -93,11 +93,16 @@ namespace MyCore.Controllers { try { + // TODO Add check for password if (newUser == null) throw new ArgumentNullException("User param is null"); + if (newUser.Password == null || newUser.Email == null) + throw new ArgumentNullException("You need to specified email and password at least"); + newUser.Token = _tokenService.GenerateToken(newUser.Email).ToString(); newUser.DateCreation = DateTime.Now; + newUser.HomeIds = new List(); List users = _userService.GetAll(); @@ -144,7 +149,7 @@ namespace MyCore.Controllers if (user == null) throw new KeyNotFoundException("User does not exist"); - UserInfo userModified = _userService.Update(updatedUser.Id, updatedUser); + UserInfo userModified = _userService.Update(updatedUser); return new OkObjectResult(userModified.ToDTO()); } diff --git a/MyCore/Controllers/RoomController.cs b/MyCore/Controllers/RoomController.cs index ba97350..14d324f 100644 --- a/MyCore/Controllers/RoomController.cs +++ b/MyCore/Controllers/RoomController.cs @@ -22,15 +22,15 @@ namespace MyCore.Service.Controllers [ApiController] public class RoomController : ControllerBase { - private UserDatabaseService _UserDatabaseService; + private HomeDatabaseService _HomeDatabaseService; private RoomDatabaseService _RoomDatabaseService; private DeviceDatabaseService _DeviceDatabaseService; private readonly IMqttClientService _mqttClientService; //private readonly IMqttOnlineClientService _mqttOnlineClientService; - public RoomController(UserDatabaseService userDatabaseService, RoomDatabaseService roomDatabaseService, DeviceDatabaseService deviceDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) + public RoomController(HomeDatabaseService homeDatabaseService, RoomDatabaseService roomDatabaseService, DeviceDatabaseService deviceDatabaseService, MqttClientServiceProvider provider)//, MqttClientOnlineServiceProvider onlineProvider) { - this._UserDatabaseService = userDatabaseService; + this._HomeDatabaseService = homeDatabaseService; this._RoomDatabaseService = roomDatabaseService; this._DeviceDatabaseService = deviceDatabaseService; this._mqttClientService = provider.MqttClientService; @@ -38,17 +38,17 @@ namespace MyCore.Service.Controllers } /// - /// Get all rooms for the specified user + /// Get all rooms for the specified home /// - /// Id of user + /// Home Id [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(typeof(string), 500)] - [HttpGet("{userId}")] - public ObjectResult GetAll(string userId) + [HttpGet("{homeId}")] + public ObjectResult GetAll(string homeId) { try { - List Rooms = _RoomDatabaseService.GetAll(userId); + List Rooms = _RoomDatabaseService.GetAll(homeId); List roomsSummaryDTO = Rooms.Select(d => d.ToSummaryDTO()).ToList(); @@ -62,25 +62,24 @@ namespace MyCore.Service.Controllers /// /// Get detail info of a specified room - /// - /// user id + /// /// room id [ProducesResponseType(typeof(RoomDetailDTO), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] [HttpGet("detail/{roomId}")] - public ObjectResult GetDetail(string userId, string roomId) + public ObjectResult GetDetail(string roomId) { try { - if (userId == null || roomId == null) + if (roomId == null) throw new ArgumentNullException("Incorrect parameters"); Room room = _RoomDatabaseService.GetById(roomId); if (room == null) throw new KeyNotFoundException("Room does not exist"); - List devices = _DeviceDatabaseService.GetByLocation(room.UserId, roomId); + List devices = _DeviceDatabaseService.GetByLocation(room.HomeId, roomId); return new OkObjectResult(room.ToDTO(devices.Select(d => d.ToDTO()).ToList())); @@ -114,7 +113,7 @@ namespace MyCore.Service.Controllers if (roomCreateOrUpdateDetail == null) throw new ArgumentNullException("Incorrect parameters"); - RoomDetailDTO roomCreated = RoomService.CreateOrUpdate(this._RoomDatabaseService, this._DeviceDatabaseService, roomCreateOrUpdateDetail.UserId, roomCreateOrUpdateDetail, true); + RoomDetailDTO roomCreated = RoomService.CreateOrUpdate(this._RoomDatabaseService, this._DeviceDatabaseService, roomCreateOrUpdateDetail.HomeId, roomCreateOrUpdateDetail, true); return new OkObjectResult(roomCreated); } @@ -143,7 +142,7 @@ namespace MyCore.Service.Controllers if (!_RoomDatabaseService.IsExist(roomCreateOrUpdateDetail.Id)) throw new KeyNotFoundException("Room does not exist"); - RoomDetailDTO roomUpdated = RoomService.CreateOrUpdate(this._RoomDatabaseService, this._DeviceDatabaseService, roomCreateOrUpdateDetail.UserId, roomCreateOrUpdateDetail, false); + RoomDetailDTO roomUpdated = RoomService.CreateOrUpdate(this._RoomDatabaseService, this._DeviceDatabaseService, roomCreateOrUpdateDetail.HomeId, roomCreateOrUpdateDetail, false); return new OkObjectResult(roomUpdated); } @@ -189,7 +188,7 @@ namespace MyCore.Service.Controllers if (device == null) throw new KeyNotFoundException("Device does not exist"); - device.LocationId = null; + device.RoomId = null; device.UpdatedDate = DateTime.Now; _DeviceDatabaseService.Update(device); @@ -231,10 +230,10 @@ namespace MyCore.Service.Controllers Room room = _RoomDatabaseService.GetById(roomId); // Delete location from all devices - List devices = _DeviceDatabaseService.GetByLocation(room.UserId, roomId); + List devices = _DeviceDatabaseService.GetByLocation(room.HomeId, roomId); foreach (var device in devices) { - device.LocationId = null; + device.RoomId = null; device.UpdatedDate = DateTime.Now; _DeviceDatabaseService.Update(device); } @@ -258,27 +257,27 @@ namespace MyCore.Service.Controllers } /// - /// Delete all room for a specified user + /// Delete all room for a specified home /// - /// Id of user + /// Home Id [ProducesResponseType(typeof(string), 202)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 500)] - [HttpDelete("user/{userId}")] - public ObjectResult DeleteAllForUser(string userId) + [HttpDelete("home/{homeId}")] + public ObjectResult DeleteAllForHome(string homeId) { try { - if (userId == null) + if (homeId == null) throw new ArgumentNullException("Incorrect parameters"); - if (!_UserDatabaseService.IsExist(userId)) - throw new KeyNotFoundException("User does not exist"); + if (!_HomeDatabaseService.IsExist(homeId)) + throw new KeyNotFoundException("Home does not exist"); - _RoomDatabaseService.RemoveForUser(userId); + _RoomDatabaseService.RemoveForHome(homeId); - return new OkObjectResult("All room associated to specified user has been removed") { StatusCode = 202 }; + return new OkObjectResult("All room associated to specified home has been removed") { StatusCode = 202 }; } catch (ArgumentNullException ex) { diff --git a/MyCore/Extensions/MqttClientService.cs b/MyCore/Extensions/MqttClientService.cs index 5c9f28f..d7e22f2 100644 --- a/MyCore/Extensions/MqttClientService.cs +++ b/MyCore/Extensions/MqttClientService.cs @@ -3,12 +3,17 @@ using MQTTnet.Client; using MQTTnet.Client.Connecting; using MQTTnet.Client.Disconnecting; using MQTTnet.Client.Options; +using MyCore.Interfaces.DTO; using MyCore.Interfaces.Models; +using MyCore.Interfaces.Models.Providers.Zigbee.Zigbee2Mqtt; +using MyCore.Service.Services; +using MyCore.Services; using MyCore.Services.Devices; using MyCore.Services.MyControlPanel; using Newtonsoft.Json; using System; using System.Collections.Generic; +using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -19,29 +24,44 @@ namespace Mqtt.Client.AspNetCore.Services { private static IMqttClient mqttClient; private IMqttClientOptions options; - public static List devices = new List(); + public static List devices = new List(); public static List devicesNew = new List(); public static List groups = new List(); - public static string userId; - static DeviceDatabaseService _deviceDatabaseService; - static GroupDatabaseService _groupDatabaseService; - static ProviderDatabaseService _providerDatabaseService; - static LocationDatabaseService _locationDatabaseService; - static AutomationDatabaseService _automationDatabaseService; - static ActionService _actionService; + public static string homeId; + private DeviceDatabaseService _deviceDatabaseService; + private GroupDatabaseService _groupDatabaseService; + private ProviderDatabaseService _providerDatabaseService; + private RoomDatabaseService _roomDatabaseService; + private AutomationDatabaseService _automationDatabaseService; + private ActionService _actionService; + private HomeDatabaseService _homeDatabaseService; public static string lastTopic; public static long lastTimeTopic; - public MqttClientService(IMqttClientOptions options) + public MqttClientService(IMqttClientOptions options, HomeDatabaseService homeDatabaseService, DeviceDatabaseService deviceDatabaseService, GroupDatabaseService groupDatabaseService, ProviderDatabaseService providerDatabaseService, RoomDatabaseService roomDatabaseService, ActionService actionService, AutomationDatabaseService automationDatabaseService) { + this._homeDatabaseService = homeDatabaseService; + this._deviceDatabaseService = deviceDatabaseService; + this._groupDatabaseService = groupDatabaseService; + this._providerDatabaseService = providerDatabaseService; + this._roomDatabaseService = roomDatabaseService; + this._automationDatabaseService = automationDatabaseService; + this._actionService = actionService; + + Home home = this._homeDatabaseService.GetAll().ToList().Where(h => h.IsDefault).FirstOrDefault(); + if (home != null) + homeId = home.Id; + + System.Console.WriteLine($"Home Id in MQTT client service : {homeId}"); + var server = "localhost"; var clientId = "ApiService"; #if DEBUG server = "192.168.31.140"; clientId = "ApiServiceTest"; #endif - this.options = options; + //this.options = options; this.options = new MqttClientOptionsBuilder() .WithClientId(clientId) .WithTcpServer(server) @@ -93,9 +113,9 @@ namespace Mqtt.Client.AspNetCore.Services // Less than one second between two messages from a same device if (!(lastTopic == topic && test <= 500) || configMessage) { - if (_actionService != null) + if (_actionService != null && homeId != null) { - ActionService.HandleActionFromMQTTAsync(topic, payload, _deviceDatabaseService, _groupDatabaseService, _providerDatabaseService, _locationDatabaseService, _automationDatabaseService, userId); + ActionService.HandleActionFromMQTTAsync(topic, payload, _deviceDatabaseService, _groupDatabaseService, _providerDatabaseService, _roomDatabaseService, _automationDatabaseService, homeId); } } else @@ -104,12 +124,14 @@ namespace Mqtt.Client.AspNetCore.Services System.Console.WriteLine($"Drop message - spam from {topic}"); } + UpdateZigbee2MqttConfigOrStateAsync(topic, payload, homeId, _deviceDatabaseService, _groupDatabaseService, _providerDatabaseService, _roomDatabaseService); + switch (topic) { case "zigbee2mqtt/bridge/config/devices": try { - var devicesConvert = JsonConvert.DeserializeObject>(payload); + var devicesConvert = JsonConvert.DeserializeObject>(payload); devices = devicesConvert; } catch (Exception ex) @@ -187,28 +209,141 @@ namespace Mqtt.Client.AspNetCore.Services await mqttClient.DisconnectAsync(); } - public static async Task PublishMessage(string topic, string message) + public static async Task PublishMessage(string topic, string message, bool retain = false) { var mqttMessage = new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(message) .WithExactlyOnceQoS() - .WithRetainFlag(false) + .WithRetainFlag(retain) .Build(); if (mqttClient.IsConnected) await mqttClient.PublishAsync(mqttMessage); } - public static void SetServices(DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, ActionService _ActionService, AutomationDatabaseService _AutomationDatabaseService, string UserId) + /*public static void SetServices(DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService, ActionService _ActionService, AutomationDatabaseService _AutomationDatabaseService, string HomeId) { _deviceDatabaseService = _DeviceDatabaseService; _groupDatabaseService = _GroupDatabaseService; _providerDatabaseService = _ProviderDatabaseService; - _locationDatabaseService = _LocationDatabaseService; + _roomDatabaseService = _RoomDatabaseService; _automationDatabaseService = _AutomationDatabaseService; _actionService = _ActionService; - userId = UserId; + homeId = HomeId; + }*/ + + public static async Task UpdateZigbee2MqttConfigOrStateAsync(string topic, string message, string homeId, DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService) + { + // update zigbee2mqqtt config + switch (topic) + { + case "zigbee2mqtt/bridge/config/devices": + try + { + var devices = JsonConvert.DeserializeObject>(message); + var zigbee2mqttProvider = _ProviderDatabaseService.GetByType(ProviderType.zigbee2mqtt); + + if (zigbee2mqttProvider != null) + { + // Retrieve existing devices + List existingDevices = _DeviceDatabaseService.GetByProviderId(zigbee2mqttProvider.Id); + var existingDevicesAddresses = existingDevices.Select(ed => ed.ServiceIdentification); + + // Filter devices and check if something new + var filteredDevices = devices.Where(d => !existingDevicesAddresses.Contains(d.ieeeAddr)).ToList(); + // Add new devices + Dictionary> createdDevices = await DeviceService.CreateFromZigbeeAsync(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, filteredDevices, zigbee2mqttProvider); + } + + System.Console.WriteLine($"Devices updated for home {homeId}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error during retrieving devices ! Exception: {ex}"); + } + break; + case "zigbee2mqtt/bridge/devices": + try + { + var devices = JsonConvert.DeserializeObject>(message); + var zigbee2mqttProvider = _ProviderDatabaseService.GetByType(ProviderType.zigbee2mqtt); + + if (zigbee2mqttProvider != null) + { + // Retrieve existing devices + /*List existingDevices = _DeviceDatabaseService.GetByProviderId(zigbee2mqttProvider.Id); + var existingDevicesAddresses = existingDevices.Select(ed => ed.ServiceIdentification);*/ + + System.Console.WriteLine($"Nbr of devices : {devices.Count}"); + + // Update supported operation + Dictionary> createdDevices = await DeviceService.UpdateFromZigbeeAsync(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, devices, zigbee2mqttProvider); + } + + System.Console.WriteLine($"Devices updated for home {homeId} - more information"); + } + catch (Exception ex) + { + Console.WriteLine($"Error during retrieving devices ! Exception: {ex}"); + } + break; + case "zigbee2mqtt/bridge/groups": + try + { + var groupsConvert = JsonConvert.DeserializeObject>(message); + + var zigbee2mqttProvider = _ProviderDatabaseService.GetByType(ProviderType.zigbee2mqtt); + + if (zigbee2mqttProvider != null) + { + var groups = _GroupDatabaseService.GetByType(homeId, "zigbee2mqtt"); + // Compare the groups from MyCore and the group we received, if something diff in one group => Hard refresh (delete, new) + + // TODO : Test with new devices !! => Id always change BUUUUUUG !! + GroupService.CompareGroupsFromZigbee2Mqtt(homeId, groups, groupsConvert, _DeviceDatabaseService, _GroupDatabaseService); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error during retrieving groups ! Exception: {ex}"); + } + break; + case "zigbee2mqtt/bridge/event": + try + { + var eventConvert = JsonConvert.DeserializeObject(message); + + if (eventConvert.data?.ieee_address != null) + { + var zigbeeDevice = _DeviceDatabaseService.GetByServiceIdentification(eventConvert.data.ieee_address); + + if (zigbeeDevice != null && eventConvert.type == "device_announce") // Check if we can not hardcode that.. + { + var status = new List(); + var state = new AutomationState(); + state.Name = "state"; + state.Value = "on"; + status.Add(state); + + var buildRequest = new Dictionary(); + buildRequest.Add(state.Name, state.Value); + + // Update device state ! + zigbeeDevice.LastState = JsonConvert.SerializeObject(buildRequest); + zigbeeDevice.LastStateDate = DateTime.Now; + _DeviceDatabaseService.Update(zigbeeDevice); + + // Check if all group has the same state // Not needed as we test the first device of a group + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error during retrieving event ! Exception: {ex}"); + } + break; + } } } } diff --git a/MyCore/Extensions/ServiceCollectionExtension.cs b/MyCore/Extensions/ServiceCollectionExtension.cs index d8bfe16..4a1ebf4 100644 --- a/MyCore/Extensions/ServiceCollectionExtension.cs +++ b/MyCore/Extensions/ServiceCollectionExtension.cs @@ -5,6 +5,7 @@ using Mqtt.Client.AspNetCore.Services; using Mqtt.Client.AspNetCore.Settings; using MQTTnet.Client.Options; using MyCore.Services; +using MyCore.Services.Devices; using System; namespace MyCore.Service.Extensions @@ -61,12 +62,19 @@ namespace MyCore.Service.Extensions private static IServiceCollection AddMqttClientServiceWithConfig(this IServiceCollection services, Action configure) { // No need as we implement options in service (localhost) - /*services.AddSingleton(serviceProvider => + services.AddSingleton(serviceProvider => { var optionBuilder = new AspCoreMqttClientOptionBuilder(serviceProvider); configure(optionBuilder); return optionBuilder.Build(); - });*/ + }); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(serviceProvider => { diff --git a/MyCore/Services/AutomationService.cs b/MyCore/Services/AutomationService.cs index c8ddc14..9f26d5e 100644 --- a/MyCore/Services/AutomationService.cs +++ b/MyCore/Services/AutomationService.cs @@ -1,5 +1,6 @@ using MyCore.Interfaces.DTO; using MyCore.Interfaces.Models; +using MyCore.Services; using MyCore.Services.MyControlPanel; using System; using System.Collections.Generic; @@ -10,7 +11,7 @@ namespace MyCore.Service.Services { public class AutomationService { - public static AutomationDTO CreateOrUpdate(AutomationDatabaseService _AutomationDatabaseService, string userId, AutomationCreateOrUpdateDetailDTO automationCreateOrUpdateDetailDTO, bool create) + public static AutomationDTO CreateOrUpdate(AutomationDatabaseService _AutomationDatabaseService, string homeId, AutomationCreateOrUpdateDetailDTO automationCreateOrUpdateDetailDTO, bool create) { Automation automation; if (create) @@ -20,7 +21,7 @@ namespace MyCore.Service.Services automation = _AutomationDatabaseService.GetById(automationCreateOrUpdateDetailDTO.Id); } - automation.UserId = userId; + automation.HomeId = homeId; automation.Name = automationCreateOrUpdateDetailDTO.Name; automation.Active = automationCreateOrUpdateDetailDTO.Active; automation.CreatedDate = create ? DateTime.Now : automation.CreatedDate; diff --git a/MyCore/Services/Devices/ActionService.cs b/MyCore/Services/Devices/ActionService.cs index 1f05ebe..723399a 100644 --- a/MyCore/Services/Devices/ActionService.cs +++ b/MyCore/Services/Devices/ActionService.cs @@ -20,7 +20,7 @@ namespace MyCore.Services.Devices private static Device deviceTrigger; private static string providerFromTopic; private static string deviceServiceName; - public static async Task HandleActionFromMQTTAsync(string topic, string message, DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, AutomationDatabaseService _AutomationDatabaseService, string userId) + public static async Task HandleActionFromMQTTAsync(string topic, string message, DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService, AutomationDatabaseService _AutomationDatabaseService, string homeId) { System.Console.WriteLine($"Received message {message}"); @@ -34,13 +34,13 @@ namespace MyCore.Services.Devices switch (providerFromTopic) { case "zigbee2mqtt": - UpdateZigbee2MqttConfigOrStateAsync(topic, message, userId, _DeviceDatabaseService, _GroupDatabaseService, _ProviderDatabaseService, _LocationDatabaseService); + break; default: break; } - currentProvider = _ProviderDatabaseService.GetByType(providerFromTopic); + currentProvider = Enum.IsDefined(typeof(ProviderType), providerFromTopic) ? _ProviderDatabaseService.GetByType((ProviderType) Enum.Parse(typeof(ProviderType), providerFromTopic.ToLower())) : null; if (currentProvider != null) { @@ -107,7 +107,7 @@ namespace MyCore.Services.Devices { case ActionType.DEVICE: var deviceAction = _DeviceDatabaseService.GetById(action.DeviceId); - var providerActionTest = _ProviderDatabaseService.GetById(userId, action.ProviderId); + var providerActionTest = _ProviderDatabaseService.GetById(homeId, action.ProviderId); DeviceNameForAction = deviceAction.Name; actionDeviceToTest = deviceAction; @@ -140,14 +140,14 @@ namespace MyCore.Services.Devices break; } - var providerAction = _ProviderDatabaseService.GetById(userId, action.ProviderId); + var providerAction = _ProviderDatabaseService.GetById(homeId, action.ProviderId); // Check if device exist if (actionDeviceToTest != null && providerAction != null) { switch (providerAction.Type) { - case "zigbee2mqtt": + case ProviderType.zigbee2mqtt: try { ActionOnZigbee2Mqtt(actionDeviceToTest, action, DeviceNameForAction); @@ -157,7 +157,7 @@ namespace MyCore.Services.Devices System.Console.WriteLine($"ActionOnZigbee2Mqtt result in error: {ex}"); } break; - case "meross": + case ProviderType.meross: try { ActionOnMeross(_DeviceDatabaseService, actionDeviceToTest, action, DeviceNameForAction); @@ -167,7 +167,7 @@ namespace MyCore.Services.Devices System.Console.WriteLine($"ActionOnMeross result in error: {ex}"); } break; - case "yeelight": + case ProviderType.yeelight: try { ActionOnYeelight(_DeviceDatabaseService, actionDeviceToTest, action); @@ -414,13 +414,15 @@ namespace MyCore.Services.Devices // Comment this for test (ensure the request will be sent) /*if (dic.Count > 0) { - if (dic["state"].ToString().ToLower() == state.Value.ToLower() && action.States.Count <= 1) // workaround if brightness not the same + //if (device.Type == DeviceType.Light) {} + var test = dic["state"].ToString().ToLower(); + var test0 = state.Value.ToLower(); + if (dic["state"].ToString().ToLower() == state.Value.ToLower() && action.States.Count <= 1) // workaround if brightness not the same => For switch or light without brightness { throw new Exception($"Action device is already at the good state : {state.Name} {state.Value}"); } }*/ - // TODO clean this if (state.Name == "brightness") { try @@ -445,6 +447,60 @@ namespace MyCore.Services.Devices throw new Exception($"Action device light|switch does not have expose of type {state.Name}"); } } + + // If any action ask for state update, check if device is already at the asked state + if (action.States.Any(s => s.Name == "state") && !action.IsForce) + { + bool sendRequest = true; + + // If action doesn't ask for brightness just test if device is already at the asked state + if (action.States.Any(s => s.Name == "brightness")) + { + // Check state and brightness + // if we got state value (current value) + if (dic.Any(d => d.Key == "state")) + { + var currentValue = dic["state"].ToString().ToLower(); + var askedValue = action.States.FirstOrDefault(s => s.Name == "state").Value.ToLower(); + if (currentValue == askedValue) + { + // Check brightness difference + if (dic.Any(d => d.Key == "brightness")) + { + try + { + var currentValueBrightness = int.Parse(dic["brightness"].ToString().ToLower()); + var askedValueBrightness = int.Parse(action.States.FirstOrDefault(s => s.Name == "brightness").Value.ToLower()); + if (Math.Abs(currentValueBrightness - askedValueBrightness) <= 5) // brightness diff is lower than 5 => don't change brightness + sendRequest = false; + else + sendRequest = true; + } + catch (Exception ex) + { + sendRequest = false; + System.Console.WriteLine($"int parse error in brightness check", ex.Message); + } + } + } + } + } + else + { + // Check only state value + // if we got state value (current value) + if (dic.Any(d => d.Key == "state")) + { + var currentValue = dic["state"].ToString().ToLower(); + var askedValue = action.States.FirstOrDefault(s => s.Name == "state").Value.ToLower(); + if (currentValue == askedValue) + sendRequest = false; + } + } + + if (!sendRequest) + throw new Exception($"Action device is already at the good state"); + } } else throw new Exception("Action device does not have expose of type light|switch"); @@ -465,7 +521,7 @@ namespace MyCore.Services.Devices request = JsonConvert.SerializeObject(buildRequest); // SEND REQUEST - var requestToSend = $"Send request ! zigbee2mqtt/{deviceNameForAction}/set/{request}"; + //var requestToSend = $"Send request ! zigbee2mqtt/{deviceNameForAction}/set/{request}"; System.Console.WriteLine($"Send request ! zigbee2mqtt/{deviceNameForAction}/set/{request}"); MqttClientService.PublishMessage("zigbee2mqtt/" + deviceNameForAction + "/set", request); @@ -573,90 +629,5 @@ namespace MyCore.Services.Devices return null; } } - - public static async Task UpdateZigbee2MqttConfigOrStateAsync(string topic, string message, string userId, DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService) { - // update zigbee2mqqtt config - switch (topic) - { - case "zigbee2mqtt/bridge/config/devices": - try - { - var devices = JsonConvert.DeserializeObject>(message); - var zigbee2mqttProvider = _ProviderDatabaseService.GetByType("zigbee2mqtt"); - - if (zigbee2mqttProvider != null) - { - // Retrieve existing devices - List existingDevices = _DeviceDatabaseService.GetByProviderId(zigbee2mqttProvider.Id); - var existingDevicesAddresses = existingDevices.Select(ed => ed.ServiceIdentification); - - // Filter devices and check if something new - var filteredDevices = devices.Where(d => !existingDevicesAddresses.Contains(d.ieee_address)).ToList(); - // Add new devices - Dictionary> createdDevices = await DeviceService.CreateFromZigbeeAsync(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, filteredDevices, zigbee2mqttProvider); - } - - System.Console.WriteLine($"Devices updated for user {userId}"); - } - catch (Exception ex) - { - Console.WriteLine($"Error during retrieving devices ! Exception: {ex}"); - } - break; - case "zigbee2mqtt/bridge/groups": - try - { - var groupsConvert = JsonConvert.DeserializeObject>(message); - - var zigbee2mqttProvider = _ProviderDatabaseService.GetByType("zigbee2mqtt"); - - if (zigbee2mqttProvider != null) - { - var groups = _GroupDatabaseService.GetByType(userId, "zigbee2mqtt"); - // Compare the groups from MyCore and the group we received, if something diff in one group => Hard refresh (delete, new) - // TODO : Test with new devices - GroupService.CompareGroupsFromZigbee2Mqtt(userId, groups, groupsConvert, _DeviceDatabaseService, _GroupDatabaseService); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error during retrieving groups ! Exception: {ex}"); - } - break; - case "zigbee2mqtt/bridge/event": - try - { - var eventConvert = JsonConvert.DeserializeObject(message); - - if (eventConvert.data?.ieee_address != null) { - var zigbeeDevice = _DeviceDatabaseService.GetByServiceIdentification(eventConvert.data.ieee_address); - - if (zigbeeDevice != null && eventConvert.type == "device_announce") // Check if we can not hardcode that.. - { - var status = new List(); - var state = new AutomationState(); - state.Name = "state"; - state.Value = "on"; - status.Add(state); - - var buildRequest = new Dictionary(); - buildRequest.Add(state.Name, state.Value); - - // Update device state ! - zigbeeDevice.LastState = JsonConvert.SerializeObject(buildRequest); - zigbeeDevice.LastStateDate = DateTime.Now; - _DeviceDatabaseService.Update(zigbeeDevice); - - // Check if all group has the same state // Not needed as we test the first device of a group - } - } - } - catch (Exception ex) - { - Console.WriteLine($"Error during retrieving event ! Exception: {ex}"); - } - break; - } - } } } diff --git a/MyCore/Services/Devices/DeviceService.cs b/MyCore/Services/Devices/DeviceService.cs index febca9f..cce413c 100644 --- a/MyCore/Services/Devices/DeviceService.cs +++ b/MyCore/Services/Devices/DeviceService.cs @@ -38,22 +38,32 @@ namespace MyCore.Services.Devices new SupportedDevice { Manufacturer = "SONOFF", Model = "BASICZBR3", Description = "Zigbee smart switch", DeviceType = DeviceType.Switch }, }; - public static DeviceDetailDTO CreateOrUpdate(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, DeviceDetailDTO deviceDetailDTO, bool create) + public static DeviceDetailDTO CreateOrUpdate(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService, string homeId, DeviceDetailDTO deviceDetailDTO, bool create, bool isZigbee = false) { Device device; - if (create) - device = new Device(); - else + + if (isZigbee) { - device = _DeviceDatabaseService.GetById(deviceDetailDTO.Id); + device = _DeviceDatabaseService.GetByServiceIdentification(deviceDetailDTO.ServiceIdentification); + if (device == null) + device = new Device(); + } + else { + if (create) + device = new Device(); + else + { + device = _DeviceDatabaseService.GetById(deviceDetailDTO.Id); + } } - if (_DeviceDatabaseService.IsAlreadyHere(userId, deviceDetailDTO.ServiceIdentification, deviceDetailDTO.Model) && create) + /*// What's the purpose here ? + if (_DeviceDatabaseService.IsAlreadyHere(homeId, deviceDetailDTO.ServiceIdentification, deviceDetailDTO.Model) && create) { return null; - } + }*/ - device.UserId = userId; + device.HomeId = homeId; device.Name = deviceDetailDTO.Name; device.Description = deviceDetailDTO.Description; device.ManufacturerName = deviceDetailDTO.ManufacturerName; @@ -63,8 +73,8 @@ namespace MyCore.Services.Devices else throw new KeyNotFoundException("Provider does not exist"); - if (device.LocationId == null || _LocationDatabaseService.IsExist(deviceDetailDTO.LocationId)) - device.LocationId = deviceDetailDTO.LocationId; + if (device.RoomId == null || _RoomDatabaseService.IsExist(deviceDetailDTO.RoomId)) + device.RoomId = deviceDetailDTO.RoomId; else throw new KeyNotFoundException("Location does not exist"); @@ -79,7 +89,7 @@ namespace MyCore.Services.Devices else device.ConnectionStatus = deviceDetailDTO.ConnectionStatus; device.Status = deviceDetailDTO.Status; - device.LocationId = deviceDetailDTO.LocationId; + device.RoomId = deviceDetailDTO.RoomId; device.CreatedDate = DateTime.Now; device.UpdatedDate = DateTime.Now; device.LastState = deviceDetailDTO.LastState; @@ -102,33 +112,38 @@ namespace MyCore.Services.Devices return _DeviceDatabaseService.Update(device).ToDTO(); } - public async static Task>> CreateFromProvider(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, Provider provider) + public async static Task>> CreateFromProvider(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService, string homeId, Provider provider) { - if (!ProviderService.IsProviderSupported(provider.Type)) - throw new KeyNotFoundException("Provider is not yet supported"); - Dictionary> devices = new Dictionary>(); try { switch (provider.Type) { - case "arlo": + case ProviderType.arlo: List arloDevices = new ArloService(provider.Username, provider.Password).GetAllDevices(); - devices = CreateArloDevices(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, arloDevices, provider); + devices = CreateArloDevices(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, arloDevices, provider); break; - case "meross": + case ProviderType.meross: List merossDevices = MqttClientMerossService.GetMerossDevices(); // TO TEST IF IT WORKS - devices = CreateMerossDevices(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, merossDevices, provider); + devices = CreateMerossDevices(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, merossDevices, provider); break; - case "yeelight": + case ProviderType.yeelight: List yeelightDevices = await YeelightService.GetDevices(); - devices = CreateYeelightDevices(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, yeelightDevices, provider); + devices = CreateYeelightDevices(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, yeelightDevices, provider); break; - case "zigbee2mqtt": - List zigbee2MqttDevices = MqttClientService.devicesNew; - devices = await CreateFromZigbeeAsync(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, zigbee2MqttDevices, provider); - /*List zigbee2MqttDevices = MqttClientService.devices; - devices = await CreateFromZigbeeAsync(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, zigbee2MqttDevices, provider);*/ + case ProviderType.zigbee2mqtt: + if (MqttClientService.devices.Count > 0) + { + // Simple list mode + List zigbee2MqttDevices = MqttClientService.devices; + devices = await CreateFromZigbeeAsync(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, zigbee2MqttDevices, provider); + } + if (MqttClientService.devicesNew.Count > 0) + { + // Complex list mode + List zigbee2MqttDevices = MqttClientService.devicesNew; + devices = await UpdateFromZigbeeAsync(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, zigbee2MqttDevices, provider); + } break; } } @@ -145,7 +160,7 @@ namespace MyCore.Services.Devices } // Old way - /*public static async Task>> CreateFromZigbeeAsync(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, List zigbee2MqttDevices, Provider provider) + /*public static async Task>> CreateFromZigbeeAsync(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string homeId, List zigbee2MqttDevices, Provider provider) { List createdZigbeeDevices = new List(); List notSupportedZigbeeDevices = new List(); @@ -186,7 +201,7 @@ namespace MyCore.Services.Devices if (deviceDetailDTO.Type != DeviceType.Unknown) { // Supoorted device ! - createdZigbeeDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, deviceDetailDTO, true)); + createdZigbeeDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, homeId, deviceDetailDTO, true)); } else { // Not yet supported ! @@ -200,7 +215,7 @@ namespace MyCore.Services.Devices }; }*/ - public static async Task>> CreateFromZigbeeAsync(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, List zigbee2MqttDevices, Provider provider) + public static async Task>> CreateFromZigbeeAsync(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService, string homeId, List zigbee2MqttDevices, Provider provider) { List createdZigbeeDevices = new List(); List notSupportedZigbeeDevices = new List(); @@ -213,23 +228,23 @@ namespace MyCore.Services.Devices //zigbee2MqttDevices = await MqttClientService.AskDevicesAsync(); } - zigbee2MqttDevices = zigbee2MqttDevices.Where(yd => !existingDevices.Select(ed => ed.ServiceIdentification).ToList().Contains(yd.ieee_address)).ToList(); + zigbee2MqttDevices = zigbee2MqttDevices.Where(yd => !existingDevices.Select(ed => ed.ServiceIdentification).ToList().Contains(yd.ieeeAddr)).ToList(); foreach (var zigbee2MqttDevice in zigbee2MqttDevices) { DeviceDetailDTO deviceDetailDTO = new DeviceDetailDTO(); deviceDetailDTO.Name = zigbee2MqttDevice.friendly_name; - deviceDetailDTO.ServiceIdentification = zigbee2MqttDevice.ieee_address; + deviceDetailDTO.ServiceIdentification = zigbee2MqttDevice.ieeeAddr; deviceDetailDTO.ProviderId = provider.Id; deviceDetailDTO.ProviderName = provider.Name; - deviceDetailDTO.Description = zigbee2MqttDevice.type == "Coordinator" ? "Coordinator" : zigbee2MqttDevice.definition.description; + deviceDetailDTO.Description = zigbee2MqttDevice.type == "Coordinator" ? "Coordinator" : zigbee2MqttDevice.description; - deviceDetailDTO.Model = zigbee2MqttDevice.type == "Coordinator" ? "Coordinator" : zigbee2MqttDevice.definition.model; // Is the base to understand incoming messages ! - deviceDetailDTO.FirmwareVersion = zigbee2MqttDevice.software_build_id; + deviceDetailDTO.Model = zigbee2MqttDevice.type == "Coordinator" ? "Coordinator" : zigbee2MqttDevice.model; // Is the base to understand incoming messages ! + //deviceDetailDTO.FirmwareVersion = zigbee2MqttDevice.software_build_id; - deviceDetailDTO.Battery = zigbee2MqttDevice.power_source == null ? false : zigbee2MqttDevice.power_source.Contains("Battery"); - deviceDetailDTO.ManufacturerName = zigbee2MqttDevice.definition?.vendor == null ? provider.Type : zigbee2MqttDevice.definition?.vendor.ToLower(); + deviceDetailDTO.Battery = zigbee2MqttDevice.powerSource == null ? false : zigbee2MqttDevice.powerSource.Contains("Battery"); + deviceDetailDTO.ManufacturerName = zigbee2MqttDevice.vendor == null ? provider.Type.ToString() : zigbee2MqttDevice.vendor.ToLower(); deviceDetailDTO.MeansOfCommunications = new List(); deviceDetailDTO.MeansOfCommunications.Add(MeansOfCommunication.Zigbee); @@ -240,22 +255,22 @@ namespace MyCore.Services.Devices { // EXPOSES ! List supportedOperationsDTO = new List(); - foreach (var supportedOperation in zigbee2MqttDevice.definition?.exposes) + /*foreach (var supportedOperation in zigbee2MqttDevice.definition?.exposes) { supportedOperationsDTO.Add(JsonConvert.SerializeObject(supportedOperation)); } deviceDetailDTO.SupportedOperations = supportedOperationsDTO; - deviceDetailDTO.Type = GetDeviceTypeFromZigbeeModel(zigbee2MqttDevice.definition.model); + deviceDetailDTO.Type = GetDeviceTypeFromZigbeeModel(zigbee2MqttDevice.definition.model);*/ } else { deviceDetailDTO.Type = DeviceType.Gateway; } - if (zigbee2MqttDevice.supported || deviceDetailDTO.Type == DeviceType.Gateway) + if (true) //zigbee2MqttDevice.supported // TODO QUID { // Supported device ! - createdZigbeeDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, deviceDetailDTO, true)); + createdZigbeeDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, deviceDetailDTO, true)); } else { @@ -270,6 +285,83 @@ namespace MyCore.Services.Devices }; } + public static async Task>> UpdateFromZigbeeAsync(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService, string homeId, List zigbee2MqttDevices, Provider provider) + { + List updatedZigbeeDevices = new List(); + List notSupportedZigbeeDevices = new List(); + + List existingDevices = _DeviceDatabaseService.GetByProviderId(provider.Id); + + // Not necessarry + if (zigbee2MqttDevices.Count <= 0) + { + //zigbee2MqttDevices = await MqttClientService.AskDevicesAsync(); + } + + //zigbee2MqttDevices = zigbee2MqttDevices.Where(yd => !existingDevices.Select(ed => ed.ServiceIdentification).ToList().Contains(yd.ieee_address)).ToList(); + + foreach (var zigbee2MqttDevice in zigbee2MqttDevices) + { + var existingDevice = _DeviceDatabaseService.GetByServiceIdentification(zigbee2MqttDevice.ieee_address); + + DeviceDetailDTO deviceDetailDTO = new DeviceDetailDTO(); + deviceDetailDTO.Name = zigbee2MqttDevice.friendly_name; + deviceDetailDTO.ServiceIdentification = zigbee2MqttDevice.ieee_address; + deviceDetailDTO.ProviderId = provider.Id; + deviceDetailDTO.ProviderName = provider.Name; + + deviceDetailDTO.Description = zigbee2MqttDevice.type == "Coordinator" ? "Coordinator" : zigbee2MqttDevice.definition.description; + + deviceDetailDTO.Model = zigbee2MqttDevice.type == "Coordinator" ? "Coordinator" : zigbee2MqttDevice.definition.model; // Is the base to understand incoming messages ! + deviceDetailDTO.FirmwareVersion = zigbee2MqttDevice.software_build_id; + + deviceDetailDTO.Battery = zigbee2MqttDevice.power_source == null ? false : zigbee2MqttDevice.power_source.Contains("Battery"); + deviceDetailDTO.ManufacturerName = zigbee2MqttDevice.definition?.vendor == null ? provider.Type.ToString() : zigbee2MqttDevice.definition?.vendor.ToLower(); + deviceDetailDTO.MeansOfCommunications = new List(); + deviceDetailDTO.MeansOfCommunications.Add(MeansOfCommunication.Zigbee); + + deviceDetailDTO.GroupIds = existingDevice != null ? existingDevice.GroupIds : null; + deviceDetailDTO.Properties = existingDevice != null ? existingDevice.Properties : null; + deviceDetailDTO.RoomId = existingDevice != null ? existingDevice.RoomId : null; + + deviceDetailDTO.CreatedDate = existingDevice != null ? existingDevice.CreatedDate : DateTime.Now; + deviceDetailDTO.UpdatedDate = DateTime.Now; + + if (zigbee2MqttDevice.type != "Coordinator") + { + // EXPOSES ! + List supportedOperationsDTO = new List(); + foreach (var supportedOperation in zigbee2MqttDevice.definition?.exposes) + { + supportedOperationsDTO.Add(JsonConvert.SerializeObject(supportedOperation)); + } + deviceDetailDTO.SupportedOperations = supportedOperationsDTO; + + deviceDetailDTO.Type = GetDeviceTypeFromZigbeeModel(zigbee2MqttDevice.definition.model); + } + else + { + deviceDetailDTO.Type = DeviceType.Gateway; + } + + if (zigbee2MqttDevice.supported || deviceDetailDTO.Type == DeviceType.Gateway) + { + // Supported device ! + updatedZigbeeDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, deviceDetailDTO, false, true)); + } + else + { + // Not yet supported ! + notSupportedZigbeeDevices.Add(deviceDetailDTO); + } + } + + return new Dictionary>() { + { "updatedZigbeeDevices", updatedZigbeeDevices }, + { "notSupportedDevices", notSupportedZigbeeDevices } + }; + } + private static DeviceType GetDeviceTypeFromZigbeeModel(string zigbeeModel) { return supportedDevices.Any(sd => sd.Model == zigbeeModel) ? @@ -279,7 +371,7 @@ namespace MyCore.Services.Devices DeviceType.Unknown; } - public static Dictionary> CreateArloDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, List arloDevices, Provider provider) + public static Dictionary> CreateArloDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService, string homeId, List arloDevices, Provider provider) { List createdArloDevices = new List(); @@ -290,7 +382,7 @@ namespace MyCore.Services.Devices foreach (var arlo in arloDevices) { DeviceDetailDTO deviceDetailDTO = new DeviceDetailDTO(); - deviceDetailDTO.ManufacturerName = provider.Type; + deviceDetailDTO.ManufacturerName = provider.Type.ToString(); deviceDetailDTO.Name = arlo.deviceName; deviceDetailDTO.Description = arlo.deviceName; // As description not exist, put name in description deviceDetailDTO.ServiceIdentification = arlo.deviceId; @@ -330,13 +422,13 @@ namespace MyCore.Services.Devices deviceDetailDTO.CreatedDate = DateTime.Now; deviceDetailDTO.UpdatedDate = DateTime.Now; - createdArloDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, deviceDetailDTO, true)); + createdArloDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, deviceDetailDTO, true)); } return new Dictionary>() { { "createdDevices", createdArloDevices } }; // TODO Check if exist not supported devices } - public static Dictionary> CreateMerossDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, List merossDevices, Provider provider) + public static Dictionary> CreateMerossDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService, string homeId, List merossDevices, Provider provider) { List createdMerossDevices = new List(); @@ -347,7 +439,7 @@ namespace MyCore.Services.Devices foreach (var meross in merossDevices) { DeviceDetailDTO deviceDetailDTO = new DeviceDetailDTO(); - deviceDetailDTO.ManufacturerName = provider.Type; + deviceDetailDTO.ManufacturerName = provider.Type.ToString(); deviceDetailDTO.HardwareVersion = meross.hdwareVersion; deviceDetailDTO.Name = meross.devName; deviceDetailDTO.Description = meross.devName; // As description not exist, put name in description @@ -385,13 +477,13 @@ namespace MyCore.Services.Devices deviceDetailDTO.MeansOfCommunications.Add(MeansOfCommunication.Wifi); // TO CHECK deviceDetailDTO.CreatedDate = DateTime.Now; deviceDetailDTO.UpdatedDate = DateTime.Now; - createdMerossDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, deviceDetailDTO, true)); + createdMerossDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, deviceDetailDTO, true)); } return new Dictionary>() { { "createdDevices", createdMerossDevices } }; // TODO Check if exist not supported devices } - public static Dictionary> CreateYeelightDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, string userId, List yeelightDevices, Provider provider) + public static Dictionary> CreateYeelightDevices(DeviceDatabaseService _DeviceDatabaseService, ProviderDatabaseService _ProviderDatabaseService, RoomDatabaseService _RoomDatabaseService, string homeId, List yeelightDevices, Provider provider) { List createdYeelightDevices = new List(); @@ -402,7 +494,7 @@ namespace MyCore.Services.Devices foreach (var light in yeelightDevices) { DeviceDetailDTO deviceDetailDTO = new DeviceDetailDTO(); - deviceDetailDTO.ManufacturerName = provider.Type; + deviceDetailDTO.ManufacturerName = provider.Type.ToString(); deviceDetailDTO.Name = light.Name; deviceDetailDTO.Description = light.Name; // As description not exist, put name in description deviceDetailDTO.IpAddress = light.Hostname; @@ -431,7 +523,7 @@ namespace MyCore.Services.Devices deviceDetailDTO.MeansOfCommunications.Add(MeansOfCommunication.Wifi); deviceDetailDTO.CreatedDate = DateTime.Now; deviceDetailDTO.UpdatedDate = DateTime.Now; - createdYeelightDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _LocationDatabaseService, userId, deviceDetailDTO, true)); + createdYeelightDevices.Add(CreateOrUpdate(_DeviceDatabaseService, _ProviderDatabaseService, _RoomDatabaseService, homeId, deviceDetailDTO, true)); } return new Dictionary>() { { "createdDevices", createdYeelightDevices } }; // TODO Check if exist not supported devices diff --git a/MyCore/Services/Devices/IoThomas/EnergyService.cs b/MyCore/Services/Devices/IoThomas/EnergyService.cs index fb8c635..766ec8b 100644 --- a/MyCore/Services/Devices/IoThomas/EnergyService.cs +++ b/MyCore/Services/Devices/IoThomas/EnergyService.cs @@ -24,25 +24,25 @@ namespace MyCore.Services return _electricityProductionData.Find(m => true).ToList(); } - public List GetElectricityProductionForSpecifiedYear(string userId, int year) + public List GetElectricityProductionForSpecifiedYear(string homeId, int year) { - return _electricityProductionData.Find(m => m.UserId == userId && m.Timestamp.Year == year).ToList(); + return _electricityProductionData.Find(m => m.HomeId == homeId && m.Timestamp.Year == year).ToList(); } - public List GetElectricityProductionForSpecifiedMonth(string userId, int month) + public List GetElectricityProductionForSpecifiedMonth(string homeId, int month) { - return _electricityProductionData.Find(m => m.UserId == userId && m.Timestamp.Month == month).ToList(); + return _electricityProductionData.Find(m => m.HomeId == homeId && m.Timestamp.Month == month).ToList(); } - public List GetElectricityProductionForSpecifiedDay(string userId, int dayOfYear) + public List GetElectricityProductionForSpecifiedDay(string homeId, int dayOfYear) { - return _electricityProductionData.Find(m => m.UserId == userId && m.Timestamp.DayOfYear == dayOfYear).ToList(); + return _electricityProductionData.Find(m => m.HomeId == homeId && m.Timestamp.DayOfYear == dayOfYear).ToList(); } // Check if necessary - public ElectricityProduction GetElectricityProductionForUser(string userId) + public ElectricityProduction GetElectricityProductionForHome(string homeId) { - return _electricityProductionData.Find(m => m.UserId == userId).FirstOrDefault(); + return _electricityProductionData.Find(m => m.HomeId == homeId).FirstOrDefault(); } public ElectricityProduction InsertData(ElectricityProduction data) @@ -70,15 +70,15 @@ namespace MyCore.Services } // Check if necessary - public void RemoveByDeviceId(string userId, string id) + public void RemoveByDeviceId(string homeId, string id) { - _electricityProductionData.DeleteOne(data => data.UserId == userId && data.DeviceId == id); + _electricityProductionData.DeleteOne(data => data.HomeId == homeId && data.DeviceId == id); } // Check if necessary - public void RemoveByDeviceIdBeforeDate(string userId, DateTime dateTime) + public void RemoveByDeviceIdBeforeDate(string homeId, DateTime dateTime) { - _electricityProductionData.DeleteOne(data => data.UserId == userId && data.Timestamp < dateTime); + _electricityProductionData.DeleteOne(data => data.HomeId == homeId && data.Timestamp < dateTime); } } } diff --git a/MyCore/Services/GroupService.cs b/MyCore/Services/GroupService.cs index 10993c8..270c505 100644 --- a/MyCore/Services/GroupService.cs +++ b/MyCore/Services/GroupService.cs @@ -1,5 +1,6 @@ using MyCore.Interfaces.DTO; using MyCore.Interfaces.Models; +using MyCore.Services; using MyCore.Services.MyControlPanel; using System; using System.Collections.Generic; @@ -10,7 +11,7 @@ namespace MyCore.Service.Services { public class GroupService { - public static GroupDetailDTO CreateOrUpdate(GroupDatabaseService _GroupDatabaseService, DeviceDatabaseService _DeviceDatabaseService, string userId, GroupCreateOrUpdateDetailDTO groupCreateOrUpdateDetailDTO, bool create) + public static GroupDetailDTO CreateOrUpdate(GroupDatabaseService _GroupDatabaseService, DeviceDatabaseService _DeviceDatabaseService, string homeId, GroupCreateOrUpdateDetailDTO groupCreateOrUpdateDetailDTO, bool create) { List devices = new List(); Group group; @@ -25,7 +26,7 @@ namespace MyCore.Service.Services group = _GroupDatabaseService.GetById(groupCreateOrUpdateDetailDTO.Id); } - group.UserId = userId; + group.HomeId = homeId; group.Name = groupCreateOrUpdateDetailDTO.Name; group.Type = group.Type; // TODO group.UpdatedDate = DateTime.Now; @@ -51,12 +52,12 @@ namespace MyCore.Service.Services return group.ToDTO(devices.Select(d => d.ToDTO()).ToList()); } - public static List CreateFromZigbeeAsync(GroupDatabaseService _GroupDatabaseService, DeviceDatabaseService _DeviceDatabaseService, string userId, List zigbee2MqttGroups) + public static List CreateFromZigbeeAsync(GroupDatabaseService _GroupDatabaseService, DeviceDatabaseService _DeviceDatabaseService, string homeId, List zigbee2MqttGroups) { List groups = new List(); // Get zigbee groups - List existingGroups = _GroupDatabaseService.GetByType(userId, "zigbee2mqtt"); + List existingGroups = _GroupDatabaseService.GetByType(homeId, "zigbee2mqtt"); foreach (var zigbee2MqttGroup in zigbee2MqttGroups.Where(z => z.members.Count > 0)) // Only take group with members { @@ -66,13 +67,12 @@ namespace MyCore.Service.Services var existingGroup = existingGroups.Where(eg => eg.ServiceIdentification == zigbee2MqttGroup.id).FirstOrDefault(); GroupCreateOrUpdateDetailDTO groupToUpdate = new GroupCreateOrUpdateDetailDTO(); - groupToUpdate.UserId = existingGroup.UserId; + groupToUpdate.HomeId = existingGroup.HomeId; groupToUpdate.Name = existingGroup.Name; groupToUpdate.Id = existingGroup.Id; - groupToUpdate.IsAlarm = existingGroup.IsAlarm; groupToUpdate.DeviceIds = existingGroup.DevicesIds; // Hard refresh - CreateOrUpdate(_GroupDatabaseService, _DeviceDatabaseService, userId, groupToUpdate, false); + CreateOrUpdate(_GroupDatabaseService, _DeviceDatabaseService, homeId, groupToUpdate, false); create = false; } @@ -84,7 +84,7 @@ namespace MyCore.Service.Services group.CreatedDate = DateTime.Now; group.DevicesIds = new List(); group.ServiceIdentification = zigbee2MqttGroup.id; - group.UserId = userId; + group.HomeId = homeId; group.Name = zigbee2MqttGroup.friendly_name; group.Type = "zigbee2mqtt"; group.UpdatedDate = DateTime.Now; @@ -118,7 +118,7 @@ namespace MyCore.Service.Services } // We only go in this method if the group config change during operation - public static void CompareGroupsFromZigbee2Mqtt(string userId, List groups, List zigbee2MqttGroups, DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService) + public static void CompareGroupsFromZigbee2Mqtt(string homeId, List groups, List zigbee2MqttGroups, DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService) { // We do not refresh all list as we don't want to create plenty of new groupId and have to delete from device param everytime List existingGroups = new List(); @@ -136,7 +136,7 @@ namespace MyCore.Service.Services if (existingGroupWithThisId == null) { // New group -> Create it ! - CreateFromZigbeeAsync(_GroupDatabaseService, _DeviceDatabaseService, userId, zigbee2MqttGroups.Where(z => z.id == zigbee2MqttGroup.id).ToList()); + CreateFromZigbeeAsync(_GroupDatabaseService, _DeviceDatabaseService, homeId, zigbee2MqttGroups.Where(z => z.id == zigbee2MqttGroup.id).ToList()); } else { if (!Enumerable.SequenceEqual(zigbee2MqttGroup.members.Select(m => m.ieee_address).OrderBy(t => t), existingGroupWithThisId.members.Select(m => m.ieee_address).OrderBy(t => t))) { @@ -157,7 +157,7 @@ namespace MyCore.Service.Services _GroupDatabaseService.Remove(groupToDelete.Id); // Create new group - CreateFromZigbeeAsync(_GroupDatabaseService, _DeviceDatabaseService, userId, new List() { zigbee2MqttGroup }); + CreateFromZigbeeAsync(_GroupDatabaseService, _DeviceDatabaseService, homeId, new List() { zigbee2MqttGroup }); } } // else do nothing diff --git a/MyCore/Services/MyControlPanel/Database/AlarmDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/AlarmDatabaseService.cs new file mode 100644 index 0000000..5b606fe --- /dev/null +++ b/MyCore/Services/MyControlPanel/Database/AlarmDatabaseService.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using MyCore.Interfaces.Models; +using Microsoft.Extensions.Configuration; +using MongoDB.Driver; + +namespace MyCore.Services +{ + public class AlarmDatabaseService + { + private readonly IMongoCollection _Alarms; + + public AlarmDatabaseService(IConfiguration config) + { + var client = new MongoClient(config.GetConnectionString("MyCoreDb")); + var database = client.GetDatabase("MyCoreDb"); + _Alarms = database.GetCollection("AlarmModes"); + } + public List GetAll(string homeId) + { + return _Alarms.Find(alarm => alarm.HomeId == homeId).ToList(); + } + + public AlarmMode GetById(string id) + { + return _Alarms.Find(alarm => alarm.Id == id).FirstOrDefault(); + } + + public bool IsExist(string id) + { + return _Alarms.Find(alarm => alarm.Id == id).FirstOrDefault() != null ? true : false; + } + + public AlarmMode Create(AlarmMode alarm) + { + _Alarms.InsertOne(alarm); + return alarm; + } + + public AlarmMode Update(AlarmMode alarmIn) + { + _Alarms.ReplaceOne(alarm => alarm.Id == alarmIn.Id, alarmIn); + return alarmIn; + } + + public void Remove(string id) + { + _Alarms.DeleteOne(alarm => alarm.Id == id); + } + + public void RemoveForHome(string homeId) + { + _Alarms.DeleteMany(alarm => alarm.HomeId== homeId); + } + } +} diff --git a/MyCore/Services/MyControlPanel/Database/AutomationDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/AutomationDatabaseService.cs index ec3b93c..d0fd881 100644 --- a/MyCore/Services/MyControlPanel/Database/AutomationDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/AutomationDatabaseService.cs @@ -6,7 +6,7 @@ using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -namespace MyCore.Services.MyControlPanel +namespace MyCore.Services { public class AutomationDatabaseService { @@ -18,9 +18,9 @@ namespace MyCore.Services.MyControlPanel var database = client.GetDatabase("MyCoreDb"); _Automations = database.GetCollection("Automations"); } - public List GetAll(string userId) + public List GetAll(string homeId) { - return _Automations.Find(a => a.UserId == userId).ToList(); + return _Automations.Find(a => a.HomeId == homeId).ToList(); } public Automation GetById(string id) @@ -28,6 +28,11 @@ namespace MyCore.Services.MyControlPanel return _Automations.Find(a => a.Id == id).FirstOrDefault(); } + public List GetByHomeId(string homeId) + { + return _Automations.Find(a => a.HomeId == homeId).ToList(); + } + public List GetByProvider(string id) { return _Automations.Find(a => a.Triggers.Any(t => t.ProviderId == id)).ToList(); @@ -60,9 +65,9 @@ namespace MyCore.Services.MyControlPanel _Automations.DeleteOne(automation => automation.Id == id); } - public void RemoveForUser(string userId) + public void RemoveForHome(string homeId) { - _Automations.DeleteMany(automation => automation.UserId == userId); + _Automations.DeleteMany(automation => automation.HomeId == homeId); } } } diff --git a/MyCore/Services/MyControlPanel/Database/DeviceDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/DeviceDatabaseService.cs index c71ce59..c0f62e9 100644 --- a/MyCore/Services/MyControlPanel/Database/DeviceDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/DeviceDatabaseService.cs @@ -7,7 +7,7 @@ using Microsoft.Extensions.Configuration; using MongoDB.Driver; using MyCore.Interfaces.DTO; -namespace MyCore.Services.MyControlPanel +namespace MyCore.Services { public class DeviceDatabaseService { @@ -19,9 +19,9 @@ namespace MyCore.Services.MyControlPanel var database = client.GetDatabase("MyCoreDb"); _Devices = database.GetCollection("Devices"); } - public List GetAll(string userId) + public List GetAll(string homeId) { - return _Devices.Find(d => d.UserId == userId).ToList(); + return _Devices.Find(d => d.HomeId == homeId).ToList(); } public Device GetById(string id) @@ -39,14 +39,19 @@ namespace MyCore.Services.MyControlPanel return _Devices.Find(d => ids.Contains(d.Id)).ToList(); } - public List GetByLocation(string userId, string locationId) + public List GetByHomeId(string homeId) { - return _Devices.Find(d => d.UserId == userId && d.LocationId == locationId).ToList(); + return _Devices.Find(h => h.HomeId == homeId).ToList(); } - public List GetByType(string userId, DeviceType type) + public List GetByLocation(string homeId, string roomId) { - return _Devices.Find(d => d.UserId == userId && d.Type == type).ToList(); + return _Devices.Find(d => d.HomeId == homeId && d.RoomId == roomId).ToList(); + } + + public List GetByType(string homeId, DeviceType type) + { + return _Devices.Find(d => d.HomeId == homeId && d.Type == type).ToList(); } public List GetByProviderId(string providerId) @@ -69,9 +74,9 @@ namespace MyCore.Services.MyControlPanel return _Devices.Find(d => d.Id == id).FirstOrDefault() != null ? true : false; } - public bool IsAlreadyHere(string userId, string serviceIdentification, string model) + public bool IsAlreadyHere(string homeId, string serviceIdentification, string model) { - return _Devices.Find(d => d.UserId == userId && d.ServiceIdentification == serviceIdentification && d.Model == model).FirstOrDefault() != null ? true : false; + return _Devices.Find(d => d.HomeId == homeId && d.ServiceIdentification == serviceIdentification && d.Model == model).FirstOrDefault() != null ? true : false; } public Device Create(Device device) @@ -96,9 +101,9 @@ namespace MyCore.Services.MyControlPanel _Devices.DeleteMany(device => device.ProviderId == providerId); } - public void RemoveForUser(string userId) + public void RemoveForHome(string homeId) { - _Devices.DeleteMany(device => device.UserId == userId); + _Devices.DeleteMany(device => device.HomeId == homeId); } } } diff --git a/MyCore/Services/MyControlPanel/Database/GroupDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/GroupDatabaseService.cs index 5ff60d8..6cb1414 100644 --- a/MyCore/Services/MyControlPanel/Database/GroupDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/GroupDatabaseService.cs @@ -6,7 +6,7 @@ using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -namespace MyCore.Services.MyControlPanel +namespace MyCore.Services { public class GroupDatabaseService { @@ -19,9 +19,9 @@ namespace MyCore.Services.MyControlPanel _Groups = database.GetCollection("Groups"); } - public List GetAll(string userId) + public List GetAll(string homeId) { - return _Groups.Find(d => d.UserId == userId).ToList(); + return _Groups.Find(d => d.HomeId == homeId).ToList(); } public Group GetById(string id) @@ -29,9 +29,14 @@ namespace MyCore.Services.MyControlPanel return _Groups.Find(d => d.Id == id).FirstOrDefault(); } - public List GetByType(string userId, string type) + public List GetByHomeId(string homeId) { - return _Groups.Find(d => d.UserId == userId && d.Type == type).ToList(); + return _Groups.Find(g => g.HomeId == homeId).ToList(); + } + + public List GetByType(string homeId, string type) + { + return _Groups.Find(d => d.HomeId == homeId && d.Type == type).ToList(); } public bool IsExist(string id) @@ -56,9 +61,9 @@ namespace MyCore.Services.MyControlPanel _Groups.DeleteOne(group => group.Id == id); } - public void RemoveForUser(string userId) + public void RemoveForHome(string homeId) { - _Groups.DeleteMany(group => group.UserId == userId); + _Groups.DeleteMany(group => group.HomeId == homeId); } } } diff --git a/MyCore/Services/MyControlPanel/Database/HomeDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/HomeDatabaseService.cs new file mode 100644 index 0000000..cf24449 --- /dev/null +++ b/MyCore/Services/MyControlPanel/Database/HomeDatabaseService.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using MyCore.Interfaces.Models; +using Microsoft.Extensions.Configuration; +using MongoDB.Driver; + +namespace MyCore.Services +{ + public class HomeDatabaseService + { + private readonly IMongoCollection _Homes; + + public HomeDatabaseService(IConfiguration config) + { + var client = new MongoClient(config.GetConnectionString("MyCoreDb")); + var database = client.GetDatabase("MyCoreDb"); + _Homes = database.GetCollection("Homes"); + } + public List GetAll() + { + return _Homes.Find(h => true).ToList(); + } + + public Home GetById(string id) + { + return _Homes.Find(m => m.Id == id).FirstOrDefault(); + } + + public bool IsExist(string id) + { + return _Homes.Find(d => d.Id == id).FirstOrDefault() != null ? true : false; + } + + public Home Create(Home home) + { + _Homes.InsertOne(home); + return home; + } + + public Home Update(string id, Home homeIn) + { + _Homes.ReplaceOne(home => home.Id == id, homeIn); + return homeIn; + } + + public void Remove(string id) + { + _Homes.DeleteOne(home => home.Id == id); + } + + } +} diff --git a/MyCore/Services/MyControlPanel/Database/LocationDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/LocationDatabaseService.cs deleted file mode 100644 index ed5c5c1..0000000 --- a/MyCore/Services/MyControlPanel/Database/LocationDatabaseService.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using MyCore.Interfaces.Models; -using Microsoft.Extensions.Configuration; -using MongoDB.Driver; - -namespace MyCore.Services.MyControlPanel -{ - public class LocationDatabaseService - { - private readonly IMongoCollection _Locations; - - public LocationDatabaseService(IConfiguration config) - { - var client = new MongoClient(config.GetConnectionString("MyCoreDb")); - var database = client.GetDatabase("MyCoreDb"); - _Locations = database.GetCollection("Locations"); - } - public List GetAll() - { - return _Locations.Find(l => true).ToList(); - } - - public Place GetById(string id) - { - return _Locations.Find(l => l.Id == id).FirstOrDefault(); - } - - public bool IsExist(string id) - { - return _Locations.Find(p => p.Id == id).FirstOrDefault() != null ? true : false; - } - - public Place Create(Place location) - { - _Locations.InsertOne(location); - return location; - } - - public Place Update(string id, Place locationIn) - { - _Locations.ReplaceOne(location => location.Id == id, locationIn); - return locationIn; - } - - public void Remove(string id) - { - _Locations.DeleteOne(location => location.Id == id); - } - } -} diff --git a/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs index cbb33d0..5ae842f 100644 --- a/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs @@ -6,7 +6,7 @@ using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -namespace MyCore.Services.MyControlPanel +namespace MyCore.Services { public class ProviderDatabaseService { @@ -18,19 +18,24 @@ namespace MyCore.Services.MyControlPanel var database = client.GetDatabase("MyCoreDb"); _Providers = database.GetCollection("Providers"); } - public List GetAll(string userId) + public List GetAll(string homeId) { - return _Providers.Find(p => p.UserId == userId).ToList(); + return _Providers.Find(p => p.HomeId == homeId).ToList(); } - public Provider GetById(string userId, string id) + public Provider GetById(string homeId, string id) { - return _Providers.Find(p => p.Id == id && p.UserId == userId).FirstOrDefault(); + return _Providers.Find(p => p.Id == id && p.HomeId == homeId).FirstOrDefault(); } - public bool AlreadyExistForUser(string userId, string name) + public List GetByHomeId(string homeId) { - return _Providers.Find(p => p.UserId == userId && p.Name == name).FirstOrDefault() != null ? true : false; ; + return _Providers.Find(p => p.HomeId == homeId).ToList(); + } + + public bool AlreadyExistForHome(string homeId, string name) + { + return _Providers.Find(p => p.HomeId == homeId && p.Name == name).FirstOrDefault() != null ? true : false; ; } public Provider GetByName(string name) @@ -38,7 +43,7 @@ namespace MyCore.Services.MyControlPanel return _Providers.Find(p => p.Name == name).FirstOrDefault(); } - public Provider GetByType(string type) + public Provider GetByType(ProviderType type) { return _Providers.Find(p => p.Type == type).FirstOrDefault(); } diff --git a/MyCore/Services/MyControlPanel/Database/RoomDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/RoomDatabaseService.cs index a0389ef..80d0db2 100644 --- a/MyCore/Services/MyControlPanel/Database/RoomDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/RoomDatabaseService.cs @@ -6,7 +6,7 @@ using MyCore.Interfaces.Models; using Microsoft.Extensions.Configuration; using MongoDB.Driver; -namespace MyCore.Services.MyControlPanel +namespace MyCore.Services { public class RoomDatabaseService { @@ -18,9 +18,9 @@ namespace MyCore.Services.MyControlPanel var database = client.GetDatabase("MyCoreDb"); _Rooms = database.GetCollection("Rooms"); } - public List GetAll(string userId) + public List GetAll(string homeId) { - return _Rooms.Find(d => d.UserId == userId).ToList(); + return _Rooms.Find(d => d.HomeId == homeId).ToList(); } public Room GetById(string id) @@ -50,9 +50,9 @@ namespace MyCore.Services.MyControlPanel _Rooms.DeleteOne(room => room.Id == id); } - public void RemoveForUser(string userId) + public void RemoveForHome(string homeId) { - _Rooms.DeleteMany(room => room.UserId == userId); + _Rooms.DeleteMany(room => room.HomeId == homeId); } } } diff --git a/MyCore/Services/MyControlPanel/Database/UserDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/UserDatabaseService.cs index 411dc68..89d26df 100644 --- a/MyCore/Services/MyControlPanel/Database/UserDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/UserDatabaseService.cs @@ -38,15 +38,31 @@ namespace MyCore.Services return _Users.Find(d => d.Id == id).FirstOrDefault() != null ? true : false; } + public bool IsExistMultiple(List ids) + { + foreach (var id in ids) + { + if (_Users.Find(d => d.Id == id).FirstOrDefault() == null) + return false; + } + return true; + } + + public UserInfo Create(UserInfo user) { _Users.InsertOne(user); return user; } - public UserInfo Update(string id, UserInfo userIn) + public List GetByHomeId(string homeId) { - _Users.ReplaceOne(user => user.Id == id, userIn); + return _Users.Find(h => h.HomeIds.Contains(homeId)).ToList(); + } + + public UserInfo Update(UserInfo userIn) + { + _Users.ReplaceOne(user => user.Id == userIn.Id, userIn); return userIn; } diff --git a/MyCore/Services/MyControlPanel/HomeService.cs b/MyCore/Services/MyControlPanel/HomeService.cs new file mode 100644 index 0000000..e0fc1da --- /dev/null +++ b/MyCore/Services/MyControlPanel/HomeService.cs @@ -0,0 +1,46 @@ +using MyCore.Interfaces.DTO; +using MyCore.Interfaces.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace MyCore.Services +{ + public class HomeService + { + public static bool IsExist(HomeDatabaseService _HomeDatabaseService, string homeId) + { + return _HomeDatabaseService.GetById(homeId) != null ? true : false ; + } + + public static Home CreateOrUpdate(HomeDatabaseService _HomeDatabaseService, AlarmDatabaseService _AlarmDatabaseService, CreateOrUpdateHomeDTO createOrUpdateHomeDTO, bool create) + { + Home home; + if (create) + home = new Home(); + else + { + home = _HomeDatabaseService.GetById(createOrUpdateHomeDTO.Id); + home.CurrentAlarmMode = _AlarmDatabaseService.IsExist(createOrUpdateHomeDTO.CurrentAlarmMode.Id) ? _AlarmDatabaseService.GetById(createOrUpdateHomeDTO.CurrentAlarmMode.Id) : null; + } + + home.Name = createOrUpdateHomeDTO.Name; + home.CreatedDate = create ? DateTime.Now : createOrUpdateHomeDTO.CreatedDate; + home.UpdatedDate = DateTime.Now; + home.IsAlarm = createOrUpdateHomeDTO.IsAlarm; + home.UsersIds = createOrUpdateHomeDTO.UsersIds.ToArray(); + // Todo : check if necessary + /*home.Users = homeDetail.Users; + home.Automations = homeDetail.Automations; + home.Devices = homeDetail.Devices; + home.Providers = homeDetail.Providers;*/ + + if (create) + return _HomeDatabaseService.Create(home); + else + return _HomeDatabaseService.Update(home.Id, home); + } + } +} + diff --git a/MyCore/Services/MyControlPanel/ProviderService.cs b/MyCore/Services/MyControlPanel/ProviderService.cs index 341f903..2f99714 100644 --- a/MyCore/Services/MyControlPanel/ProviderService.cs +++ b/MyCore/Services/MyControlPanel/ProviderService.cs @@ -10,40 +10,30 @@ namespace MyCore.Services.MyControlPanel { public class ProviderService { - static List supportedProviders = new List() { - "arlo", - "meross", - "yeelight", - "zigbee2mqtt" - }; - - public static bool IsExist(ProviderDatabaseService _ProviderDatabaseService, string userId, string providerId) + public static bool IsExist(ProviderDatabaseService _ProviderDatabaseService, string homeId, string providerId) { - return _ProviderDatabaseService.GetById(userId, providerId) != null ? true : false; + return _ProviderDatabaseService.GetById(homeId, providerId) != null ? true : false; } - public static List GetAll(ProviderDatabaseService _ProviderDatabaseService, string userId) + public static List GetAll(ProviderDatabaseService _ProviderDatabaseService, string homeId) { - return _ProviderDatabaseService.GetAll(userId); + return _ProviderDatabaseService.GetAll(homeId); } - public static ProviderDTO CreateOrUpdate(ProviderDatabaseService _ProviderDatabaseService, string userId, ProviderDTO providerDTO, bool create) + public static ProviderDTO CreateOrUpdate(ProviderDatabaseService _ProviderDatabaseService, string homeId, ProviderDTO providerDTO, bool create) { Provider provider; if (create) provider = new Provider(); else { - provider = _ProviderDatabaseService.GetById(userId, providerDTO.Id); + provider = _ProviderDatabaseService.GetById(homeId, providerDTO.Id); } - if (!IsProviderSupported(providerDTO.Type)) - throw new KeyNotFoundException("Provider is not yet supported"); - provider.Type = providerDTO.Type; provider.Name = providerDTO.Name; provider.Endpoint = providerDTO.Endpoint; - provider.UserId = providerDTO.UserId; + provider.HomeId = providerDTO.HomeId; provider.Username = providerDTO.Username; provider.Password = providerDTO.Password; provider.ApiKey = providerDTO.ApiKey; @@ -55,20 +45,9 @@ namespace MyCore.Services.MyControlPanel return _ProviderDatabaseService.Update(provider.Id, provider).ToDTO(); } - public static Provider GetProviderById(ProviderDatabaseService _ProviderDatabaseService, string userId, string providerId) + public static Provider GetProviderById(ProviderDatabaseService _ProviderDatabaseService, string homeId, string providerId) { - return _ProviderDatabaseService.GetById(userId, providerId); - } - - // TODO Get supported services - public static List GetSupportedProvider() - { - return supportedProviders; - } - - public static bool IsProviderSupported(string providerName) - { - return supportedProviders.Contains(providerName) ? true : false; + return _ProviderDatabaseService.GetById(homeId, providerId); } } } diff --git a/MyCore/Services/MyControlPanel/UserService.cs b/MyCore/Services/MyControlPanel/UserService.cs deleted file mode 100644 index 2d01cec..0000000 --- a/MyCore/Services/MyControlPanel/UserService.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace MyCore.Services.MyControlPanel -{ - public class UserService - { - public static bool IsExist(UserDatabaseService _UserDatabaseService, string userId) - { - return _UserDatabaseService.GetById(userId) != null ? true : false ; - } - } -} - diff --git a/MyCore/Services/RoomService.cs b/MyCore/Services/RoomService.cs index 0f61022..134c6b2 100644 --- a/MyCore/Services/RoomService.cs +++ b/MyCore/Services/RoomService.cs @@ -1,5 +1,6 @@ using MyCore.Interfaces.DTO; using MyCore.Interfaces.Models; +using MyCore.Services; using MyCore.Services.MyControlPanel; using System; using System.Collections.Generic; @@ -10,7 +11,7 @@ namespace MyCore.Service { public class RoomService { - public static RoomDetailDTO CreateOrUpdate(RoomDatabaseService _RoomDatabaseService, DeviceDatabaseService _DeviceDatabaseService, string userId, RoomCreateOrUpdateDetailDTO roomCreateOrUpdateDetailDTO, bool create) + public static RoomDetailDTO CreateOrUpdate(RoomDatabaseService _RoomDatabaseService, DeviceDatabaseService _DeviceDatabaseService, string homeId, RoomCreateOrUpdateDetailDTO roomCreateOrUpdateDetailDTO, bool create) { List devices = new List(); Room room; @@ -24,12 +25,12 @@ namespace MyCore.Service room = _RoomDatabaseService.GetById(roomCreateOrUpdateDetailDTO.Id); } - room.UserId = userId; + room.HomeId = homeId; room.Name = roomCreateOrUpdateDetailDTO.Name; room.UpdatedDate = DateTime.Now; List currentDevices = _DeviceDatabaseService.GetByIds(roomCreateOrUpdateDetailDTO.DeviceIds); // A device cannot have multiple rooms. Filter list - currentDevices = currentDevices.Where(c => c.LocationId == null).ToList(); // TODO add exception or something + currentDevices = currentDevices.Where(c => c.RoomId == null).ToList(); // TODO add exception or something if (create) { @@ -46,7 +47,7 @@ namespace MyCore.Service { Device device = _DeviceDatabaseService.GetById(deviceId); devices.Add(device); - device.LocationId = room.Id; + device.RoomId = room.Id; _DeviceDatabaseService.Update(device); } diff --git a/MyCore/Startup.cs b/MyCore/Startup.cs index a5cda8b..01b49d4 100644 --- a/MyCore/Startup.cs +++ b/MyCore/Startup.cs @@ -62,9 +62,9 @@ namespace MyCore Configuration.GetSection(nameof(BrokerHostSettings)).Bind(brokerHostSettings); AppSettingsProvider.BrokerHostSettings = brokerHostSettings; - BrokerHostSettings brokerOnlineHostSettings = new BrokerHostSettings(); + /*BrokerHostSettings brokerOnlineHostSettings = new BrokerHostSettings(); Configuration.GetSection(nameof(BrokerHostSettings)).Bind(brokerOnlineHostSettings); - AppSettingsOnlineProvider.BrokerHostOnlineSettings = brokerOnlineHostSettings; + AppSettingsOnlineProvider.BrokerHostOnlineSettings = brokerOnlineHostSettings;*/ } private void MapClientSettings() @@ -73,9 +73,9 @@ namespace MyCore Configuration.GetSection(nameof(ClientSettings)).Bind(clientSettings); AppSettingsProvider.ClientSettings = clientSettings; - ClientSettings clientOnlineSettings = new ClientSettings(); + /*ClientSettings clientOnlineSettings = new ClientSettings(); Configuration.GetSection(nameof(ClientSettings)).Bind(clientOnlineSettings); - AppSettingsOnlineProvider.ClientOnlineSettings = clientOnlineSettings; + AppSettingsOnlineProvider.ClientOnlineSettings = clientOnlineSettings;*/ } // This method gets called by the runtime. Use this method to add services to the container. @@ -140,10 +140,11 @@ namespace MyCore }; }); - services.AddMqttClientHostedService(); // Todo client files (a lot are useless) - services.AddMqttClientOnlineHostedService(); + + //services.AddMqttClientOnlineHostedService(); - services.AddMerossClientHostedService(); // Todo client files (a lot are useless) + // Comment this line when dev + //services.AddMerossClientHostedService(); // Todo client files (a lot are useless) services.AddScoped(); // To clarify if needed.. ? @@ -153,13 +154,16 @@ namespace MyCore services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); + services.AddScoped(); + + services.AddMqttClientHostedService(); // Todo client files (a lot are useless) } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.