Major rewrite
This commit is contained in:
3
.gitignore
vendored
3
.gitignore
vendored
@@ -2,3 +2,6 @@
|
||||
/house-plant-api/bin
|
||||
/house-plant-api/obj
|
||||
/house-plant-api/.vs
|
||||
/SoilMoistureAPI/.vs
|
||||
/SoilMoistureAPI/bin
|
||||
/SoilMoistureAPI/obj
|
||||
|
||||
115
SoilMoistureAPI/Controllers/DeviceController.cs
Normal file
115
SoilMoistureAPI/Controllers/DeviceController.cs
Normal file
@@ -0,0 +1,115 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SoilMoistureAPI.Data;
|
||||
using SoilMoistureAPI.Models;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SoilMoistureAPI.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class DeviceController : ControllerBase
|
||||
{
|
||||
private readonly SoilMoistureContext _context;
|
||||
|
||||
public DeviceController(SoilMoistureContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// POST: api/Device
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<Device>> CreateDevice(Device device)
|
||||
{
|
||||
if (device == null || string.IsNullOrEmpty(device.DeviceId))
|
||||
{
|
||||
return BadRequest("Invalid device data.");
|
||||
}
|
||||
|
||||
// Check if device already exists
|
||||
var existingDevice = await _context.Devices.FindAsync(device.DeviceId);
|
||||
if (existingDevice != null)
|
||||
{
|
||||
return Conflict("Device with the same DeviceId already exists.");
|
||||
}
|
||||
|
||||
_context.Devices.Add(device);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return CreatedAtAction(nameof(GetDevice), new { id = device.DeviceId }, device);
|
||||
}
|
||||
|
||||
// GET: api/Device/{id}
|
||||
[HttpGet("{id}")]
|
||||
public async Task<ActionResult<Device>> GetDevice(string id)
|
||||
{
|
||||
var device = await _context.Devices
|
||||
.Include(d => d.SoilMoistures)
|
||||
.FirstOrDefaultAsync(d => d.DeviceId == id);
|
||||
|
||||
if (device == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
return device;
|
||||
}
|
||||
|
||||
// PUT: api/Device/{id}/nickname
|
||||
[HttpPut("{id}/nickname")]
|
||||
public async Task<IActionResult> UpdateNickname(string id, [FromBody] string newNickname)
|
||||
{
|
||||
if (string.IsNullOrEmpty(newNickname))
|
||||
{
|
||||
return BadRequest("Nickname cannot be empty.");
|
||||
}
|
||||
|
||||
var device = await _context.Devices.FindAsync(id);
|
||||
if (device == null)
|
||||
{
|
||||
return NotFound("Device not found.");
|
||||
}
|
||||
|
||||
device.Nickname = newNickname;
|
||||
_context.Entry(device).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
return NoContent(); // 204 No Content
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!DeviceExists(id))
|
||||
{
|
||||
return NotFound("Device not found.");
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE: api/Device/{id}
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteDevice(string id)
|
||||
{
|
||||
var device = await _context.Devices.FindAsync(id);
|
||||
if (device == null)
|
||||
{
|
||||
return NotFound("Device not found.");
|
||||
}
|
||||
|
||||
_context.Devices.Remove(device);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return NoContent(); // 204 No Content
|
||||
}
|
||||
|
||||
private bool DeviceExists(string id)
|
||||
{
|
||||
return _context.Devices.Any(e => e.DeviceId == id);
|
||||
}
|
||||
}
|
||||
}
|
||||
96
SoilMoistureAPI/Controllers/SoilMoistureController.cs
Normal file
96
SoilMoistureAPI/Controllers/SoilMoistureController.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SoilMoistureAPI.Data;
|
||||
using SoilMoistureAPI.Models;
|
||||
|
||||
namespace SoilMoistureAPI.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class SoilMoistureController : ControllerBase
|
||||
{
|
||||
private readonly SoilMoistureContext _context;
|
||||
|
||||
public SoilMoistureController(SoilMoistureContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// POST: api/SoilMoisture
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostSoilMoisture([FromBody] SoilMoistureDto data)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
return BadRequest("No data received.");
|
||||
}
|
||||
|
||||
// Basic validation: ensure required fields are provided.
|
||||
if (string.IsNullOrEmpty(data.DeviceId))
|
||||
{
|
||||
ModelState.AddModelError("DeviceId", "The DeviceId field is required.");
|
||||
}
|
||||
// You might also want to validate moisture level here.
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
// Check if a record for this device already exists
|
||||
var existingRecord = await _context.SoilMoistures
|
||||
.Include(sm => sm.Device)
|
||||
.FirstOrDefaultAsync(sm => sm.DeviceId == data.DeviceId);
|
||||
|
||||
if (existingRecord != null)
|
||||
{
|
||||
// Update the existing record
|
||||
existingRecord.MoistureLevel = data.MoistureLevel;
|
||||
existingRecord.Timestamp = DateTime.UtcNow;
|
||||
|
||||
_context.SoilMoistures.Update(existingRecord);
|
||||
await _context.SaveChangesAsync();
|
||||
return Ok(existingRecord);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create a new record
|
||||
var newRecord = new SoilMoisture
|
||||
{
|
||||
DeviceId = data.DeviceId,
|
||||
MoistureLevel = data.MoistureLevel,
|
||||
Timestamp = DateTime.UtcNow,
|
||||
Device = new Device
|
||||
{
|
||||
DeviceId = data.DeviceId,
|
||||
Nickname = "Dave"
|
||||
}
|
||||
};
|
||||
|
||||
_context.SoilMoistures.Add(newRecord);
|
||||
await _context.SaveChangesAsync();
|
||||
return Ok(newRecord);
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/SoilMoisture/5
|
||||
[HttpGet("{id}")]
|
||||
public async Task<ActionResult<SoilMoisture>> GetSoilMoisture(int id)
|
||||
{
|
||||
var soilMoisture = await _context.SoilMoistures.FindAsync(id);
|
||||
|
||||
if (soilMoisture == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
return soilMoisture;
|
||||
}
|
||||
|
||||
// GET: api/SoilMoisture
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<IEnumerable<SoilMoisture>>> GetSoilMoistures()
|
||||
{
|
||||
return await _context.SoilMoistures.ToListAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
29
SoilMoistureAPI/Data/SoilMoistureContext.cs
Normal file
29
SoilMoistureAPI/Data/SoilMoistureContext.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SoilMoistureAPI.Models;
|
||||
|
||||
namespace SoilMoistureAPI.Data
|
||||
{
|
||||
public class SoilMoistureContext : DbContext
|
||||
{
|
||||
public SoilMoistureContext(DbContextOptions<SoilMoistureContext> options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public DbSet<SoilMoisture> SoilMoistures { get; set; }
|
||||
public DbSet<Device> Devices { get; set; } // New DbSet for Devices
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
// Configure the primary key for Device
|
||||
modelBuilder.Entity<Device>()
|
||||
.HasKey(d => d.DeviceId);
|
||||
|
||||
// Configure one-to-many relationship
|
||||
modelBuilder.Entity<Device>()
|
||||
.HasMany(d => d.SoilMoistures)
|
||||
.WithOne(s => s.Device)
|
||||
.HasForeignKey(s => s.DeviceId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
}
|
||||
34
SoilMoistureAPI/Dockerfile
Normal file
34
SoilMoistureAPI/Dockerfile
Normal file
@@ -0,0 +1,34 @@
|
||||
# Use the official .NET SDK image for building the application
|
||||
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Copy the csproj file and restore dependencies
|
||||
COPY ["SoilMoistureAPI.csproj", "./"]
|
||||
RUN dotnet restore "SoilMoistureAPI.csproj"
|
||||
|
||||
# Copy the remaining source code and build the project
|
||||
COPY . .
|
||||
RUN dotnet build "SoilMoistureAPI.csproj" -c Release -o /app/build
|
||||
|
||||
# Publish the application to the /app/publish directory
|
||||
FROM build AS publish
|
||||
RUN dotnet publish "SoilMoistureAPI.csproj" -c Release -o /app/publish
|
||||
|
||||
# Use the official ASP.NET Core runtime image for running the application
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
|
||||
#RUN groupadd --gid "1000" "plantpal" && useradd --uid "1000" --gid "1000" -m "plantpal"
|
||||
#RUN chown plantpal:1000 /app
|
||||
#USER plantpal
|
||||
|
||||
# Expose port 80 (HTTP) and 443 (HTTPS) if needed
|
||||
EXPOSE 80
|
||||
#EXPOSE 443
|
||||
|
||||
# Set environment variables
|
||||
ENV ASPNETCORE_URLS=http://+:80
|
||||
|
||||
# Set the entry point to run the application
|
||||
ENTRYPOINT ["dotnet", "SoilMoistureAPI.dll"]
|
||||
44
SoilMoistureAPI/Middleware/ApiKeyMiddleware.cs
Normal file
44
SoilMoistureAPI/Middleware/ApiKeyMiddleware.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System.Linq; // Ensure this namespace is included
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SoilMoistureAPI.Middleware
|
||||
{
|
||||
public class ApiKeyMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private const string APIKEYNAME = "X-API-KEY";
|
||||
private readonly string[] _validApiKeys;
|
||||
|
||||
public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
|
||||
{
|
||||
_next = next;
|
||||
_validApiKeys = configuration.GetSection("ApiSettings:ValidApiKeys").Get<string[]>();
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey))
|
||||
{
|
||||
context.Response.StatusCode = 401; // Unauthorized
|
||||
await context.Response.WriteAsync("API Key was not provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert StringValues to string using FirstOrDefault()
|
||||
var apiKey = extractedApiKey.FirstOrDefault();
|
||||
|
||||
if (string.IsNullOrEmpty(apiKey) || !_validApiKeys.Contains(apiKey))
|
||||
{
|
||||
context.Response.StatusCode = 403; // Forbidden
|
||||
await context.Response.WriteAsync("Unauthorized client.");
|
||||
return;
|
||||
}
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
79
SoilMoistureAPI/Migrations/20250109170429_InitialCreate.Designer.cs
generated
Normal file
79
SoilMoistureAPI/Migrations/20250109170429_InitialCreate.Designer.cs
generated
Normal file
@@ -0,0 +1,79 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SoilMoistureAPI.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SoilMoistureAPI.Migrations
|
||||
{
|
||||
[DbContext(typeof(SoilMoistureContext))]
|
||||
[Migration("20250109170429_InitialCreate")]
|
||||
partial class InitialCreate
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
|
||||
|
||||
modelBuilder.Entity("SoilMoistureAPI.Models.Device", b =>
|
||||
{
|
||||
b.Property<string>("DeviceId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Nickname")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("DeviceId");
|
||||
|
||||
b.ToTable("Devices");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SoilMoistureAPI.Models.SoilMoisture", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("DeviceId")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<float>("MoistureLevel")
|
||||
.HasColumnType("REAL");
|
||||
|
||||
b.Property<DateTime>("Timestamp")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DeviceId");
|
||||
|
||||
b.ToTable("SoilMoistures");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SoilMoistureAPI.Models.SoilMoisture", b =>
|
||||
{
|
||||
b.HasOne("SoilMoistureAPI.Models.Device", "Device")
|
||||
.WithMany("SoilMoistures")
|
||||
.HasForeignKey("DeviceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Device");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SoilMoistureAPI.Models.Device", b =>
|
||||
{
|
||||
b.Navigation("SoilMoistures");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
63
SoilMoistureAPI/Migrations/20250109170429_InitialCreate.cs
Normal file
63
SoilMoistureAPI/Migrations/20250109170429_InitialCreate.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SoilMoistureAPI.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Devices",
|
||||
columns: table => new
|
||||
{
|
||||
DeviceId = table.Column<string>(type: "TEXT", nullable: false),
|
||||
Nickname = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Devices", x => x.DeviceId);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "SoilMoistures",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "INTEGER", nullable: false)
|
||||
.Annotation("Sqlite:Autoincrement", true),
|
||||
DeviceId = table.Column<string>(type: "TEXT", nullable: false),
|
||||
MoistureLevel = table.Column<float>(type: "REAL", nullable: false),
|
||||
Timestamp = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_SoilMoistures", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_SoilMoistures_Devices_DeviceId",
|
||||
column: x => x.DeviceId,
|
||||
principalTable: "Devices",
|
||||
principalColumn: "DeviceId",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_SoilMoistures_DeviceId",
|
||||
table: "SoilMoistures",
|
||||
column: "DeviceId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "SoilMoistures");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Devices");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SoilMoistureAPI.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SoilMoistureAPI.Migrations
|
||||
{
|
||||
[DbContext(typeof(SoilMoistureContext))]
|
||||
partial class SoilMoistureContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
|
||||
|
||||
modelBuilder.Entity("SoilMoistureAPI.Models.Device", b =>
|
||||
{
|
||||
b.Property<string>("DeviceId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Nickname")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("DeviceId");
|
||||
|
||||
b.ToTable("Devices");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SoilMoistureAPI.Models.SoilMoisture", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("DeviceId")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<float>("MoistureLevel")
|
||||
.HasColumnType("REAL");
|
||||
|
||||
b.Property<DateTime>("Timestamp")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DeviceId");
|
||||
|
||||
b.ToTable("SoilMoistures");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SoilMoistureAPI.Models.SoilMoisture", b =>
|
||||
{
|
||||
b.HasOne("SoilMoistureAPI.Models.Device", "Device")
|
||||
.WithMany("SoilMoistures")
|
||||
.HasForeignKey("DeviceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Device");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SoilMoistureAPI.Models.Device", b =>
|
||||
{
|
||||
b.Navigation("SoilMoistures");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
18
SoilMoistureAPI/Models/Device.cs
Normal file
18
SoilMoistureAPI/Models/Device.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SoilMoistureAPI.Models
|
||||
{
|
||||
public class Device
|
||||
{
|
||||
[Key]
|
||||
public string DeviceId { get; set; } // Primary Key
|
||||
|
||||
[Required]
|
||||
[MaxLength(100)]
|
||||
public string Nickname { get; set; }
|
||||
|
||||
// Navigation Property
|
||||
public ICollection<SoilMoisture> SoilMoistures { get; set; }
|
||||
}
|
||||
}
|
||||
8
SoilMoistureAPI/Models/DeviceDto.cs
Normal file
8
SoilMoistureAPI/Models/DeviceDto.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace SoilMoistureAPI.Models
|
||||
{
|
||||
public class DeviceDto
|
||||
{
|
||||
public string DeviceId { get; set; }
|
||||
public string Nickname { get; set; }
|
||||
}
|
||||
}
|
||||
24
SoilMoistureAPI/Models/SoilMoisture.cs
Normal file
24
SoilMoistureAPI/Models/SoilMoisture.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace SoilMoistureAPI.Models
|
||||
{
|
||||
public class SoilMoisture
|
||||
{
|
||||
[Key]
|
||||
public int Id { get; set; }
|
||||
|
||||
[Required]
|
||||
[ForeignKey("Device")]
|
||||
public string DeviceId { get; set; } // Foreign Key
|
||||
|
||||
[Required]
|
||||
public float MoistureLevel { get; set; }
|
||||
|
||||
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
|
||||
|
||||
// Navigation Property
|
||||
public Device Device { get; set; }
|
||||
}
|
||||
}
|
||||
8
SoilMoistureAPI/Models/SoilMoistureDto.cs
Normal file
8
SoilMoistureAPI/Models/SoilMoistureDto.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace SoilMoistureAPI.Models
|
||||
{
|
||||
public class SoilMoistureDto
|
||||
{
|
||||
public string DeviceId { get; set; }
|
||||
public float MoistureLevel { get; set; }
|
||||
}
|
||||
}
|
||||
70
SoilMoistureAPI/Program.cs
Normal file
70
SoilMoistureAPI/Program.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SoilMoistureAPI.Data;
|
||||
//using SoilMoistureAPI.Middleware;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.WebHost.ConfigureKestrel(options =>
|
||||
{
|
||||
options.ListenAnyIP(80); // Listen on port 80 for HTTP
|
||||
// Optionally, listen on port 443 for HTTPS
|
||||
/*
|
||||
options.ListenAnyIP(443, listenOptions =>
|
||||
{
|
||||
listenOptions.UseHttps();
|
||||
});
|
||||
*/
|
||||
});
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// Configure CORS
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowClient",
|
||||
builder =>
|
||||
{
|
||||
//builder.WithOrigins("http://localhost:3000", "http://soilmoisture_client:80")
|
||||
builder.AllowAnyOrigin()
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod();
|
||||
});
|
||||
});
|
||||
|
||||
// Register the DB context with SQLite
|
||||
builder.Services.AddDbContext<SoilMoistureContext>(options =>
|
||||
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
|
||||
|
||||
// Add Swagger/OpenAPI support
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Apply migrations at startup
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<SoilMoistureContext>();
|
||||
db.Database.Migrate();
|
||||
}
|
||||
|
||||
// Use API Key Middleware
|
||||
//app.UseMiddleware<ApiKeyMiddleware>();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseCors("AllowClient");
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
23
SoilMoistureAPI/Properties/launchSettings.json
Normal file
23
SoilMoistureAPI/Properties/launchSettings.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5115",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7274;http://localhost:5115",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,23 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0-windows10.0.26100.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>house_plant_api</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="InTheHand.BluetoothLE" Version="4.0.37" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.0" />
|
||||
<PackageReference Include="RJCP.SerialPortStream" Version="3.0.1" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
|
||||
<PackageReference Include="System.IO.Ports" Version="9.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Adapters\" />
|
||||
<Folder Include="Migrations\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
9
SoilMoistureAPI/SoilMoistureAPI.csproj.user
Normal file
9
SoilMoistureAPI/SoilMoistureAPI.csproj.user
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ActiveDebugProfile>http</ActiveDebugProfile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
64
SoilMoistureAPI/SoilMoistureAPI.http
Normal file
64
SoilMoistureAPI/SoilMoistureAPI.http
Normal file
@@ -0,0 +1,64 @@
|
||||
### Base URL
|
||||
@baseUrl = http://localhost:80
|
||||
|
||||
### Common Headers
|
||||
@apiKey = Your_API_Key_1
|
||||
|
||||
### 1. Device Management
|
||||
|
||||
#### 1.1 Create a New Device
|
||||
POST {{baseUrl}}/api/Device
|
||||
Content-Type: application/json
|
||||
X-API-KEY: {{apiKey}}
|
||||
|
||||
{
|
||||
"DeviceId": "ESP32_Device_01",
|
||||
"Nickname": "Greenhouse Sensor"
|
||||
}
|
||||
|
||||
#### 1.2 Get Device Details
|
||||
GET {{baseUrl}}/api/Device/ESP32_Device_01
|
||||
X-API-KEY: {{apiKey}}
|
||||
|
||||
#### 1.3 Update Device Nickname
|
||||
PUT {{baseUrl}}/api/Device/ESP32_Device_01/nickname
|
||||
Content-Type: application/json
|
||||
X-API-KEY: {{apiKey}}
|
||||
|
||||
"Greenhouse Sensor v2"
|
||||
|
||||
#### 1.4 Delete a Device
|
||||
DELETE {{baseUrl}}/api/Device/ESP32_Device_01
|
||||
X-API-KEY: {{apiKey}}
|
||||
|
||||
### 2. Soil Moisture Data Management
|
||||
|
||||
#### 2.1 Post New Soil Moisture Data
|
||||
POST {{baseUrl}}/api/SoilMoisture
|
||||
Content-Type: application/json
|
||||
X-API-KEY: {{apiKey}}
|
||||
|
||||
{
|
||||
"DeviceId": "ESP32_Device_01",
|
||||
"MoistureLevel": 75.5
|
||||
}
|
||||
|
||||
#### 2.2 Get All Soil Moisture Readings
|
||||
GET {{baseUrl}}/api/SoilMoisture?pageNumber=1&pageSize=10
|
||||
X-API-KEY: {{apiKey}}
|
||||
|
||||
#### 2.3 Get Specific Soil Moisture Reading
|
||||
GET {{baseUrl}}/api/SoilMoisture/1
|
||||
X-API-KEY: {{apiKey}}
|
||||
|
||||
### 3. Health Check
|
||||
|
||||
#### 3.1 Get Health Status
|
||||
GET {{baseUrl}}/health
|
||||
X-API-KEY: {{apiKey}}
|
||||
|
||||
### 4. Swagger Documentation Access
|
||||
|
||||
#### 4.1 Access Swagger UI
|
||||
GET {{baseUrl}}/swagger/index.html
|
||||
X-API-KEY: {{apiKey}}
|
||||
22
SoilMoistureAPI/SoilMoistureAPI.sln
Normal file
22
SoilMoistureAPI/SoilMoistureAPI.sln
Normal file
@@ -0,0 +1,22 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.12.35527.113 d17.12
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SoilMoistureAPI", "SoilMoistureAPI.csproj", "{CE9A98F2-99B9-488A-B047-A0DB7F065769}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{CE9A98F2-99B9-488A-B047-A0DB7F065769}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{CE9A98F2-99B9-488A-B047-A0DB7F065769}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{CE9A98F2-99B9-488A-B047-A0DB7F065769}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{CE9A98F2-99B9-488A-B047-A0DB7F065769}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
32
SoilMoistureAPI/SoilMoistureAPI.xml
Normal file
32
SoilMoistureAPI/SoilMoistureAPI.xml
Normal file
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Container>
|
||||
<Beta>False</Beta>
|
||||
<Category>HomeAutomation:</Category>
|
||||
<Date>2025-01-08</Date>
|
||||
<Changes>
|
||||
[b]8.JAN.2025:[/b]Added[br]
|
||||
</Changes>
|
||||
<Support>http://forums.unraid.net</Support>
|
||||
<Name>PlanyPal API</Name>
|
||||
<Description>
|
||||
PlantPal's API[br][br]
|
||||
</Description>
|
||||
<Registry>localhost:5000/soilmoistureapi-api</Registry>
|
||||
<GitHub>https://github.com/</GitHub>
|
||||
<Repository>localhost:5000/soilmoistureapi-api</Repository>
|
||||
<BindTime>true</BindTime>
|
||||
<Privileged>false</Privileged>
|
||||
<Networking>
|
||||
<Mode>bridge</Mode>
|
||||
<Publish>
|
||||
<Port>
|
||||
<HostPort>3016</HostPort>
|
||||
<ContainerPort>80</ContainerPort>
|
||||
<Protocol>tcp</Protocol>
|
||||
</Port>
|
||||
</Publish>
|
||||
</Networking>
|
||||
<WebUI>http://[IP]:[PORT:3016]</WebUI>
|
||||
<Banner>http://i.imgur.com/zXpacAF.png</Banner>
|
||||
<Icon>http://i.imgur.com/zXpacAF.png</Icon>
|
||||
</Container>
|
||||
12
SoilMoistureAPI/appsettings.json
Normal file
12
SoilMoistureAPI/appsettings.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Data Source=app/data/SoilMoisture.db"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
35
docker-compose.yml
Normal file
35
docker-compose.yml
Normal file
@@ -0,0 +1,35 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
api:
|
||||
build:
|
||||
context: ./SoilMoistureAPI
|
||||
dockerfile: Dockerfile
|
||||
container_name: soilmoisture_api
|
||||
ports:
|
||||
- "8000:80" # Host port 8000 maps to container port 80 (HTTP)
|
||||
volumes:
|
||||
- ./SoilMoistureAPI/data:/app/data
|
||||
environment:
|
||||
- ASPNETCORE_URLS=http://+:80
|
||||
- ConnectionStrings__DefaultConnection=Data Source=/app/data/SoilMoisture.db
|
||||
networks:
|
||||
- soilmoisture_network
|
||||
restart: unless-stopped
|
||||
|
||||
client:
|
||||
build:
|
||||
context: ./plant-browser
|
||||
dockerfile: Dockerfile
|
||||
container_name: soilmoisture_client
|
||||
ports:
|
||||
- "3000:80" # Host port 3000 maps to container port 80 (NGINX)
|
||||
depends_on:
|
||||
- api
|
||||
networks:
|
||||
- soilmoisture_network
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
soilmoisture_network:
|
||||
driver: bridge
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,31 +0,0 @@
|
||||
namespace house_plant_api.Context
|
||||
{
|
||||
using house_plant_api.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
public class AppDbContext : DbContext
|
||||
{
|
||||
public DbSet<Device> Devices { get; set; }
|
||||
|
||||
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.Entity<Device>()
|
||||
.HasKey(d => d.Id);
|
||||
|
||||
modelBuilder.Entity<Device>()
|
||||
.Property(d => d.Name)
|
||||
.IsRequired();
|
||||
|
||||
modelBuilder.Entity<Device>()
|
||||
.Property(d => d.Nickname);
|
||||
|
||||
modelBuilder.Entity<Device>()
|
||||
.Property(d => d.Uuid)
|
||||
.IsRequired();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
namespace house_plant_api.Controllers
|
||||
{
|
||||
using house_plant_api.Context;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class DevicesController : ControllerBase
|
||||
{
|
||||
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
|
||||
|
||||
public DevicesController(IDbContextFactory<AppDbContext> dbContextFactory)
|
||||
{
|
||||
_dbContextFactory = dbContextFactory;
|
||||
}
|
||||
|
||||
// GET: api/devices
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetDevices()
|
||||
{
|
||||
using var dbContext = _dbContextFactory.CreateDbContext();
|
||||
var devices = await dbContext.Devices.ToListAsync();
|
||||
var result = devices.Select(d => new
|
||||
{
|
||||
d.Name,
|
||||
d.Uuid,
|
||||
d.Nickname,
|
||||
Moisture = d.Moisture.HasValue ? $"{d.Moisture}%" : "N/A",
|
||||
d.LastSeen
|
||||
});
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// GET: api/devices/{name}
|
||||
[HttpGet("{name}")]
|
||||
public async Task<IActionResult> GetDevice(string name)
|
||||
{
|
||||
using var dbContext = _dbContextFactory.CreateDbContext();
|
||||
var device = await dbContext.Devices.FirstOrDefaultAsync(d => d.Name == name);
|
||||
|
||||
if (device == null)
|
||||
return NotFound(new { Error = $"Device '{name}' not found." });
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
device.Name,
|
||||
device.Uuid,
|
||||
device.Nickname,
|
||||
Moisture = device.Moisture.HasValue ? $"{device.Moisture}%" : "N/A",
|
||||
device.LastSeen
|
||||
});
|
||||
}
|
||||
|
||||
// DELETE: api/devices/{name}
|
||||
[HttpDelete("{name}")]
|
||||
public async Task<IActionResult> DeleteDevice(string name)
|
||||
{
|
||||
using var dbContext = _dbContextFactory.CreateDbContext();
|
||||
var device = await dbContext.Devices.FirstOrDefaultAsync(d => d.Name == name);
|
||||
|
||||
if (device == null)
|
||||
return NotFound(new { Error = $"Device '{name}' not found in database." });
|
||||
|
||||
dbContext.Devices.Remove(device);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
return Ok(new { Message = $"Device '{name}' removed successfully." });
|
||||
}
|
||||
|
||||
// PUT: api/devices/{name}/nickname
|
||||
[HttpPut("{name}/nickname")]
|
||||
public async Task<IActionResult> UpdateNickname(string name, [FromBody] NicknameUpdateRequest request)
|
||||
{
|
||||
// Find the device by Name
|
||||
using var dbContext = _dbContextFactory.CreateDbContext();
|
||||
var device = await dbContext.Devices.FirstOrDefaultAsync(d => d.Name == name);
|
||||
|
||||
if (device == null)
|
||||
{
|
||||
return NotFound(new { Error = $"Device '{name}' not found." });
|
||||
}
|
||||
|
||||
// Update the Nickname
|
||||
device.Nickname = request.Nickname;
|
||||
|
||||
// Save changes
|
||||
dbContext.Devices.Update(device);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
Message = $"Nickname updated successfully for device '{name}'.",
|
||||
Nickname = device.Nickname
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// A simple DTO (Data Transfer Object) for updating the nickname
|
||||
public class NicknameUpdateRequest
|
||||
{
|
||||
public string Nickname { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
namespace house_plant_api.Models
|
||||
{
|
||||
using System;
|
||||
|
||||
public class Device
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string Nickname { get; set; }
|
||||
public string Uuid { get; set; }
|
||||
public int? Moisture { get; set; }
|
||||
public DateTime? LastSeen { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using house_plant_api.Context;
|
||||
using house_plant_api.Services;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// 1. Register EF Core with DbContextFactory
|
||||
builder.Services.AddDbContextFactory<AppDbContext>(options =>
|
||||
options.UseSqlite("Data Source=devices.db"));
|
||||
|
||||
// 2. Register the BluetoothService (can be Singleton or Transient)
|
||||
builder.Services.AddSingleton<BluetoothService>();
|
||||
|
||||
// 3. Register the hosted service
|
||||
builder.Services.AddHostedService<DevicePollingService>();
|
||||
|
||||
// 4. Add controllers
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// 1. Register CORS services
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowAll", policyBuilder =>
|
||||
{
|
||||
policyBuilder
|
||||
.AllowAnyOrigin() // Allows requests from any domain
|
||||
.AllowAnyHeader() // Allows any request headers
|
||||
.AllowAnyMethod(); // Allows any HTTP method (GET, POST, PUT, etc.)
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// 3. Use CORS with the named policy
|
||||
app.UseCors("AllowAll");
|
||||
|
||||
// Ensure DB is created or migrated
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var dbContextFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<AppDbContext>>();
|
||||
using var dbContext = dbContextFactory.CreateDbContext();
|
||||
dbContext.Database.EnsureCreated(); // or dbContext.Database.Migrate() if using migrations
|
||||
}
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:62301",
|
||||
"sslPort": 44394
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"house_plant_api": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7284;http://localhost:5284",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
namespace house_plant_api.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using house_plant_api.Models;
|
||||
using InTheHand.Bluetooth;
|
||||
|
||||
public class BluetoothService
|
||||
{
|
||||
private readonly Guid _serviceUuid = Guid.Parse("12345678-1234-1234-1234-123456789abc");
|
||||
private readonly Guid _characteristicUuid = Guid.Parse("abcd1234-5678-1234-5678-abcdef123456");
|
||||
|
||||
public async Task<IReadOnlyCollection<BluetoothDevice>> ScanDevicesAsync()
|
||||
{
|
||||
// Scan for BLE devices
|
||||
return await Bluetooth.ScanForDevicesAsync();
|
||||
}
|
||||
|
||||
public async Task<int> GetSoilMoistureAsync(string deviceName)
|
||||
{
|
||||
// 1. Scan for devices and match by name
|
||||
var devices = await Bluetooth.ScanForDevicesAsync();
|
||||
var targetDevice = devices.FirstOrDefault(d => d.Name == deviceName);
|
||||
|
||||
if (targetDevice == null)
|
||||
throw new Exception($"Device '{deviceName}' not found.");
|
||||
|
||||
// 2. Connect and read moisture
|
||||
await targetDevice.Gatt.ConnectAsync();
|
||||
try
|
||||
{
|
||||
var services = await targetDevice.Gatt.GetPrimaryServicesAsync();
|
||||
var targetService = services.FirstOrDefault(s => s.Uuid == _serviceUuid);
|
||||
if (targetService == null)
|
||||
throw new Exception("Moisture service not found.");
|
||||
|
||||
var characteristics = await targetService.GetCharacteristicsAsync();
|
||||
var targetCharacteristic = characteristics.FirstOrDefault(c => c.Uuid == _characteristicUuid);
|
||||
if (targetCharacteristic == null)
|
||||
throw new Exception("Moisture characteristic not found.");
|
||||
|
||||
var value = await targetCharacteristic.ReadValueAsync();
|
||||
return BitConverter.ToInt32(value, 0);
|
||||
}
|
||||
finally
|
||||
{
|
||||
targetDevice.Gatt.Disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
namespace house_plant_api.Services
|
||||
{
|
||||
using house_plant_api.Context;
|
||||
using house_plant_api.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public class CachedBluetoothService
|
||||
{
|
||||
private readonly BluetoothService _bluetoothService;
|
||||
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
|
||||
|
||||
public CachedBluetoothService(
|
||||
BluetoothService bluetoothService,
|
||||
IDbContextFactory<AppDbContext> dbContextFactory)
|
||||
{
|
||||
_bluetoothService = bluetoothService;
|
||||
_dbContextFactory = dbContextFactory;
|
||||
}
|
||||
|
||||
public List<Device> GetTrackedDevices()
|
||||
{
|
||||
// If you're using an IDbContextFactory:
|
||||
using var dbContext = _dbContextFactory.CreateDbContext();
|
||||
// Or if you're injecting a scoped dbContext (see note below):
|
||||
// var dbContext = _dbContext;
|
||||
|
||||
return dbContext.Devices.ToList();
|
||||
}
|
||||
|
||||
public async Task<List<Device>> GetTrackedDevicesAsync()
|
||||
{
|
||||
using var dbContext = _dbContextFactory.CreateDbContext();
|
||||
return await dbContext.Devices.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task PollDevicesAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var devices = await _bluetoothService.ScanDevicesAsync();
|
||||
|
||||
// Create a fresh AppDbContext instance
|
||||
using var dbContext = _dbContextFactory.CreateDbContext();
|
||||
|
||||
foreach (var device in devices)
|
||||
{
|
||||
var existingDevice = dbContext.Devices
|
||||
.FirstOrDefault(d => d.Uuid == device.Id.ToString());
|
||||
|
||||
if (existingDevice == null)
|
||||
{
|
||||
dbContext.Devices.Add(new Device
|
||||
{
|
||||
Name = device.Name,
|
||||
Nickname = "Pakkun Flower",
|
||||
Uuid = device.Id.ToString(),
|
||||
LastSeen = DateTime.Now
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
existingDevice.LastSeen = DateTime.Now;
|
||||
|
||||
try
|
||||
{
|
||||
var moisture = await _bluetoothService.GetSoilMoistureAsync(device.Name);
|
||||
existingDevice.Moisture = moisture;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Swallow exceptions from reading moisture
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Error during polling: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteDeviceAsync(string name)
|
||||
{
|
||||
using var dbContext = _dbContextFactory.CreateDbContext();
|
||||
var device = dbContext.Devices.FirstOrDefault(d => d.Name == name);
|
||||
|
||||
if (device == null)
|
||||
return false;
|
||||
|
||||
dbContext.Devices.Remove(device);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
namespace house_plant_api.Services
|
||||
{
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using InTheHand.Bluetooth;
|
||||
using house_plant_api.Context;
|
||||
using house_plant_api.Models;
|
||||
|
||||
public class DevicePollingService : BackgroundService
|
||||
{
|
||||
private readonly ILogger<DevicePollingService> _logger;
|
||||
private readonly BluetoothService _bluetoothService;
|
||||
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
|
||||
private readonly TimeSpan _pollingInterval = TimeSpan.FromSeconds(10);
|
||||
|
||||
public DevicePollingService(
|
||||
ILogger<DevicePollingService> logger,
|
||||
BluetoothService bluetoothService,
|
||||
IDbContextFactory<AppDbContext> dbContextFactory)
|
||||
{
|
||||
_logger = logger;
|
||||
_bluetoothService = bluetoothService;
|
||||
_dbContextFactory = dbContextFactory;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await PollDevicesAsync();
|
||||
await Task.Delay(_pollingInterval, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PollDevicesAsync()
|
||||
{
|
||||
_logger.LogInformation("Polling devices for moisture data...");
|
||||
|
||||
try
|
||||
{
|
||||
// 1. Scan for BLE devices
|
||||
var devices = await _bluetoothService.ScanDevicesAsync();
|
||||
|
||||
// 2. Open a new DB context for each polling run
|
||||
using var dbContext = _dbContextFactory.CreateDbContext();
|
||||
|
||||
// 3. Filter devices that have "SoilSensor" in the name (if desired)
|
||||
var soilDevices = devices
|
||||
.Where(d => !string.IsNullOrEmpty(d.Name) && d.Name.Contains("SoilSensor", StringComparison.OrdinalIgnoreCase))
|
||||
.ToList();
|
||||
|
||||
// 4. For each device, attempt to get moisture data and store/update in DB
|
||||
foreach (var device in soilDevices)
|
||||
{
|
||||
var existingDevice = dbContext.Devices
|
||||
.FirstOrDefault(d => d.Uuid == device.Id.ToString());
|
||||
|
||||
if (existingDevice == null)
|
||||
{
|
||||
// Add new device to DB
|
||||
existingDevice = new Device
|
||||
{
|
||||
Name = device.Name,
|
||||
Nickname = "Pakkun Flower",
|
||||
Uuid = device.Id.ToString(),
|
||||
LastSeen = DateTime.Now
|
||||
};
|
||||
dbContext.Devices.Add(existingDevice);
|
||||
}
|
||||
else
|
||||
{
|
||||
existingDevice.LastSeen = DateTime.Now;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Attempt to read moisture from the device
|
||||
var moisture = await _bluetoothService.GetSoilMoistureAsync(device.Name);
|
||||
existingDevice.Moisture = moisture;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// If reading fails, log and continue
|
||||
_logger.LogWarning(ex, $"Failed to read moisture from {device.Name}");
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Save changes
|
||||
await dbContext.SaveChangesAsync();
|
||||
_logger.LogInformation("Polling cycle complete.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during device polling.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,25 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.2.32526.322
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "house-plant-api", "house-plant-api.csproj", "{B9DDD6E9-3F03-4E70-B70C-832B6AB79BF0}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{B9DDD6E9-3F03-4E70-B70C-832B6AB79BF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B9DDD6E9-3F03-4E70-B70C-832B6AB79BF0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B9DDD6E9-3F03-4E70-B70C-832B6AB79BF0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B9DDD6E9-3F03-4E70-B70C-832B6AB79BF0}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {E84FCCE2-5F7C-4F20-9663-220B767E5A2B}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -1,4 +0,0 @@
|
||||
// <autogenerated />
|
||||
using System;
|
||||
using System.Reflection;
|
||||
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
|
||||
@@ -1,23 +0,0 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:4.0.30319.42000
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
[assembly: System.Reflection.AssemblyCompanyAttribute("house-plant-api")]
|
||||
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
|
||||
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+a426dce05e7078fd640479bc6275b245e1288429")]
|
||||
[assembly: System.Reflection.AssemblyProductAttribute("house-plant-api")]
|
||||
[assembly: System.Reflection.AssemblyTitleAttribute("house-plant-api")]
|
||||
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
|
||||
|
||||
// Generated by the MSBuild WriteCodeFragment class.
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
cb53261d04034aa4f1c238bde724ae959471c3d7407c687211410d9a41ef0a2a
|
||||
@@ -1,21 +0,0 @@
|
||||
is_global = true
|
||||
build_property.TargetFramework = net6.0
|
||||
build_property.TargetPlatformMinVersion =
|
||||
build_property.UsingMicrosoftNETSdkWeb = true
|
||||
build_property.ProjectTypeGuids =
|
||||
build_property.InvariantGlobalization =
|
||||
build_property.PlatformNeutralAssembly =
|
||||
build_property.EnforceExtendedAnalyzerRules =
|
||||
build_property._SupportedPlatformList = Linux,macOS,Windows
|
||||
build_property.RootNamespace = house_plant_api
|
||||
build_property.RootNamespace = house_plant_api
|
||||
build_property.ProjectDir = C:\Users\ckoch\Documents\GitHub\houseplant\house-plant-api\
|
||||
build_property.EnableComHosting =
|
||||
build_property.EnableGeneratedComInterfaceComImportInterop =
|
||||
build_property.RazorLangVersion = 6.0
|
||||
build_property.SupportLocalizedComponentNames =
|
||||
build_property.GenerateRazorMetadataSourceChecksumAttributes =
|
||||
build_property.MSBuildProjectDirectory = C:\Users\ckoch\Documents\GitHub\houseplant\house-plant-api
|
||||
build_property._RazorSourceGeneratorDebug =
|
||||
build_property.EffectiveAnalysisLevelStyle = 6.0
|
||||
build_property.EnableCodeStyleSeverity =
|
||||
@@ -1,17 +0,0 @@
|
||||
// <auto-generated/>
|
||||
global using global::Microsoft.AspNetCore.Builder;
|
||||
global using global::Microsoft.AspNetCore.Hosting;
|
||||
global using global::Microsoft.AspNetCore.Http;
|
||||
global using global::Microsoft.AspNetCore.Routing;
|
||||
global using global::Microsoft.Extensions.Configuration;
|
||||
global using global::Microsoft.Extensions.DependencyInjection;
|
||||
global using global::Microsoft.Extensions.Hosting;
|
||||
global using global::Microsoft.Extensions.Logging;
|
||||
global using global::System;
|
||||
global using global::System.Collections.Generic;
|
||||
global using global::System.IO;
|
||||
global using global::System.Linq;
|
||||
global using global::System.Net.Http;
|
||||
global using global::System.Net.Http.Json;
|
||||
global using global::System.Threading;
|
||||
global using global::System.Threading.Tasks;
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,112 +0,0 @@
|
||||
{
|
||||
"format": 1,
|
||||
"restore": {
|
||||
"C:\\Users\\ckoch\\Documents\\GitHub\\houseplant\\house-plant-api\\house-plant-api.csproj": {}
|
||||
},
|
||||
"projects": {
|
||||
"C:\\Users\\ckoch\\Documents\\GitHub\\houseplant\\house-plant-api\\house-plant-api.csproj": {
|
||||
"version": "1.0.0",
|
||||
"restore": {
|
||||
"projectUniqueName": "C:\\Users\\ckoch\\Documents\\GitHub\\houseplant\\house-plant-api\\house-plant-api.csproj",
|
||||
"projectName": "house-plant-api",
|
||||
"projectPath": "C:\\Users\\ckoch\\Documents\\GitHub\\houseplant\\house-plant-api\\house-plant-api.csproj",
|
||||
"packagesPath": "C:\\Users\\ckoch\\.nuget\\packages\\",
|
||||
"outputPath": "C:\\Users\\ckoch\\Documents\\GitHub\\houseplant\\house-plant-api\\obj\\",
|
||||
"projectStyle": "PackageReference",
|
||||
"fallbackFolders": [
|
||||
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"
|
||||
],
|
||||
"configFilePaths": [
|
||||
"C:\\Users\\ckoch\\AppData\\Roaming\\NuGet\\NuGet.Config",
|
||||
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config",
|
||||
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
|
||||
],
|
||||
"originalTargetFrameworks": [
|
||||
"net8.0-windows10.0.26100.0"
|
||||
],
|
||||
"sources": {
|
||||
"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
|
||||
"C:\\Program Files\\dotnet\\library-packs": {},
|
||||
"https://api.nuget.org/v3/index.json": {}
|
||||
},
|
||||
"frameworks": {
|
||||
"net8.0-windows10.0.26100": {
|
||||
"targetAlias": "net8.0-windows10.0.26100.0",
|
||||
"projectReferences": {}
|
||||
}
|
||||
},
|
||||
"warningProperties": {
|
||||
"warnAsError": [
|
||||
"NU1605"
|
||||
]
|
||||
},
|
||||
"restoreAuditProperties": {
|
||||
"enableAudit": "true",
|
||||
"auditLevel": "low",
|
||||
"auditMode": "direct"
|
||||
},
|
||||
"SdkAnalysisLevel": "9.0.100"
|
||||
},
|
||||
"frameworks": {
|
||||
"net8.0-windows10.0.26100": {
|
||||
"targetAlias": "net8.0-windows10.0.26100.0",
|
||||
"dependencies": {
|
||||
"InTheHand.BluetoothLE": {
|
||||
"target": "Package",
|
||||
"version": "[4.0.37, )"
|
||||
},
|
||||
"Microsoft.EntityFrameworkCore": {
|
||||
"target": "Package",
|
||||
"version": "[9.0.0, )"
|
||||
},
|
||||
"Microsoft.EntityFrameworkCore.Sqlite": {
|
||||
"target": "Package",
|
||||
"version": "[9.0.0, )"
|
||||
},
|
||||
"RJCP.SerialPortStream": {
|
||||
"target": "Package",
|
||||
"version": "[3.0.1, )"
|
||||
},
|
||||
"Swashbuckle.AspNetCore": {
|
||||
"target": "Package",
|
||||
"version": "[7.2.0, )"
|
||||
},
|
||||
"System.IO.Ports": {
|
||||
"target": "Package",
|
||||
"version": "[9.0.0, )"
|
||||
}
|
||||
},
|
||||
"imports": [
|
||||
"net461",
|
||||
"net462",
|
||||
"net47",
|
||||
"net471",
|
||||
"net472",
|
||||
"net48",
|
||||
"net481"
|
||||
],
|
||||
"assetTargetFallback": true,
|
||||
"warn": true,
|
||||
"downloadDependencies": [
|
||||
{
|
||||
"name": "Microsoft.Windows.SDK.NET.Ref",
|
||||
"version": "[10.0.26100.54, 10.0.26100.54]"
|
||||
}
|
||||
],
|
||||
"frameworkReferences": {
|
||||
"Microsoft.AspNetCore.App": {
|
||||
"privateAssets": "none"
|
||||
},
|
||||
"Microsoft.NETCore.App": {
|
||||
"privateAssets": "all"
|
||||
},
|
||||
"Microsoft.Windows.SDK.NET.Ref.Windows": {
|
||||
"privateAssets": "all"
|
||||
}
|
||||
},
|
||||
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\9.0.101/PortableRuntimeIdentifierGraph.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
|
||||
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
|
||||
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
|
||||
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">$(UserProfile)\.nuget\packages\</NuGetPackageRoot>
|
||||
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">C:\Users\ckoch\.nuget\packages\;C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages</NuGetPackageFolders>
|
||||
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
|
||||
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.12.2</NuGetToolVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<SourceRoot Include="C:\Users\ckoch\.nuget\packages\" />
|
||||
<SourceRoot Include="C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages\" />
|
||||
</ItemGroup>
|
||||
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.extensions.apidescription.server\6.0.5\build\Microsoft.Extensions.ApiDescription.Server.props" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.apidescription.server\6.0.5\build\Microsoft.Extensions.ApiDescription.Server.props')" />
|
||||
<Import Project="$(NuGetPackageRoot)swashbuckle.aspnetcore\7.2.0\build\Swashbuckle.AspNetCore.props" Condition="Exists('$(NuGetPackageRoot)swashbuckle.aspnetcore\7.2.0\build\Swashbuckle.AspNetCore.props')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.entityframeworkcore\9.0.0\buildTransitive\net8.0\Microsoft.EntityFrameworkCore.props" Condition="Exists('$(NuGetPackageRoot)microsoft.entityframeworkcore\9.0.0\buildTransitive\net8.0\Microsoft.EntityFrameworkCore.props')" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<PkgMicrosoft_Extensions_ApiDescription_Server Condition=" '$(PkgMicrosoft_Extensions_ApiDescription_Server)' == '' ">C:\Users\ckoch\.nuget\packages\microsoft.extensions.apidescription.server\6.0.5</PkgMicrosoft_Extensions_ApiDescription_Server>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<Import Project="$(NuGetPackageRoot)system.text.json\9.0.0\buildTransitive\net8.0\System.Text.Json.targets" Condition="Exists('$(NuGetPackageRoot)system.text.json\9.0.0\buildTransitive\net8.0\System.Text.Json.targets')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.extensions.apidescription.server\6.0.5\build\Microsoft.Extensions.ApiDescription.Server.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.apidescription.server\6.0.5\build\Microsoft.Extensions.ApiDescription.Server.targets')" />
|
||||
<Import Project="$(NuGetPackageRoot)sqlitepclraw.lib.e_sqlite3\2.1.10\buildTransitive\net8.0\SQLitePCLRaw.lib.e_sqlite3.targets" Condition="Exists('$(NuGetPackageRoot)sqlitepclraw.lib.e_sqlite3\2.1.10\buildTransitive\net8.0\SQLitePCLRaw.lib.e_sqlite3.targets')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.extensions.logging.abstractions\9.0.0\buildTransitive\net8.0\Microsoft.Extensions.Logging.Abstractions.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.logging.abstractions\9.0.0\buildTransitive\net8.0\Microsoft.Extensions.Logging.Abstractions.targets')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.extensions.options\9.0.0\buildTransitive\net8.0\Microsoft.Extensions.Options.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.options\9.0.0\buildTransitive\net8.0\Microsoft.Extensions.Options.targets')" />
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,67 +0,0 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dgSpecHash": "puDPynTpJjc=",
|
||||
"success": true,
|
||||
"projectFilePath": "C:\\Users\\ckoch\\Documents\\GitHub\\houseplant\\house-plant-api\\house-plant-api.csproj",
|
||||
"expectedPackageFiles": [
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\inthehand.bluetoothle\\4.0.37\\inthehand.bluetoothle.4.0.37.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.data.sqlite.core\\9.0.0\\microsoft.data.sqlite.core.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.entityframeworkcore\\9.0.0\\microsoft.entityframeworkcore.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.entityframeworkcore.abstractions\\9.0.0\\microsoft.entityframeworkcore.abstractions.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.entityframeworkcore.analyzers\\9.0.0\\microsoft.entityframeworkcore.analyzers.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.entityframeworkcore.relational\\9.0.0\\microsoft.entityframeworkcore.relational.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.entityframeworkcore.sqlite\\9.0.0\\microsoft.entityframeworkcore.sqlite.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.entityframeworkcore.sqlite.core\\9.0.0\\microsoft.entityframeworkcore.sqlite.core.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.apidescription.server\\6.0.5\\microsoft.extensions.apidescription.server.6.0.5.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.caching.abstractions\\9.0.0\\microsoft.extensions.caching.abstractions.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.caching.memory\\9.0.0\\microsoft.extensions.caching.memory.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.configuration.abstractions\\9.0.0\\microsoft.extensions.configuration.abstractions.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.dependencyinjection\\9.0.0\\microsoft.extensions.dependencyinjection.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.dependencyinjection.abstractions\\9.0.0\\microsoft.extensions.dependencyinjection.abstractions.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.dependencymodel\\9.0.0\\microsoft.extensions.dependencymodel.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.logging\\9.0.0\\microsoft.extensions.logging.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.logging.abstractions\\9.0.0\\microsoft.extensions.logging.abstractions.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.options\\9.0.0\\microsoft.extensions.options.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.extensions.primitives\\9.0.0\\microsoft.extensions.primitives.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.openapi\\1.6.22\\microsoft.openapi.1.6.22.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\rjcp.core.environment\\0.3.0\\rjcp.core.environment.0.3.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\rjcp.core.syscompat\\0.2.0\\rjcp.core.syscompat.0.2.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\rjcp.diagnostics.trace\\0.2.1\\rjcp.diagnostics.trace.0.2.1.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\rjcp.io.buffer\\0.2.1\\rjcp.io.buffer.0.2.1.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\rjcp.io.device\\0.8.1\\rjcp.io.device.0.8.1.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\rjcp.serialportstream\\3.0.1\\rjcp.serialportstream.3.0.1.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.android-arm.runtime.native.system.io.ports\\9.0.0\\runtime.android-arm.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.android-arm64.runtime.native.system.io.ports\\9.0.0\\runtime.android-arm64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.android-x64.runtime.native.system.io.ports\\9.0.0\\runtime.android-x64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.android-x86.runtime.native.system.io.ports\\9.0.0\\runtime.android-x86.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.linux-arm.runtime.native.system.io.ports\\9.0.0\\runtime.linux-arm.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.linux-arm64.runtime.native.system.io.ports\\9.0.0\\runtime.linux-arm64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.linux-bionic-arm64.runtime.native.system.io.ports\\9.0.0\\runtime.linux-bionic-arm64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.linux-bionic-x64.runtime.native.system.io.ports\\9.0.0\\runtime.linux-bionic-x64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.linux-musl-arm.runtime.native.system.io.ports\\9.0.0\\runtime.linux-musl-arm.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.linux-musl-arm64.runtime.native.system.io.ports\\9.0.0\\runtime.linux-musl-arm64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.linux-musl-x64.runtime.native.system.io.ports\\9.0.0\\runtime.linux-musl-x64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.linux-x64.runtime.native.system.io.ports\\9.0.0\\runtime.linux-x64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.maccatalyst-arm64.runtime.native.system.io.ports\\9.0.0\\runtime.maccatalyst-arm64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.maccatalyst-x64.runtime.native.system.io.ports\\9.0.0\\runtime.maccatalyst-x64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.native.system.io.ports\\9.0.0\\runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.osx-arm64.runtime.native.system.io.ports\\9.0.0\\runtime.osx-arm64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\runtime.osx-x64.runtime.native.system.io.ports\\9.0.0\\runtime.osx-x64.runtime.native.system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\sqlitepclraw.bundle_e_sqlite3\\2.1.10\\sqlitepclraw.bundle_e_sqlite3.2.1.10.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\sqlitepclraw.core\\2.1.10\\sqlitepclraw.core.2.1.10.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\sqlitepclraw.lib.e_sqlite3\\2.1.10\\sqlitepclraw.lib.e_sqlite3.2.1.10.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\sqlitepclraw.provider.e_sqlite3\\2.1.10\\sqlitepclraw.provider.e_sqlite3.2.1.10.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\swashbuckle.aspnetcore\\7.2.0\\swashbuckle.aspnetcore.7.2.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\swashbuckle.aspnetcore.swagger\\7.2.0\\swashbuckle.aspnetcore.swagger.7.2.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\swashbuckle.aspnetcore.swaggergen\\7.2.0\\swashbuckle.aspnetcore.swaggergen.7.2.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\swashbuckle.aspnetcore.swaggerui\\7.2.0\\swashbuckle.aspnetcore.swaggerui.7.2.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\system.diagnostics.diagnosticsource\\9.0.0\\system.diagnostics.diagnosticsource.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\system.io.pipelines\\9.0.0\\system.io.pipelines.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\system.io.ports\\9.0.0\\system.io.ports.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\system.memory\\4.5.3\\system.memory.4.5.3.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\system.text.encodings.web\\9.0.0\\system.text.encodings.web.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\system.text.json\\9.0.0\\system.text.json.9.0.0.nupkg.sha512",
|
||||
"C:\\Users\\ckoch\\.nuget\\packages\\microsoft.windows.sdk.net.ref\\10.0.26100.54\\microsoft.windows.sdk.net.ref.10.0.26100.54.nupkg.sha512"
|
||||
],
|
||||
"logs": []
|
||||
}
|
||||
4
plant-browser/.vscode/extensions.json
vendored
4
plant-browser/.vscode/extensions.json
vendored
@@ -1,4 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
|
||||
"recommendations": ["angular.ng-template"]
|
||||
}
|
||||
20
plant-browser/.vscode/launch.json
vendored
20
plant-browser/.vscode/launch.json
vendored
@@ -1,20 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "ng serve",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "npm: start",
|
||||
"url": "http://localhost:4200/"
|
||||
},
|
||||
{
|
||||
"name": "ng test",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "npm: test",
|
||||
"url": "http://localhost:9876/debug.html"
|
||||
}
|
||||
]
|
||||
}
|
||||
42
plant-browser/.vscode/tasks.json
vendored
42
plant-browser/.vscode/tasks.json
vendored
@@ -1,42 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "start",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"owner": "typescript",
|
||||
"pattern": "$tsc",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": {
|
||||
"regexp": "(.*?)"
|
||||
},
|
||||
"endsPattern": {
|
||||
"regexp": "bundle generation complete"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "test",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"owner": "typescript",
|
||||
"pattern": "$tsc",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": {
|
||||
"regexp": "(.*?)"
|
||||
},
|
||||
"endsPattern": {
|
||||
"regexp": "bundle generation complete"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
25
plant-browser/Dockerfile
Normal file
25
plant-browser/Dockerfile
Normal file
@@ -0,0 +1,25 @@
|
||||
# Stage 1: Build the Angular application
|
||||
FROM node:18-alpine AS build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
|
||||
COPY . .
|
||||
RUN npm run build --prod
|
||||
|
||||
# Stage 2: Serve the Angular app using NGINX
|
||||
FROM nginx:stable-alpine AS runtime
|
||||
|
||||
COPY --from=build /app/dist/plant-browser/browser /usr/share/nginx/html
|
||||
|
||||
# Remove the default NGINX configuration
|
||||
RUN rm /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Copy custom NGINX configuration
|
||||
COPY nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -40,6 +40,12 @@
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/environments/environment.ts",
|
||||
"with": "src/environments/environment.prod.ts"
|
||||
}
|
||||
],
|
||||
"budgets": [
|
||||
{
|
||||
"type": "initial",
|
||||
|
||||
45
plant-browser/nginx.conf
Normal file
45
plant-browser/nginx.conf
Normal file
@@ -0,0 +1,45 @@
|
||||
# soilmoisture_client/nginx.conf
|
||||
|
||||
worker_processes 1;
|
||||
|
||||
events { worker_connections 1024; }
|
||||
|
||||
http {
|
||||
include mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
sendfile on;
|
||||
keepalive_timeout 65;
|
||||
|
||||
# Docker's internal DNS resolver
|
||||
resolver 127.0.0.11 valid=10s;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html index.htm;
|
||||
|
||||
# Serve Angular App with Client-Side Routing
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# Proxy API Requests to ASP.NET Core API
|
||||
location /api/ {
|
||||
proxy_pass http://soilmoisture_api:80/api/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
|
||||
# Optional: Increase timeout settings if necessary
|
||||
proxy_connect_timeout 600;
|
||||
proxy_send_timeout 600;
|
||||
proxy_read_timeout 600;
|
||||
send_timeout 600;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,23 +2,24 @@ import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { SoilData } from '../models/soil-data.model';
|
||||
import { environment } from '../../environments/environment';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class SoilDataService {
|
||||
private apiUrl = 'http://localhost:5284/api/'; // Replace with your actual API endpoint
|
||||
private baseUrl = environment.apiUrl;
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
constructor(private http: HttpClient) { }
|
||||
|
||||
getPlants(): Observable<SoilData[]> {
|
||||
return this.http.get<SoilData[]>(this.apiUrl + 'devices');
|
||||
return this.http.get<SoilData[]>(`${this.baseUrl}/SoilMoisture`);
|
||||
}
|
||||
|
||||
// Update device nickname
|
||||
updateNickname(name: string, nickname: string): Observable<any> {
|
||||
const url = `${this.apiUrl}devices/${encodeURIComponent(name)}/nickname`;
|
||||
return this.http.put(url, { nickname: nickname });
|
||||
}
|
||||
// Update device nickname
|
||||
updateNickname(name: string, nickname: string): Observable<any> {
|
||||
const url = `${this.baseUrl}/Device/${encodeURIComponent(name)}/nickname`;
|
||||
return this.http.put(url, { nickname: nickname });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
4
plant-browser/src/environments/environment.prod.ts
Normal file
4
plant-browser/src/environments/environment.prod.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export const environment = {
|
||||
production: true,
|
||||
apiUrl: '/api' // Relative path for production (handled by NGINX proxy)
|
||||
};
|
||||
4
plant-browser/src/environments/environment.ts
Normal file
4
plant-browser/src/environments/environment.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export const environment = {
|
||||
production: false,
|
||||
apiUrl: 'http://localhost:8000/api' // For development
|
||||
};
|
||||
Reference in New Issue
Block a user