Major rewrite
This commit is contained in:
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
SoilMoistureAPI/Data/SoilMoisture.db
Normal file
BIN
SoilMoistureAPI/Data/SoilMoisture.db
Normal file
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
23
SoilMoistureAPI/SoilMoistureAPI.csproj
Normal file
23
SoilMoistureAPI/SoilMoistureAPI.csproj
Normal file
@@ -0,0 +1,23 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<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="Swashbuckle.AspNetCore" Version="7.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<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>
|
||||
8
SoilMoistureAPI/appsettings.Development.json
Normal file
8
SoilMoistureAPI/appsettings.Development.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
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": "*"
|
||||
}
|
||||
Reference in New Issue
Block a user