diff --git a/.env b/.env new file mode 100644 index 0000000..eafc6c7 --- /dev/null +++ b/.env @@ -0,0 +1,4 @@ +POSTGRES_USER="postgres" +POSTGRES_PASSWORD="12345" +POSTGRES_DB="main_database" +DB_CONNECTION_STRING="Host=postgres:5432;Database=${POSTGRES_DB};Username=${POSTGRES_USER};Password=${POSTGRES_PASSWORD}" \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..26212b2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,399 @@ +# ---> VisualStudio +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..e8a7501 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,35 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md. + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/Cloud/bin/Debug/net6.0/Cloud.dll", + "args": [], + "cwd": "${workspaceFolder}/Cloud", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..c17f084 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "dotnet.defaultSolution": "Cloud.sln" +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..d410234 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,41 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/Cloud.sln", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary;ForceNoAlign" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/Cloud.sln", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary;ForceNoAlign" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/Cloud.sln" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/Cloud.sln b/Cloud.sln new file mode 100644 index 0000000..215c0ae --- /dev/null +++ b/Cloud.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cloud", "Cloud\Cloud.csproj", "{D279AAA9-D4F8-4C7B-B34D-44A7429C87AA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D279AAA9-D4F8-4C7B-B34D-44A7429C87AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D279AAA9-D4F8-4C7B-B34D-44A7429C87AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D279AAA9-D4F8-4C7B-B34D-44A7429C87AA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D279AAA9-D4F8-4C7B-B34D-44A7429C87AA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/Cloud/ApplicationContext.cs b/Cloud/ApplicationContext.cs new file mode 100644 index 0000000..681040d --- /dev/null +++ b/Cloud/ApplicationContext.cs @@ -0,0 +1,31 @@ +using Cloud.Models; +using Microsoft.EntityFrameworkCore; + +namespace Cloud; +public class ApplicationContext : DbContext +{ + public DbSet Users { get; set; } = null!; + public DbSet Farms { get; set; } = null!; + public DbSet Greenhouses { get; set; } = null!; + + public ApplicationContext(DbContextOptions options) + : base(options) + { + } + + public ApplicationContext() + : base(new DbContextOptionsBuilder() + .UseNpgsql("Host=localhost;Port=5438;Database=main_database;Username=postgres;Password=12345") + .Options) + { + Database.EnsureCreated(); + } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (!optionsBuilder.IsConfigured) + { + optionsBuilder.UseNpgsql("Host=localhost;Port=5438;Database=main_database;Username=postgres;Password=12345"); + } + } +} diff --git a/Cloud/Cloud.csproj b/Cloud/Cloud.csproj new file mode 100644 index 0000000..042333f --- /dev/null +++ b/Cloud/Cloud.csproj @@ -0,0 +1,24 @@ + + + + net6.0 + enable + enable + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/Cloud/Controllers/AuthController.cs b/Cloud/Controllers/AuthController.cs new file mode 100644 index 0000000..c63a89c --- /dev/null +++ b/Cloud/Controllers/AuthController.cs @@ -0,0 +1,104 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Identity; +using Cloud.Models; +using Cloud.Requests; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Text; +using Microsoft.EntityFrameworkCore; +using Microsoft.AspNetCore.Authorization; +using System.Security.Claims; + +namespace Cloud.Controllers; + +[ApiController] +[Route("api/[controller]")] +public class AuthController : ControllerBase +{ + private PasswordHasher _passwordHasher; + private IConfiguration _config; + private ApplicationContext _context; + + public AuthController(IConfiguration config, ApplicationContext context) + { + _passwordHasher = new PasswordHasher(); + _config = config; + _context = context; + } + + [HttpPost("register")] + public async Task Register([FromBody] RegisterRequest request) + { + var existUser = await _context.Users.SingleOrDefaultAsync(u => u.Email == request.Email); + + if (existUser != null) { + return BadRequest("Пользователь с такой эл. почтой уже существует"); + } + + var user = new User + { + Name = request.Name, + Email = request.Email, + Password = _passwordHasher.HashPassword(null, request.Password) + }; + + _context.Users.Add(user); + await _context.SaveChangesAsync(); + + return Ok("Пользователь успешно зарегистрирован"); + } + + [HttpPost("login")] + public async Task Login([FromBody] LoginRequest request) + { + var user = await _context.Users.SingleOrDefaultAsync(u => u.Email == request.Email); + + if (user == null) { + return Unauthorized("Пользователя с такой эл. почтой не существует"); + } + + var verificationResult = _passwordHasher.VerifyHashedPassword(null, user.Password, request.Password); + + if (verificationResult == PasswordVerificationResult.Failed) { + return Unauthorized("Неверный пароль"); + } + + var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); + var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); + + var claims = new[] + { + new Claim(ClaimTypes.Name, user.Email), + }; + + var Sectoken = new JwtSecurityToken(_config["Jwt:Issuer"], + _config["Jwt:Issuer"], + claims: claims, + expires: DateTime.Now.AddMinutes(120), + signingCredentials: credentials); + + var token = new JwtSecurityTokenHandler().WriteToken(Sectoken); + + return Ok(token); + } + + [Authorize] + [HttpGet("user")] + public async Task GetAuthUser() + { + var userEmail = User.Identity.Name; + + var user = await _context.Users.SingleOrDefaultAsync(u => u.Email == userEmail); + + if (user == null) { + return NotFound("Пользователь не найден"); + } + + return Ok(new + { + user.Id, + user.Name, + user.Email + }); + } +} \ No newline at end of file diff --git a/Cloud/Controllers/FarmController.cs b/Cloud/Controllers/FarmController.cs new file mode 100644 index 0000000..b5cf078 --- /dev/null +++ b/Cloud/Controllers/FarmController.cs @@ -0,0 +1,128 @@ +using Cloud.Models; +using Cloud.Requests; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace Cloud.Controllers +{ + [Authorize] + [ApiController] + [Route("api/user")] + public class FarmController : ControllerBase + { + private IConfiguration _config; + private ApplicationContext _context; + + public FarmController(IConfiguration config, ApplicationContext context) + { + _config = config; + _context = context; + } + + [HttpGet("{userId}/farm")] + public async Task>> Index(int userId) + { + try + { + List farms = await + _context.Farms.Where(x => x.UserId == userId).AsNoTracking().ToListAsync(); + if (!farms.Any()) + return NotFound("Farms is not found"); + + return Ok(farms); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + [HttpGet("{userId}/farm/{farmId}")] + public async Task> Show(int userId, int farmId) + { + try + { + Farm? farm = await + _context.Farms.FirstOrDefaultAsync(x => x.UserId == userId && x.Id == farmId); + + if (farm == null) + return NotFound("Farm is not found"); + + return Ok(farm); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + [HttpPost("{userId}/farm")] + public async Task> Create([FromBody] FarmRequest farmRequest, int userId) + { + try + { + var farm = new Farm + { + Name = farmRequest.Name, + UserId = userId, + RaspberryIP = farmRequest.RaspberryIP, + }; + + Farm? farmCreated = _context.Farms.Add(farm).Entity; + await _context.SaveChangesAsync(); + + return Ok(farmCreated); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + [HttpPut("{userId}/farm/{farmId}")] + public async Task> Update([FromBody] FarmRequest farmRequest, int userId, int farmId) + { + try + { + Farm? farm = await _context.Farms.FirstOrDefaultAsync(x => x.Id == farmId && x.UserId == userId); + + if (farm == null) + return NotFound("Farm is not found"); + + farm.Name = farmRequest.Name; + farm.RaspberryIP = farmRequest.RaspberryIP; + + _context.Farms.Update(farm); + await _context.SaveChangesAsync(); + + return Ok(farm); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + [HttpDelete("{userId}/farm/{farmId}")] + public async Task Delete(int userId, int farmId) + { + try + { + Farm? farm = await _context.Farms.FirstOrDefaultAsync(x => x.Id == farmId && x.UserId == userId); + + if (farm == null) + return NotFound("Farm is not found"); + + _context.Farms.Remove(farm); + await _context.SaveChangesAsync(); + + return Ok("Farm deleted successfully"); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/Cloud/Controllers/GreengouseController.cs b/Cloud/Controllers/GreengouseController.cs new file mode 100644 index 0000000..9f4c025 --- /dev/null +++ b/Cloud/Controllers/GreengouseController.cs @@ -0,0 +1,160 @@ +using Cloud.Models; +using Cloud.Requests; +using Cloud.Services.Broker; +using Cloud.Services.Broker.Support; +using Cloud.Services.Domain; +using Microsoft.AspNetCore.Mvc; + +namespace Cloud.Controllers +{ + [ApiController] + [Route("api/farm/{farmId}/greenhouse")] + public class GreenhouseController : ControllerBase + { + private readonly IGreenhouseService _greenhouseService; + public GreenhouseController(IGreenhouseService greenhouseService) + { + _greenhouseService = greenhouseService; + } + + /// + /// Возвращает текущую информацию о всех теплицах пользователя + /// + /// + /// + [HttpGet] + public async Task>> GetAll(int farmId) + { + try + { + var greenhouses = _greenhouseService.GetAll(farmId); + if (greenhouses == null) return NotFound("Greenhouses is not found"); + return Ok(greenhouses); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + /// + /// Возвращает текущую информацию о конкретной теплице + /// + /// + /// + /// + [HttpGet("{greenhouseId}")] + public async Task> Get(int farmId, int greenhouseId) + { + try + { + var greenhouses = _greenhouseService.GetGreenhouseInfo(greenhouseId, farmId); + return Ok(greenhouses); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + /// + /// Возвращает сохраненные данные для автоматизации теплицы + /// + /// + /// + /// + [HttpGet("{greenhouseId}/settings")] + public async Task> GetGreenhouse(int farmId, int greenhouseId) + { + try + { + var greenhouse = await _greenhouseService.GetGreenhouse(greenhouseId); + if (greenhouse == null) return NotFound("Greenhouses is not found"); + return Ok(greenhouse); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + /// + /// Сохраняет в базе данных API данные для автоматизации теплицы + /// + /// + /// + /// + [HttpPost] + public async Task> SaveToDatabase(int farmId, GreenhouseRequest greenhouse) + { + try + { + var greenhouseEntity = new Greenhouse() + { + RecomendedTemperature = greenhouse.RecomendedTemperature, + WateringMode = greenhouse.WateringMode, + HeatingMode = greenhouse.HeatingMode + }; + + var result = await _greenhouseService.Create(greenhouseEntity); + return Ok(result); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + + } + + + /// + /// Обновляет в базе данных API данные для автоматизации теплицы + /// + /// ID фермы + /// ID теплицы + /// Данные для обновления + /// Обновленный объект Greenhouse + [HttpPut("{greenhouseId}/settings")] + public async Task> Update(int farmId, int greenhouseId, GreenhouseRequest greenhouse) + { + try + { + var greenhouseEntity = new Greenhouse() + { + Id = greenhouseId, + FarmId = farmId, + WateringMode = greenhouse.WateringMode, + HeatingMode = greenhouse.HeatingMode, + RecomendedTemperature = greenhouse.RecomendedTemperature + }; + + var result = await _greenhouseService.Update(greenhouseEntity); + return Ok(result); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + + /// + /// Удаляет из базы данных API запись настроек автоматизации теплицы + /// + /// + /// + /// + [HttpDelete("{greenhouseId}")] + public async Task Delete(int farmId, int greenhouseId) + { + try + { + _ = await _greenhouseService.Delete(greenhouseId); + return Ok(); + } + catch (Exception ex) + { + return BadRequest(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/Cloud/Controllers/ValveController.cs b/Cloud/Controllers/ValveController.cs new file mode 100644 index 0000000..9fc973a --- /dev/null +++ b/Cloud/Controllers/ValveController.cs @@ -0,0 +1,43 @@ +using Cloud.Requests; +using Cloud.Services; +using Cloud.Services.Broker; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System.ComponentModel.DataAnnotations; +using System.Text.Json; + +namespace Cloud.Controllers +{ + [Authorize] + [ApiController] + [Route("api")] + public class ValveController : ControllerBase + { + //Контроллер вентиля + + private readonly IBrokerService _kafkaService; + + public ValveController(IBrokerService kafkaService) + { + _kafkaService = kafkaService; + } + + [HttpPost("farm/{farmId}/greenhouse/{ghId}/watering")] + public async Task interactValve([FromBody] ValveRequest request, int farmId, int ghId) + { + var kafkaRequest = new + { + FarmId = farmId, + GreenHouseId = ghId, + SomeAction = request.Action, + }; + + var message = JsonSerializer.Serialize(kafkaRequest); + return Ok(kafkaRequest); + + /*await _kafkaService.ProduceAsync("ValvesHeatersRequest", message); + + return Ok($"Valve status is {request.Action}");*/ + } + } +} diff --git a/Cloud/Dockerfile b/Cloud/Dockerfile new file mode 100644 index 0000000..b4c2152 --- /dev/null +++ b/Cloud/Dockerfile @@ -0,0 +1,30 @@ +FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +WORKDIR /app +EXPOSE 5124 + +ENV ASPNETCORE_URLS=http://+:5124 + +# Creates a non-root user with an explicit UID and adds permission to access the /app folder +# For more info, please refer to https://aka.ms/vscode-docker-dotnet-configure-containers +RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app +USER appuser + +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +ARG configuration=Development +WORKDIR /src +COPY ["Cloud.csproj", "."] +RUN dotnet restore "./Cloud.csproj" +COPY . . +WORKDIR "/src/." +RUN dotnet build "./Cloud.csproj" -c $configuration -o /app/build + +FROM build AS publish +ARG configuration=Development +RUN dotnet publish "./Cloud.csproj" -c $configuration -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . + +ENTRYPOINT ["dotnet", "Cloud.dll"] + diff --git a/Cloud/Enums/ValveEnum.cs b/Cloud/Enums/ValveEnum.cs new file mode 100644 index 0000000..f04d64a --- /dev/null +++ b/Cloud/Enums/ValveEnum.cs @@ -0,0 +1,9 @@ +namespace Cloud.Enums +{ + public enum ValveEnum + { + Open, + Close, + Auto + } +} diff --git a/Cloud/Middlewares/DatabaseMiddleware.cs b/Cloud/Middlewares/DatabaseMiddleware.cs new file mode 100644 index 0000000..88091bf --- /dev/null +++ b/Cloud/Middlewares/DatabaseMiddleware.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore; + +namespace Cloud.Middlewares; + +public static class DatabaseMiddleware +{ + public static void AddDbConnectionService(this IServiceCollection services) + { + string connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING") + ?? "Host=localhost;Port=5438;Database=main_database;Username=postgres;Password=12345"; + + services.AddDbContext(options => + options.UseNpgsql(connectionString)); + + } + public static void MigrateDb(this IApplicationBuilder app) + { + try + { + using var scope = app.ApplicationServices.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); + + context.Database.Migrate(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/Cloud/Migrations/20241027220558_CreateUsersTable.Designer.cs b/Cloud/Migrations/20241027220558_CreateUsersTable.Designer.cs new file mode 100644 index 0000000..d1c7360 --- /dev/null +++ b/Cloud/Migrations/20241027220558_CreateUsersTable.Designer.cs @@ -0,0 +1,53 @@ +// +using Cloud; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Cloud.Migrations +{ + [DbContext(typeof(ApplicationContext))] + [Migration("20241027220558_CreateUsersTable")] + partial class CreateUsersTable + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Cloud.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Cloud/Migrations/20241027220558_CreateUsersTable.cs b/Cloud/Migrations/20241027220558_CreateUsersTable.cs new file mode 100644 index 0000000..4c9a4dd --- /dev/null +++ b/Cloud/Migrations/20241027220558_CreateUsersTable.cs @@ -0,0 +1,34 @@ +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Cloud.Migrations +{ + public partial class CreateUsersTable : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false), + Email = table.Column(type: "text", nullable: false), + Password = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git a/Cloud/Migrations/20241028192806_CreateFarmsTable.Designer.cs b/Cloud/Migrations/20241028192806_CreateFarmsTable.Designer.cs new file mode 100644 index 0000000..4bc7f80 --- /dev/null +++ b/Cloud/Migrations/20241028192806_CreateFarmsTable.Designer.cs @@ -0,0 +1,95 @@ +// +using Cloud; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Cloud.Migrations +{ + [DbContext(typeof(ApplicationContext))] + [Migration("20241028192806_CreateFarmsTable")] + partial class CreateFarmsTable + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Cloud.Models.Farm", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RaspberryMacAddr") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Farms"); + }); + + modelBuilder.Entity("Cloud.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Cloud.Models.Farm", b => + { + b.HasOne("Cloud.Models.User", "User") + .WithMany("Farms") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Cloud.Models.User", b => + { + b.Navigation("Farms"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Cloud/Migrations/20241028192806_CreateFarmsTable.cs b/Cloud/Migrations/20241028192806_CreateFarmsTable.cs new file mode 100644 index 0000000..a297728 --- /dev/null +++ b/Cloud/Migrations/20241028192806_CreateFarmsTable.cs @@ -0,0 +1,45 @@ +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Cloud.Migrations +{ + public partial class CreateFarmsTable : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Farms", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false), + UserId = table.Column(type: "integer", nullable: false), + RaspberryMacAddr = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Farms", x => x.Id); + table.ForeignKey( + name: "FK_Farms_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Farms_UserId", + table: "Farms", + column: "UserId"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Farms"); + } + } +} diff --git a/Cloud/Migrations/20241030111034_front.Designer.cs b/Cloud/Migrations/20241030111034_front.Designer.cs new file mode 100644 index 0000000..017938b --- /dev/null +++ b/Cloud/Migrations/20241030111034_front.Designer.cs @@ -0,0 +1,95 @@ +// +using Cloud; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Cloud.Migrations +{ + [DbContext(typeof(ApplicationContext))] + [Migration("20241030111034_front")] + partial class front + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Cloud.Models.Farm", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RaspberryMacAddr") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Farms"); + }); + + modelBuilder.Entity("Cloud.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Cloud.Models.Farm", b => + { + b.HasOne("Cloud.Models.User", "User") + .WithMany("Farms") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Cloud.Models.User", b => + { + b.Navigation("Farms"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Cloud/Migrations/20241030111034_front.cs b/Cloud/Migrations/20241030111034_front.cs new file mode 100644 index 0000000..9ca6bc8 --- /dev/null +++ b/Cloud/Migrations/20241030111034_front.cs @@ -0,0 +1,19 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Cloud.Migrations +{ + public partial class front : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + + } + } +} diff --git a/Cloud/Migrations/ApplicationContextModelSnapshot.cs b/Cloud/Migrations/ApplicationContextModelSnapshot.cs new file mode 100644 index 0000000..c499a41 --- /dev/null +++ b/Cloud/Migrations/ApplicationContextModelSnapshot.cs @@ -0,0 +1,93 @@ +// +using Cloud; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Cloud.Migrations +{ + [DbContext(typeof(ApplicationContext))] + partial class ApplicationContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Cloud.Models.Farm", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RaspberryMacAddr") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Farms"); + }); + + modelBuilder.Entity("Cloud.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Cloud.Models.Farm", b => + { + b.HasOne("Cloud.Models.User", "User") + .WithMany("Farms") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Cloud.Models.User", b => + { + b.Navigation("Farms"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Cloud/Models/Farm.cs b/Cloud/Models/Farm.cs new file mode 100644 index 0000000..48fd855 --- /dev/null +++ b/Cloud/Models/Farm.cs @@ -0,0 +1,12 @@ +namespace Cloud.Models +{ + public class Farm + { + public int Id { get; set; } + public string Name { get; set; } + public int UserId { get; set; } + public User? User { get; set; } + public string RaspberryIP { get; set; } + List Greenhouses { get; set; } = new(); + } +} \ No newline at end of file diff --git a/Cloud/Models/Greenhouse.cs b/Cloud/Models/Greenhouse.cs new file mode 100644 index 0000000..ec2f54a --- /dev/null +++ b/Cloud/Models/Greenhouse.cs @@ -0,0 +1,14 @@ +using Cloud.Models.Support; + +namespace Cloud.Models +{ + public class Greenhouse + { + public int Id { get; set; } + public int RecomendedTemperature { get; set; } + public WateringMode WateringMode { get; set; } + public HeatingMode HeatingMode { get; set; } + public int FarmId { get; set; } + public Farm? Farm { get; set; } + } +} \ No newline at end of file diff --git a/Cloud/Models/Support/HeatingMode.cs b/Cloud/Models/Support/HeatingMode.cs new file mode 100644 index 0000000..81f082e --- /dev/null +++ b/Cloud/Models/Support/HeatingMode.cs @@ -0,0 +1,8 @@ +namespace Cloud.Models.Support +{ + public enum HeatingMode + { + Manual, + Auto + } +} \ No newline at end of file diff --git a/Cloud/Models/Support/WateringMode.cs b/Cloud/Models/Support/WateringMode.cs new file mode 100644 index 0000000..3e58fe4 --- /dev/null +++ b/Cloud/Models/Support/WateringMode.cs @@ -0,0 +1,8 @@ +namespace Cloud.Models.Support +{ + public enum WateringMode + { + Manual, + Auto + } +} \ No newline at end of file diff --git a/Cloud/Models/User.cs b/Cloud/Models/User.cs new file mode 100644 index 0000000..269dec4 --- /dev/null +++ b/Cloud/Models/User.cs @@ -0,0 +1,13 @@ +namespace Cloud.Models; +public class User +{ + public int Id { get; set; } + + public string Name { get; set; } + + public string Email { get; set; } + + public string Password { get; set; } + + public List Farms { get; set; } = new(); +} \ No newline at end of file diff --git a/Cloud/Program.cs b/Cloud/Program.cs new file mode 100644 index 0000000..16d0c36 --- /dev/null +++ b/Cloud/Program.cs @@ -0,0 +1,133 @@ +using Cloud; +using Microsoft.EntityFrameworkCore; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.IdentityModel.Tokens; +using System.Text; +using FluentValidation; +using FluentValidation.AspNetCore; +using Cloud.Validation; +using StackExchange.Redis; +using Cloud.Services.Broker.Implement.Kafka; +using Cloud.Services.Broker; +using Cloud.Services; +using Cloud.Services.Domain.Implement; +using Cloud.Services.Domain; +using Cloud.Services.Cache; +using Cloud.Support; +using System.Text.RegularExpressions; +using Cloud.Middlewares; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddSingleton(); +builder.Services.AddTransient(); + +//Redis configuration +string redisUrl = Environment.GetEnvironmentVariable("REDIS_URL") ?? "localhost:6379"; +builder.Services.AddSingleton(sp => +{ + var configuration = ConfigurationOptions.Parse(redisUrl); + return ConnectionMultiplexer.Connect(configuration); +}); +builder.Services.AddSingleton(); + +//Jwt configuration +var jwtIssuer = builder.Configuration.GetSection("Jwt:Issuer").Get(); +var jwtKey = builder.Configuration.GetSection("Jwt:Key").Get(); + +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = jwtIssuer, + ValidAudience = jwtIssuer, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)) + }; + }); +// Настройка подключения к БД +builder.Services.AddDbConnectionService(); +// Настройка CORS +string frontUrl = Environment.GetEnvironmentVariable("FRONT_URL") ?? "http://localhost:3000"; +builder.Services.AddCors(options => +{ + options.AddPolicy("AllowFrontendLocalhost", builder => + { + builder.WithOrigins(frontUrl) // фронтенд + .AllowAnyHeader() + .AllowAnyMethod(); + }); +}); + +builder.Services.AddControllers(); +builder.Services.AddFluentValidationAutoValidation(); +builder.Services.AddFluentValidationClientsideAdapters(); +builder.Services.AddValidatorsFromAssemblyContaining(); +builder.Services.AddValidatorsFromAssemblyContaining(); +builder.Services.AddValidatorsFromAssemblyContaining(); +builder.Services.AddValidatorsFromAssemblyContaining(); + +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(c => +{ + c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "Cloud API", Version = "v1" }); + + c.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme + { + Description = "Введите ваш Bearer токен", + Name = "Authorization", + In = Microsoft.OpenApi.Models.ParameterLocation.Header, + Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey + }); + + c.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement + { + { + new Microsoft.OpenApi.Models.OpenApiSecurityScheme + { + Reference = new Microsoft.OpenApi.Models.OpenApiReference + { + Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme, + Id = "Bearer" + } + }, + new string[] {} + } + }); +}); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + Console.WriteLine("Swagger enabled"); + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "Cloud API V1"); + c.RoutePrefix = string.Empty; + }); +} + +app.UseHttpsRedirection(); + +// Включение CORS +app.UseCors("AllowFrontendLocalhost"); + +// Применение миграций +app.MigrateDb(); + +app.UseAuthentication(); + +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); diff --git a/Cloud/Properties/launchSettings.json b/Cloud/Properties/launchSettings.json new file mode 100644 index 0000000..2e9e32f --- /dev/null +++ b/Cloud/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:43967", + "sslPort": 44304 + } + }, + "profiles": { + "Cloud": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7113;http://localhost:5124", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Cloud/Requests/FarmRequest.cs b/Cloud/Requests/FarmRequest.cs new file mode 100644 index 0000000..3371488 --- /dev/null +++ b/Cloud/Requests/FarmRequest.cs @@ -0,0 +1,8 @@ +namespace Cloud.Requests +{ + public class FarmRequest + { + public string Name { get; set; } + public string RaspberryIP { get; set; } + } +} \ No newline at end of file diff --git a/Cloud/Requests/GreenhouseRequest.cs b/Cloud/Requests/GreenhouseRequest.cs new file mode 100644 index 0000000..7f2fe80 --- /dev/null +++ b/Cloud/Requests/GreenhouseRequest.cs @@ -0,0 +1,11 @@ +using Cloud.Models.Support; + +namespace Cloud.Requests +{ + public class GreenhouseRequest + { + public int RecomendedTemperature { get; set; } + public WateringMode WateringMode { get; set; } + public HeatingMode HeatingMode { get; set; } + } +} \ No newline at end of file diff --git a/Cloud/Requests/LoginRequest.cs b/Cloud/Requests/LoginRequest.cs new file mode 100644 index 0000000..472da63 --- /dev/null +++ b/Cloud/Requests/LoginRequest.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Cloud.Requests; + +public class LoginRequest +{ + public string Email { get; set; } + + public string Password { get; set; } +} \ No newline at end of file diff --git a/Cloud/Requests/RegisterRequest.cs b/Cloud/Requests/RegisterRequest.cs new file mode 100644 index 0000000..a92e7a8 --- /dev/null +++ b/Cloud/Requests/RegisterRequest.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Cloud.Requests; + +public class RegisterRequest +{ + public string Name { get; set; } + + public string Email { get; set; } + + public string Password { get; set; } +} \ No newline at end of file diff --git a/Cloud/Requests/ValveRequest.cs b/Cloud/Requests/ValveRequest.cs new file mode 100644 index 0000000..dee6a5a --- /dev/null +++ b/Cloud/Requests/ValveRequest.cs @@ -0,0 +1,7 @@ +namespace Cloud.Requests +{ + public class ValveRequest + { + public string Action { get; set; } + } +} diff --git a/Cloud/Services/Broker/IBrokerConsumer.cs b/Cloud/Services/Broker/IBrokerConsumer.cs new file mode 100644 index 0000000..c152981 --- /dev/null +++ b/Cloud/Services/Broker/IBrokerConsumer.cs @@ -0,0 +1,9 @@ +using Cloud.Services.Broker.Support; + +namespace Cloud.Services.Broker +{ + public interface IBrokerConsumer + { + IEnumerable? WaitMessages(string topic) where T : IBrokerResponse; + } +} \ No newline at end of file diff --git a/Cloud/Services/Broker/IBrokerProducer.cs b/Cloud/Services/Broker/IBrokerProducer.cs new file mode 100644 index 0000000..abed579 --- /dev/null +++ b/Cloud/Services/Broker/IBrokerProducer.cs @@ -0,0 +1,9 @@ +using Cloud.Services.Broker.Support; + +namespace Cloud.Services.Broker +{ + public interface IBrokerProducer + { + Task ProduceAsync(string topic, Command command); + } +} \ No newline at end of file diff --git a/Cloud/Services/Broker/IBrokerService.cs b/Cloud/Services/Broker/IBrokerService.cs new file mode 100644 index 0000000..356157b --- /dev/null +++ b/Cloud/Services/Broker/IBrokerService.cs @@ -0,0 +1,9 @@ +using Cloud.Services.Broker.Support; + +namespace Cloud.Services.Broker +{ + public interface IBrokerService : IBrokerProducer, IBrokerConsumer + { + void ChangeBrokerIp(string ip); + } +} \ No newline at end of file diff --git a/Cloud/Services/Broker/Implement/Kafka/KafkaConsumer.cs b/Cloud/Services/Broker/Implement/Kafka/KafkaConsumer.cs new file mode 100644 index 0000000..f29a4b8 --- /dev/null +++ b/Cloud/Services/Broker/Implement/Kafka/KafkaConsumer.cs @@ -0,0 +1,93 @@ + +using Cloud.Services.Broker.Support; +using Confluent.Kafka; +using System.Diagnostics; +using System.Text.Json; + +namespace Cloud.Services.Broker.Implement.Kafka +{ + public class KafkaConsumer : IBrokerConsumer + { + private IConsumer _consumer; + private readonly IConfiguration _config; + + public KafkaConsumer(IConfiguration config) + { + _config = config; + Console.WriteLine($"KafkaConsumer created. IP:" + _config["KAFKA_URL"]); + ChangeBrokerIp(_config["KAFKA_URL"]); + } + + public IEnumerable? WaitMessages(string topic) + where T : IBrokerResponse + { + List res = new(); + List partitions; + + using var adminClient = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = _config["KAFKA_URL"] }).Build(); + var meta = adminClient.GetMetadata(TimeSpan.FromSeconds(20)); + var currentTopic = meta.Topics.SingleOrDefault(t => t.Topic == topic) + ?? throw new Exception($"Topic {topic} not found"); + partitions = currentTopic.Partitions; + + _consumer.Subscribe(topic); + foreach (var partition in partitions) + { + var topicPartition = new TopicPartition(topic, partition.PartitionId); + _consumer.Assign(topicPartition); + + T? message = _consume(); + if (message == null) return null; + res.Add(message); + + } + _consumer.Unassign(); + _consumer.Unsubscribe(); + return res; + } + + private T? _consume() where T : IBrokerResponse + { + var sw = new Stopwatch(); + sw.Start(); + try + { + while (true) + { + var consumeResult = _consumer.Consume(TimeSpan.FromMinutes(1)); + + if (consumeResult?.Message?.Value == null) + { + // Предел по времени + if (sw.Elapsed > TimeSpan.FromMinutes(1)) + { + return default; + } + continue; + } + + string jsonObj = consumeResult.Message.Value; + return JsonSerializer.Deserialize(jsonObj); + + } + } + catch (Exception ex) + { + _consumer.Close(); + throw; + } + } + + public void ChangeBrokerIp(string ip) + { + var consumerConfig = new ConsumerConfig() + { + BootstrapServers = ip, + GroupId = _config["Kafka:GroupId"], + AutoOffsetReset = AutoOffsetReset.Earliest, + }; + _consumer?.Close(); + _consumer = new ConsumerBuilder(consumerConfig).Build(); + } + } +} \ No newline at end of file diff --git a/Cloud/Services/Broker/Implement/Kafka/KafkaProducer.cs b/Cloud/Services/Broker/Implement/Kafka/KafkaProducer.cs new file mode 100644 index 0000000..6a916bb --- /dev/null +++ b/Cloud/Services/Broker/Implement/Kafka/KafkaProducer.cs @@ -0,0 +1,38 @@ +using System.Text.Json; +using Cloud.Services.Broker.Support; +using Confluent.Kafka; + +namespace Cloud.Services.Broker.Implement.Kafka +{ + public class KafkaProducer : IBrokerProducer + { + private IProducer _producer; + private readonly IConfiguration _config; + + public KafkaProducer(IConfiguration configuration) + { + _config = configuration; + Console.WriteLine($"KafkaProducer created. IP:" + _config["KAFKA_URL"]); + ChangeBrokerIp(_config["KAFKA_URL"]); + } + public async Task ProduceAsync(string topic, Command command) + { + var commandSerialized = JsonSerializer.Serialize(command); + var message = new Message { Key = Guid.NewGuid().ToString(), Value = commandSerialized }; + + //Produce the Message + await _producer.ProduceAsync(topic, message); + } + + public void ChangeBrokerIp(string ip) + { + var producerConfig = new ProducerConfig + { + BootstrapServers = ip + }; + + //Build the Producer + _producer = new ProducerBuilder(producerConfig).Build(); + } + } +} \ No newline at end of file diff --git a/Cloud/Services/Broker/Implement/Kafka/KafkaService.cs b/Cloud/Services/Broker/Implement/Kafka/KafkaService.cs new file mode 100644 index 0000000..8fc9174 --- /dev/null +++ b/Cloud/Services/Broker/Implement/Kafka/KafkaService.cs @@ -0,0 +1,30 @@ +using Cloud.Services.Broker.Support; + +namespace Cloud.Services.Broker.Implement.Kafka +{ + public class KafkaService : IBrokerService + { + private readonly KafkaProducer _producer; + private readonly KafkaConsumer _consumer; + + public KafkaService(IConfiguration configuration) + { + _producer = new KafkaProducer(configuration); + _consumer = new KafkaConsumer(configuration); + } + + public IEnumerable? WaitMessages(string topic) + where T : IBrokerResponse + => _consumer.WaitMessages(topic); + + + public async Task ProduceAsync(string topic, Command command) + => await _producer.ProduceAsync("commands", command); + + public void ChangeBrokerIp(string ip) + { + _consumer.ChangeBrokerIp(ip); + _producer.ChangeBrokerIp(ip); + } + } +} \ No newline at end of file diff --git a/Cloud/Services/Broker/Support/Command.cs b/Cloud/Services/Broker/Support/Command.cs new file mode 100644 index 0000000..2debae3 --- /dev/null +++ b/Cloud/Services/Broker/Support/Command.cs @@ -0,0 +1,10 @@ +using System.Text.Json; + +namespace Cloud.Services.Broker.Support +{ + public class Command + { + public Guid GreenhouseId { get; set; } + public string CommandName { get; set; } = null!; + } +} \ No newline at end of file diff --git a/Cloud/Services/Broker/Support/CommandResult.cs b/Cloud/Services/Broker/Support/CommandResult.cs new file mode 100644 index 0000000..e66004d --- /dev/null +++ b/Cloud/Services/Broker/Support/CommandResult.cs @@ -0,0 +1,9 @@ +namespace Cloud.Services.Broker.Support +{ + public class CommandResult : IBrokerResponse + { + public int CommandId { get; set; } + public int GreenhouseId { get; set; } + public string ResultMessage { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/Cloud/Services/Broker/Support/GreenhouseInfo.cs b/Cloud/Services/Broker/Support/GreenhouseInfo.cs new file mode 100644 index 0000000..bea028b --- /dev/null +++ b/Cloud/Services/Broker/Support/GreenhouseInfo.cs @@ -0,0 +1,12 @@ +namespace Cloud.Services.Broker.Support +{ + public class GreenhouseInfo : IBrokerResponse + { + public int Id { get; set; } + public int PercentWater { get; set; } + public int SoilTemperature { get; set; } + public bool PumpStatus { get; set; } + public bool HeatingStatus { get; set; } + public bool AutoWateringStatus { get; set; } + } +} \ No newline at end of file diff --git a/Cloud/Services/Broker/Support/IBrokerResponse.cs b/Cloud/Services/Broker/Support/IBrokerResponse.cs new file mode 100644 index 0000000..e13b65f --- /dev/null +++ b/Cloud/Services/Broker/Support/IBrokerResponse.cs @@ -0,0 +1,6 @@ +namespace Cloud.Services.Broker.Support +{ + public interface IBrokerResponse + { + } +} \ No newline at end of file diff --git a/Cloud/Services/Cache/IRedisCacheService.cs b/Cloud/Services/Cache/IRedisCacheService.cs new file mode 100644 index 0000000..a5b11f6 --- /dev/null +++ b/Cloud/Services/Cache/IRedisCacheService.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Cloud.Services.Cache +{ + public interface IRedisCacheService + { + Task SetCacheAsync(string key, T value, TimeSpan? expiry = null); + Task GetCacheAsync(string key); + } +} \ No newline at end of file diff --git a/Cloud/Services/Cache/RedisCacheService.cs b/Cloud/Services/Cache/RedisCacheService.cs new file mode 100644 index 0000000..2fadf24 --- /dev/null +++ b/Cloud/Services/Cache/RedisCacheService.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using StackExchange.Redis; +using System.Text.Json; + +namespace Cloud.Services.Cache +{ + public class RedisCacheService : IRedisCacheService + { + private readonly IConnectionMultiplexer _connectionMultiplexer; + + public RedisCacheService(IConnectionMultiplexer connectionMultiplexer) + { + _connectionMultiplexer = connectionMultiplexer; + } + + public async Task SetCacheAsync(string key, T value, TimeSpan? expiry = null) + { + var database = _connectionMultiplexer.GetDatabase(); + var serializedValue = JsonSerializer.Serialize(value); + await database.StringSetAsync(key, serializedValue, expiry); + } + + public async Task GetCacheAsync(string key) + { + var database = _connectionMultiplexer.GetDatabase(); + var value = await database.StringGetAsync(key); + + if (value.IsNullOrEmpty) + return default; + + return JsonSerializer.Deserialize(value); + } + } +} \ No newline at end of file diff --git a/Cloud/Services/Domain/IGreenhouseService.cs b/Cloud/Services/Domain/IGreenhouseService.cs new file mode 100644 index 0000000..523af87 --- /dev/null +++ b/Cloud/Services/Domain/IGreenhouseService.cs @@ -0,0 +1,45 @@ +using Cloud.Models; +using Cloud.Services.Broker.Support; + +namespace Cloud.Services.Domain; + +public interface IGreenhouseService +{ + /// + /// Возвращает текущую информацию о конкретной теплице из брокера + /// + /// ID теплицы + /// ID фермы, то есть брокера + /// Текущие данные о теплице от менеджера теплицы + public Task GetGreenhouseInfo(int id, int farmId); + /// + /// Возвращает сохраненные данные для автоматизации теплицы из базы данных + /// + /// ID теплицы + /// Данные для автоматизации теплицы + public Task GetGreenhouse(int id); + /// + /// Возвращает список данных о всех теплицах пользователя из брокера + /// + /// ID фермы + /// Список текущих данных о теплицах + public Task?> GetAll(int farmId); + /// + /// Сохраняет данные об автоматизации теплицы в базу данных + /// + /// Данные автоматизации теплицы + /// Созданную сущность из базы данных + public Task Create(Greenhouse greenhouse); + /// + /// Обновляет данные автоматизации теплицы в базе данных + /// + /// Новая информация об автоматизации теплицы + /// Обновленную сущность из базы данных + public Task Update(Greenhouse greenhouse); + /// + /// Удаляет данные об автоматизации теплицы из базы данных + /// + /// ID данных автоматизации теплицы + /// Возвращает удаленную сущность + public Task Delete(int id); +} \ No newline at end of file diff --git a/Cloud/Services/Domain/Implement/GreenhouseService.cs b/Cloud/Services/Domain/Implement/GreenhouseService.cs new file mode 100644 index 0000000..f398a39 --- /dev/null +++ b/Cloud/Services/Domain/Implement/GreenhouseService.cs @@ -0,0 +1,67 @@ +using Cloud.Models; +using Cloud.Services.Broker; +using Cloud.Services.Broker.Support; +using Microsoft.EntityFrameworkCore; + +namespace Cloud.Services.Domain.Implement; + +public class GreenhouseService : IGreenhouseService +{ + private readonly IBrokerService _brokerService; + private readonly ApplicationContext _context; + + public GreenhouseService(IBrokerService brokerService, ApplicationContext context) + { + _context = context; + _brokerService = brokerService; + } + + public async Task Create(Greenhouse greenhouse) + { + var res = await _context.Greenhouses.AddAsync(greenhouse); + await _context.SaveChangesAsync(); + return res.Entity; + } + + public async Task Delete(int id) + { + var greenhouse = await _context.Greenhouses.FirstOrDefaultAsync(x => x.Id == id); + + _context.Greenhouses.Remove(greenhouse); + await _context.SaveChangesAsync(); + return greenhouse; + } + + + public async Task GetGreenhouse(int id) + { + return await _context.Greenhouses.FirstOrDefaultAsync(x => x.Id == id); + } + + public async Task Update(Greenhouse greenhouse) + { + var res = _context.Greenhouses.Update(greenhouse); + await _context.SaveChangesAsync(); + return res.Entity; + } + + public async Task?> GetAll(int farmId) + { + // await _changeBrokerIp(farmId); + return _brokerService.WaitMessages("data"); + } + + public async Task GetGreenhouseInfo(int id, int farmId) + { + // await _changeBrokerIp(farmId); + var infos = _brokerService.WaitMessages("data"); + return infos?.FirstOrDefault(x => x.Id == id); + } + + private async Task _changeBrokerIp(int farmId) + { + var farm = await _context.Farms.FirstOrDefaultAsync(x => x.Id == farmId); + _brokerService.ChangeBrokerIp(farm.RaspberryIP); + + } +} diff --git a/Cloud/Support/NetworkSupport.cs b/Cloud/Support/NetworkSupport.cs new file mode 100644 index 0000000..752d9a6 --- /dev/null +++ b/Cloud/Support/NetworkSupport.cs @@ -0,0 +1,26 @@ +namespace Cloud.Support; + +public static class NetworkSupport +{ + public static async Task CheckConnectionAsync(string address) + { + using var client = new HttpClient(); + try + { + var response = await client.GetAsync(address); + + if (response.IsSuccessStatusCode) + { + Console.WriteLine($"Соединение успешно проверено. Статус-код: {response.StatusCode}"); + } + else + { + Console.WriteLine($"Соединение не удалось проверить. Статус-код: {response.StatusCode}. URL: {address}"); + } + } + catch (HttpRequestException ex) + { + Console.WriteLine($"Ошибка при проверке соединения: {ex.Message}. URL: {address}"); + } + } +} \ No newline at end of file diff --git a/Cloud/Validation/FarmValidator.cs b/Cloud/Validation/FarmValidator.cs new file mode 100644 index 0000000..c4df29e --- /dev/null +++ b/Cloud/Validation/FarmValidator.cs @@ -0,0 +1,18 @@ +using Cloud.Requests; +using FluentValidation; + +namespace Cloud.Validation +{ + public class FarmValidator : AbstractValidator + { + public FarmValidator() + { + RuleFor(request => request.RaspberryIP) + .NotEmpty().WithMessage("IP address can't be empty") + .Matches(@"^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$").WithMessage("IP address is not valid"); + + RuleFor(request => request.Name) + .NotEmpty().WithMessage("Name can't be empty"); + } + } +} \ No newline at end of file diff --git a/Cloud/Validation/LoginValidator.cs b/Cloud/Validation/LoginValidator.cs new file mode 100644 index 0000000..19f6ec0 --- /dev/null +++ b/Cloud/Validation/LoginValidator.cs @@ -0,0 +1,18 @@ +using Cloud.Requests; +using FluentValidation; + +namespace Cloud.Validation; + +public class LoginValidator : AbstractValidator +{ + public LoginValidator() + { + RuleFor(request => request.Email) + .NotEmpty().WithMessage("Email обязателен для заполнения") + .EmailAddress().WithMessage("Некорректный формат Email"); + + RuleFor(request => request.Password) + .NotEmpty().WithMessage("Пароль обязателен для заполнения") + .MinimumLength(8).WithMessage("Пароль должен быть не менее 8 символов"); + } +} diff --git a/Cloud/Validation/RegisterValidator.cs b/Cloud/Validation/RegisterValidator.cs new file mode 100644 index 0000000..1cfcb8d --- /dev/null +++ b/Cloud/Validation/RegisterValidator.cs @@ -0,0 +1,22 @@ +using Cloud.Requests; +using FluentValidation; + +namespace Cloud.Validation; + +public class RegisterValidator : AbstractValidator +{ + public RegisterValidator() + { + RuleFor(user => user.Name) + .NotEmpty().WithMessage("Имя обязательно для заполнения") + .MaximumLength(50).WithMessage("Имя должно быть не более 50 символов"); + + RuleFor(user => user.Email) + .NotEmpty().WithMessage("Email обязателен для заполнения") + .EmailAddress().WithMessage("Некорректный формат Email"); + + RuleFor(user => user.Password) + .NotEmpty().WithMessage("Пароль обязателен для заполнения") + .MinimumLength(8).WithMessage("Пароль должен быть не менее 8 символов"); + } +} \ No newline at end of file diff --git a/Cloud/Validation/ValveValidator.cs b/Cloud/Validation/ValveValidator.cs new file mode 100644 index 0000000..4a19f58 --- /dev/null +++ b/Cloud/Validation/ValveValidator.cs @@ -0,0 +1,16 @@ +using Cloud.Enums; +using Cloud.Requests; +using FluentValidation; + +namespace Cloud.Validation +{ + public class ValveValidator : AbstractValidator + { + public ValveValidator() { + + RuleFor(request => request.Action) + .NotEmpty().WithMessage("Action can't be empty"). + IsEnumName(typeof (ValveEnum)).WithMessage("Action is not correct"); + } + } +} diff --git a/Cloud/appsettings.Development.json b/Cloud/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Cloud/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Cloud/appsettings.json b/Cloud/appsettings.json new file mode 100644 index 0000000..e80f5b5 --- /dev/null +++ b/Cloud/appsettings.json @@ -0,0 +1,17 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "Kafka": { + "BootstrapServers": "localhost:9092", + "GroupId": "ValvesHeaters" + }, + "AllowedHosts": "*", + "Jwt": { + "Key": "m7TyhE20s0dVtUDAr9EnFdPZnAG8maxgBTaiW5j6kO6RQhWDAGxYmXyu0suDnE0o", + "Issuer": "localhost" + } +} \ No newline at end of file diff --git a/GreenhouseController/ManageController.py b/GreenhouseController/ManageController.py new file mode 100644 index 0000000..2d9ad10 --- /dev/null +++ b/GreenhouseController/ManageController.py @@ -0,0 +1,48 @@ +from json import dumps + + + +from json import dumps + +class ManageController: + def __init__(self, producer, topic='commands'): + self.valve_state = "closed" + self.heater_state = "off" + self.producer = producer + self.topic = topic + + def toggle_device(self, device, request_id, greenhouse_id): + + + if device == 'valve': + + if self.valve_state == 'closed': + self.valve_state = 'open' + print("Valve opened") + else: + self.valve_state = 'closed' + print("Valve closed") + + elif device == 'heater': + + if self.heater_state == 'off': + self.heater_state = 'on' + print("Heater turned on") + else: + self.heater_state = 'off' + print("Heater turned off") + + + self.send_status(request_id, greenhouse_id) + + def send_status(self, request_id, greenhouse_id): + + status = { + 'request_id': request_id, + 'greenhouse_id': greenhouse_id, + 'valve_state': self.valve_state, + 'heater_state': self.heater_state + } + + print(f"Sent device status: {status}") + return status \ No newline at end of file diff --git a/GreenhouseDetector/Dockerfile b/GreenhouseDetector/Dockerfile new file mode 100644 index 0000000..7be5c76 --- /dev/null +++ b/GreenhouseDetector/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.9-slim + +WORKDIR /app + +COPY requirements.txt . + +RUN pip install --no-cache-dir -r requirements.txt + +COPY GreenhouseDetector/detector.py . + +CMD ["python", "detector.py"] \ No newline at end of file diff --git a/GreenhouseDetector/detector.py b/GreenhouseDetector/detector.py new file mode 100644 index 0000000..4921dfe --- /dev/null +++ b/GreenhouseDetector/detector.py @@ -0,0 +1,43 @@ +import os +import time +import random as rnd + +from flask import Flask +import requests +import threading + + +app = Flask(__name__) + +class Detector: + def __init__(self, id, moistureThresholdUpper, moistureThresholdLower, tempThresholdUpper, tempThresholdLower): + self.MANAGER_URL = os.environ.get('MANAGER_URL') + print("MANAGER_URL=", self.MANAGER_URL) + self.id = id + self.moistureThresholdUpper = moistureThresholdUpper + self.moistureThresholdLower = moistureThresholdLower + self.tempThresholdUpper = tempThresholdUpper + self.tempThresholdLower = tempThresholdLower + self.moisture = 0 + self.temp = 0 + + def cycle(self): + self.moisture += rnd.random() / 100 + self.temp += (rnd.random() - 0.5) / 100 + + def sendData(self): + data = {"moisture": self.moisture, + "temp": self.temp} + requests.post(f"{self.MANAGER_URL}/webhook?id={self.id}", json=data) + +detector1 = Detector(1, 0.6, 0.2, 40, 20) + +detectors = [detector1] + +if __name__ =="__main__": + while True: + for detector in detectors: + detector.cycle() + detector.sendData() + time.sleep(1) + diff --git a/GreenhouseManager/Dockerfile b/GreenhouseManager/Dockerfile new file mode 100644 index 0000000..ab31b66 --- /dev/null +++ b/GreenhouseManager/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.9-slim + +WORKDIR /app + +COPY requirements.txt . + +RUN pip install --no-cache-dir -r requirements.txt + +COPY GreenhouseManager/manager.py . + +CMD ["python", "manager.py"] \ No newline at end of file diff --git a/GreenhouseManager/manager.py b/GreenhouseManager/manager.py new file mode 100644 index 0000000..8366baf --- /dev/null +++ b/GreenhouseManager/manager.py @@ -0,0 +1,140 @@ +import os +from kafka import KafkaProducer, KafkaConsumer +import kafka +import socket +from json import dumps, loads +from flask import Flask, request +import time +from enum import Enum +import threading + + +app = Flask(__name__) + +def start_manager(): + return + +class Manager: + def __init__(self, _id: int, moisture: float = 0, temp: float = 20, isAutoOn: bool = False, valve_state: str = "closed", + heater_state: str = "off"): + KAFKA_URL = os.environ.get('KAFKA_URL') + print("KAFKA_URL=", KAFKA_URL) + self._id = _id + self.moisture = moisture + self.temp = temp + self.isAutoOn = isAutoOn + self.valve_state = valve_state + self.heater_state = heater_state + + self.dataPublisher = KafkaProducer( + bootstrap_servers=[KAFKA_URL], + client_id=f'manager{self._id}_producer', + value_serializer=lambda v: dumps(v).encode('utf-8') + ) + + self.controllerConsumer = KafkaConsumer( + 'commands', + bootstrap_servers=[KAFKA_URL], + auto_offset_reset='earliest', + enable_auto_commit=True, + consumer_timeout_ms=2000, + group_id=f'manager{self._id}', + value_deserializer=lambda x: loads(x.decode('utf-8')) + ) + self.controllerConsumerResponse = KafkaProducer( + bootstrap_servers=[KAFKA_URL], + client_id=f'manager{self._id}_producer', + value_serializer=lambda v: dumps(v).encode('utf-8') + ) + + def sendData(self): + print("sending data...") + message = { + 'id': self._id, + 'moisture': self.moisture, + 'temp': self.temp, + 'valveStatus': str(self.valve_state), + 'heaterStatus': str(self.heater_state), + 'isAutoOn': self.isAutoOn + } + + print(message) + self.dataPublisher.send('data', message) + self.dataPublisher.flush() + + + def toggle_device(self, device, request_id, greenhouse_id): + + if device == 'valve': + + if self.valve_state == 'closed': + self.valve_state = 'open' + print("Valve opened") + else: + self.valve_state = 'closed' + print("Valve closed") + + elif device == 'heater': + + if self.heater_state == 'off': + self.heater_state = 'on' + print("Heater turned on") + else: + self.heater_state = 'off' + print("Heater turned off") + + self.send_status(request_id, greenhouse_id) + + def send_status(self, request_id, greenhouse_id): + + status = { + 'request_id': request_id, + 'greenhouse_id': greenhouse_id, + 'valve_state': self.valve_state, + 'heater_state': self.heater_state + } + self.sendDataCommand(status) + print("Updating info...\n") + + def sendDataCommand(self, message): + print("sending data...") + + self.dataPublisher.send('response', message) + + def getCommand(self): + messages = self.controllerConsumer.poll(timeout_ms=1000) + + # Проверяем, есть ли сообщения + + for tp, msgs in messages.items(): + for message in msgs: + print(f"Manager {self._id} received message: ") + print(message.value) + self.request_id = message.value['request_id'] + self.greenhouse_id = message.value['greenhouse_id'] + self.command = message.value['command'] + self.toggle_device(self.command, self.request_id, self.greenhouse_id) + +@app.route(f'/webhook', methods=['POST']) +def webhook(): + print("received webhook", request.args.get('id')) + for manager in managers: + print() + if int(request.args.get('id')) == manager._id and request.method == 'POST': + print("Data received from Webhook is", request.json) + + body = request.json + for key, value in body.items(): + setattr(manager, key, value) + + manager.sendData() + + return f"Webhook received for manager {manager._id}" + return "Webhook ignored" + +t1 = threading.Thread(target=start_manager) +manager1 = Manager(_id=1) +managers = [manager1] + +if __name__ == "__main__": + threading.Thread(target=lambda: app.run(host="0.0.0.0", port=20002, debug=True, use_reloader=False)).start() \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..5587923 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,143 @@ +networks: + vpn: + name: kafkaVPN + driver: bridge + ipam: + config: + - subnet: "192.168.2.0/24" + gateway: "192.168.2.1" + +services: + cloud: + networks: + - vpn + build: ./Cloud/ + ports: + - "5124:5124" + environment: + ASPNETCORE_ENVIRONMENT: Development + DB_CONNECTION_STRING: ${DB_CONNECTION_STRING} + REDDIS_URL: redis:6379 + KAFKA_URL: kafka:29092 + # Добавить, когда будет фронт! + # FRONT_URL: front:3000 + depends_on: + - postgres + - redis + postgres: + image: postgres:14 + container_name: cucumber_database + environment: + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + POSTGRES_DB: ${POSTGRES_DB} + ports: + - "5438:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + redis: + image: 'redis:latest' + ports: + - '6379:6379' + volumes: + - 'cloud-redis:/data' + healthcheck: + test: + - CMD + - redis-cli + - ping + retries: 3 + timeout: 5s + zookeeper: + networks: + - vpn + image: confluentinc/cp-zookeeper:7.4.0 + environment: + ZOOKEEPER_CLIENT_PORT: 2181 + ZOOKEEPER_TICK_TIME: 2000 + ports: + - 2181:2181 + kafka: + networks: + vpn: + ipv4_address: 192.168.2.10 + image: confluentinc/cp-kafka:7.4.0 + ports: + - 9092:9092 + - 9997:9997 + expose: + - 29092:29092 + environment: + KAFKA_BROKER_ID: 1 + KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 + KAFKA_LISTENERS: HOST://0.0.0.0:9092,DOCKER://0.0.0.0:29092 + KAFKA_ADVERTISED_LISTENERS: HOST://192.168.1.5:9092,DOCKER://kafka:29092 + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: DOCKER:PLAINTEXT,HOST:PLAINTEXT + KAFKA_INTER_BROKER_LISTENER_NAME: DOCKER + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 + KAFKA_LOG_FLUSH_INTERVAL_MESSAGES: 10000 + KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 + depends_on: + - zookeeper + init-kafka: + networks: + - vpn + image: confluentinc/cp-kafka:7.4.0 + depends_on: + - kafka + entrypoint: [ '/bin/sh', '-c' ] + command: | + " + # blocks until kafka is reachable + kafka-topics --bootstrap-server kafka:29092 --list + + echo -e 'Creating kafka topics' + kafka-topics --bootstrap-server kafka:29092 --create --if-not-exists --topic commands --replication-factor 1 --partitions 1 + kafka-topics --bootstrap-server kafka:29092 --create --if-not-exists --topic data --replication-factor 1 --partitions 1 + kafka-topics --bootstrap-server kafka:29092 --create --if-not-exists --topic response --replication-factor 1 --partitions 1 + + echo -e 'Successfully created the following topics:' + kafka-topics --bootstrap-server kafka:29092 --list + " + kafka-ui: + networks: + - vpn + container_name: kafka-ui + image: provectuslabs/kafka-ui:latest + ports: + - 8080:8080 + depends_on: + - kafka + environment: + KAFKA_CLUSTERS_0_NAME: local + KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:29092 + KAFKA_CLUSTERS_0_METRICS_PORT: 9997 + manager: + networks: + - vpn + build: + context: . + dockerfile: ./GreenhouseManager/Dockerfile + environment: + KAFKA_URL: kafka:29092 + depends_on: + - kafka + expose: + - 20002 + detector: + networks: + - vpn + build: + context: . + dockerfile: ./GreenhouseDetector/Dockerfile + environment: + MANAGER_URL: http://manager:20002 + depends_on: + - manager + +volumes: + postgres_data: + driver: local + cloud-redis: + driver: local diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0145355 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +kafka-python~=2.0.2 +Flask~=3.0.3 +requests~=2.31.0 \ No newline at end of file