Compare commits

...

38 Commits

Author SHA1 Message Date
c42d2e3c16
Fix logout 2025-04-01 09:05:05 +02:00
LilleBRG
c9155d582b no errors after merge. update database please 2025-03-31 15:49:35 +02:00
LilleBRG
db023ac84e Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-31 14:49:34 +02:00
Jeas0001
1ca64702d7 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-31 11:16:29 +02:00
Jeas0001
6cb36947cb Made the datetime optional 2025-03-31 11:16:16 +02:00
fb3705690d
Don't send undefined content type in frontend 2025-03-31 11:03:38 +02:00
e2dd9d9e6e
Fix cookie path 2025-03-31 11:00:20 +02:00
Jeas0001
668b29c068 Undid last commit from me 2025-03-31 10:50:21 +02:00
Jeas0001
d9205d425c Datetime ranged have any logs 2025-03-31 10:48:20 +02:00
fe85e1ff23
Add JS constants to gitignore 2025-03-31 10:42:23 +02:00
Jeas0001
7a3d5b4f71 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-31 10:39:35 +02:00
Jeas0001
9dc19efd83 Removed unnessesary usings and added a datetimerange for getting logs 2025-03-31 10:39:07 +02:00
6fe0841cbc
Add error handling on dashboard 2025-03-31 10:31:57 +02:00
df130b312c
Style dashboard 2025-03-31 10:20:26 +02:00
dd2a3cf150
Show real temperature data in frontend 2025-03-31 09:30:08 +02:00
Jeas0001
f6e2c8f450 Gets userId from the jwttoken 2025-03-31 09:19:50 +02:00
LilleBRG
8202885870 devices half made 2025-03-27 22:17:45 +01:00
b8bb86edca
Fix JWT bearer authentication 2025-03-27 10:47:31 +01:00
Jeas0001
595ade2d79 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-27 10:37:25 +01:00
02bfbabcfc
Set auth token when logging in 2025-03-27 10:33:40 +01:00
0f1b10d2d7
Change how requests are sent in order to send auth token 2025-03-27 10:33:40 +01:00
Jeas0001
8ad863b781 Added securityDefinition and requirements 2025-03-27 10:22:46 +01:00
Jeas0001
46de83dc42 RefreshToken is made 2025-03-27 10:17:25 +01:00
Jeas0001
edc195b234 Fixed AMQPPublish and split the code into more functions and added Refresh token to Usermodel 2025-03-27 09:48:08 +01:00
Jeas0001
bce48fe8d1 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-26 14:28:30 +01:00
Jeas0001
998cb90acc Changed the name of the publisher 2025-03-26 14:28:20 +01:00
Jeas0001
47797d18a0 Made AMQPPush for pushing the device limits to RabbitMQ and consume after 1 hour 2025-03-26 13:14:12 +01:00
Jeas0001
6f311fabd4 Comments 2025-03-26 12:14:42 +01:00
2f5f753ab6
Implement printing temperature on display 2025-03-26 09:59:25 +01:00
LilleBRG
8f6f332292 device table header 2025-03-25 16:20:08 +01:00
LilleBRG
a3f3d8f861 changes to updateuser, added logout button 2025-03-25 16:11:14 +01:00
LilleBRG
f42dcd743a profile gets data from db, changes to edituser 2025-03-25 14:24:36 +01:00
Jeas0001
60c0fc9475 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-25 13:15:52 +01:00
Jeas0001
507e156f17 Some comment in AMQPReciever, AMQPReciever and DBAccess 2025-03-25 13:15:42 +01:00
90cbf7ae81
Fix listening for AMQP messages, remove test console app 2025-03-25 12:54:52 +01:00
8c6037b010
Implement AMQP in IoT 2025-03-25 12:30:53 +01:00
Jeas0001
fccea25296 Merge branch 'Jeppe' 2025-03-25 10:51:20 +01:00
b943ad5f97
Fix dockerfile and add exec perms to deploy script 2025-03-25 09:40:06 +01:00
64 changed files with 1700 additions and 562 deletions

View File

@ -0,0 +1,109 @@
using Api.DBAccess;
using Api.Models;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Json;
namespace Api.AMQP
{
public class AMQPPublisher
{
private readonly IConfiguration _configuration;
private readonly DbAccess _dbAccess;
private IConnection _conn;
private IChannel _channel;
private ConnectionFactory _factory;
private string _queue;
public AMQPPublisher(IConfiguration configuration, DbAccess dbAccess)
{
_dbAccess = dbAccess;
_configuration = configuration;
_factory = new ConnectionFactory();
_queue = "temperature-limits";
InitFactory();
}
public async Task Handle_Push_Device_Limits()
{
while (true)
{
await Connect();
// Publishes all devices limits
var devices = _dbAccess.ReadDevices();
foreach (var device in devices)
{
var deviceLimit = new DeviceLimit();
deviceLimit.ReferenceId = device.ReferenceId;
deviceLimit.TempHigh = device.TempHigh;
deviceLimit.TempLow = device.TempLow;
string message = JsonSerializer.Serialize(deviceLimit);
var body = Encoding.UTF8.GetBytes(message);
await _channel.BasicPublishAsync(exchange: string.Empty, routingKey: _queue, body: body);
}
// Short delay before disconnecting from rabbitMQ
await Task.Delay(1000);
// Disconnecting from rabbitMQ to save resources
await Dispose();
// 1 hour delay
await Task.Delay(3600000);
await Connect();
// Here all messages is consumed so the queue is empty
var consumer = new AsyncEventingBasicConsumer(_channel);
consumer.ReceivedAsync += (model, ea) =>
{
Console.WriteLine("Emptying queue");
return Task.CompletedTask;
};
// Consumes the data in the queue
await _channel.BasicConsumeAsync(_queue, true, consumer);
// Short delay before disconnecting from rabbitMQ
await Task.Delay(1000);
await Dispose();
}
}
// Disconnects from rabbitMQ
private async Task<bool> Dispose()
{
await _channel.CloseAsync();
await _conn.CloseAsync();
await _channel.DisposeAsync();
await _conn.DisposeAsync();
return true;
}
// Connects to rabbitMQ
private async Task<bool> Connect()
{
// Creating a new connection to rabbitMQ
_conn = await _factory.CreateConnectionAsync();
Console.WriteLine("AMQPClient connected");
_channel = await _conn.CreateChannelAsync();
// Here we connect to the queue through the channel that got created earlier
await _channel.QueueDeclareAsync(queue: _queue, durable: false, exclusive: false, autoDelete: false);
Console.WriteLine($"{_queue} connected");
return true;
}
// The info for the factory
private void InitFactory()
{
_factory.UserName = _configuration["AMQP:username"];
_factory.Password = _configuration["AMQP:password"];
_factory.HostName = _configuration["AMQP:host"];
_factory.Port = Convert.ToInt32(_configuration["AMQP:port"]);
}
}
}

View File

@ -0,0 +1,97 @@
using Api.DBAccess;
using Api.Models;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Json;
namespace Api.AMQPReciever
{
public class AMQPReciever
{
private readonly IConfiguration _configuration;
private readonly DbAccess _dbAccess;
private IConnection _conn;
private IChannel _channel;
private ConnectionFactory _factory;
private string _queue;
public AMQPReciever(IConfiguration configuration, DbAccess dbAccess)
{
_dbAccess = dbAccess;
_configuration = configuration;
_factory = new ConnectionFactory();
_queue = "temperature-logs";
InitFactory();
}
public async Task Handle_Received_Application_Message()
{
await Connect();
// Everytime a message is recieved from the queue it goes into this consumer.ReceivedAsync
var consumer = new AsyncEventingBasicConsumer(_channel);
consumer.ReceivedAsync += (model, ea) =>
{
Console.WriteLine("Received application message.");
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
var messageReceive = JsonSerializer.Deserialize<MessageReceive>(message);
// Checks if the message has the data we need
if (messageReceive == null || messageReceive.device_id == null || messageReceive.timestamp == 0)
{
return Task.CompletedTask;
}
// Convert to the model we use in the database and gets the device from the database that is used for getting the current set temphigh and templow
TemperatureLogs newLog = new TemperatureLogs();
string refernceId = messageReceive.device_id;
var device = _dbAccess.ReadDevice(refernceId);
// Checks if the device exist if it doesn't it throws the data away
if (device == null) { return Task.CompletedTask; }
newLog.Temperature = messageReceive.temperature;
newLog.Date = DateTimeOffset.FromUnixTimeSeconds(messageReceive.timestamp).DateTime;
newLog.TempHigh = device.TempHigh;
newLog.TempLow = device.TempLow;
// Send the data to dbaccess to be saved
_dbAccess.CreateLog(newLog, refernceId);
return Task.CompletedTask;
};
// Consumes the data in the queue
await _channel.BasicConsumeAsync(_queue, true, consumer);
while (true);
}
// Connects to rabbitMQ
private async Task<bool> Connect()
{
// Creating a new connection to rabbitMQ
_conn = await _factory.CreateConnectionAsync();
Console.WriteLine("AMQPClient connected");
_channel = await _conn.CreateChannelAsync();
// Here we connect to the queue through the channel that got created earlier
await _channel.QueueDeclareAsync(queue: _queue, durable: false, exclusive: false, autoDelete: false);
Console.WriteLine($"{_queue} connected");
return true;
}
// The info for the factory
private void InitFactory()
{
_factory.UserName = _configuration["AMQP:username"];
_factory.Password = _configuration["AMQP:password"];
_factory.HostName = _configuration["AMQP:host"];
_factory.Port = Convert.ToInt32(_configuration["AMQP:port"]);
}
}
}

View File

@ -1,74 +0,0 @@
using Api.DBAccess;
using Api.Models;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Json;
namespace Api.AMQPReciever
{
public class AMQPReciever
{
private readonly IConfiguration _configuration;
private readonly DbAccess _dbAccess;
public AMQPReciever(IConfiguration configuration, DbAccess dbAccess)
{
_dbAccess = dbAccess;
_configuration = configuration;
}
public async Task Handle_Received_Application_Message()
{
var factory = new ConnectionFactory();
var queue = "temperature-logs";
factory.UserName = _configuration["AMQP:username"];
factory.Password = _configuration["AMQP:password"];
factory.HostName = _configuration["AMQP:host"];
factory.Port = Convert.ToInt32(_configuration["AMQP:port"]);
using var conn = await factory.CreateConnectionAsync();
Console.WriteLine("AMQPClien connected");
using var channel = await conn.CreateChannelAsync();
await channel.QueueDeclareAsync(queue: queue, durable: false, exclusive: false, autoDelete: false);
Console.WriteLine($"{queue} connected");
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += (model, ea) =>
{
Console.WriteLine("Received application message.");
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
var messageReceive = JsonSerializer.Deserialize<MQTTMessageReceive>(message);
if (messageReceive == null || messageReceive.temperature == 0 || messageReceive.device_id == null || messageReceive.timestamp == 0)
{
return Task.CompletedTask;
}
TemperatureLogs newLog = new TemperatureLogs();
string refernceId = messageReceive.device_id;
var device = _dbAccess.ReadDevice(refernceId);
if (device == null) { return Task.CompletedTask; }
newLog.Temperature = messageReceive.temperature;
newLog.Date = DateTimeOffset.FromUnixTimeSeconds(messageReceive.timestamp).DateTime;
newLog.TempHigh = device.TempHigh;
newLog.TempLow = device.TempLow;
_dbAccess.CreateLog(newLog, refernceId);
return Task.CompletedTask;
};
await channel.BasicConsumeAsync(queue, true, consumer);
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}
}

View File

@ -1,7 +1,6 @@
using Api.DBAccess;
using Api.Models;
using Microsoft.AspNetCore.Mvc;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Api.BusinessLogic
{
@ -16,6 +15,12 @@ namespace Api.BusinessLogic
_configuration = configuration;
}
/// <summary>
/// Gets the user from dbaccess using the userId and checks if the user exists
/// Gets all devices that match the userId and checks if there are any devices connected to the user
/// </summary>
/// <param name="userId">UserId that matches a user that owns the devices</param>
/// <returns>returns the devices in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> GetDevices(int userId)
{
var profile = await _dbAccess.ReadUser(userId);
@ -29,6 +34,13 @@ namespace Api.BusinessLogic
return new OkObjectResult(devices);
}
/// <summary>
/// Checks if the user that the device is trying to be added to exists
/// Then it is send to dbaccess
/// </summary>
/// <param name="device">The new device</param>
/// <param name="userId">The user that owns the device</param>
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> AddDevice(Device device, int userId)
{
var profile = await _dbAccess.ReadUser(userId);
@ -38,7 +50,15 @@ namespace Api.BusinessLogic
return await _dbAccess.CreateDevice(device, userId);
}
public async Task<IActionResult> GetLogs(int deviceId)
/// <summary>
/// Checks if the device exist that is trying to be read from
/// Gets the logs and checks if there are any in the list
/// Checks if the datetimeRange have 2 values that are the same bc that means they want all logs
/// Then it makes a new list with all data that are in the range of the 2 datetimes
/// </summary>
/// <param name="deviceId">The deviceId that you want from the logs</param>
/// <returns>returns the logs in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> GetLogs(DateTimeRange dateTimeRange, int deviceId)
{
var device = await _dbAccess.ReadDevice(deviceId);
@ -48,9 +68,23 @@ namespace Api.BusinessLogic
if (logs.Count == 0) { return new ConflictObjectResult(new { message = "Could not find any logs connected to the device" }); }
return new OkObjectResult(logs);
if (dateTimeRange.DateTimeStart == dateTimeRange.DateTimeEnd) { return new OkObjectResult(logs); }
List<TemperatureLogs> rangedLogs = new List<TemperatureLogs>();
foreach (var log in logs)
{
if (log.Date <= dateTimeRange.DateTimeStart && log.Date >= dateTimeRange.DateTimeEnd) { rangedLogs.Add(log); }
}
return new OkObjectResult(rangedLogs);
}
/// <summary>
/// Checks if the deviceId matches a device
/// </summary>
/// <param name="device">The updated info</param>
/// <param name="deviceId">The device to be edited</param>
/// <returns>returns the updated device in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> EditDevice(Device device, int deviceId)
{
var device1 = _dbAccess.ReadDevice(deviceId);

View File

@ -1,5 +1,6 @@
using Api.DBAccess;
using Api.Models;
using Api.Models.User;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
@ -22,6 +23,22 @@ namespace Api.BusinessLogic
_configuration = configuration;
}
public async Task<IActionResult> getUser(int userId)
{
User user = await _dbAccess.getUser(userId);
if (user == null || user.Id == 0) { return new ConflictObjectResult(new { message = "Could not find user" }); }
return new OkObjectResult(new { user.Id, user.UserName, user.Email });
}
/// <summary>
/// First checks if the mail is a valid one with regex so if there is something before the @ and after and it has a domain
/// Then it checks if the password is to our security standard
/// Then it makes sure the user has a device list
/// The last thing before it saves the user is creating a salt and then hashing of the password
/// </summary>
/// <param name="user">The new user</param>
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> RegisterUser(User user)
{
if (!new Regex(@".+@.+\..+").IsMatch(user.Email))
@ -41,13 +58,20 @@ namespace Api.BusinessLogic
string salt = Guid.NewGuid().ToString();
string hashedPassword = ComputeHash(user.Password, SHA256.Create(), salt);
user.Salt = salt;
user.Password = hashedPassword;
return await _dbAccess.CreateUser(user);
}
/// <summary>
/// Gets the user that matches the login
/// Hashes the login password with the users salt
/// checks if the hashed password that the login has is the same as the one saved in the database
/// </summary>
/// <param name="login">Has a username or email and a password</param>
/// <returns>Returns a jwt token, username and userid</returns>
public async Task<IActionResult> Login(Login login)
{
User user = await _dbAccess.Login(login);
@ -59,37 +83,74 @@ namespace Api.BusinessLogic
if (user.Password == hashedPassword)
{
var token = GenerateJwtToken(user);
return new OkObjectResult(new { token, user.UserName, user.Id });
user.RefreshToken = Guid.NewGuid().ToString();
_dbAccess.UpdatesRefreshToken(user.RefreshToken, user.Id);
return new OkObjectResult(new { token, user.UserName, user.Id, refreshToken = user.RefreshToken });
}
return new ConflictObjectResult(new { message = "Invalid password" });
}
/// <summary>
/// First checks if the mail is a valid one with regex so if there is something before the @ and after and it has a domain
/// Then it checks if the password is to our security standard
/// Finds the user that matches the userId and hashes a new hash with the old salt
/// Then the updated user and the userId is being send to dbaccess
/// </summary>
/// <param name="user">Contains the updated user info</param>
/// <param name="userId">Has the id for the user that is to be updated</param>
/// <returns>returns the updated user in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> EditProfile(User user, int userId)
{
if (!new Regex(@".+@.+\..+").IsMatch(user.Email))
{
return new ConflictObjectResult(new { message = "Invalid email address" });
}
if (!PasswordSecurity(user.Password))
{
return new ConflictObjectResult(new { message = "Password is not up to the security standard" });
}
var profile = await _dbAccess.ReadUser(userId);
string hashedPassword = ComputeHash(user.Password, SHA256.Create(), profile.Salt);
user.Password = hashedPassword;
return await _dbAccess.UpdateUser(user, userId);
}
public async Task<IActionResult> changePassword(ChangePasswordRequest passwordRequest, int userId)
{
var user = await _dbAccess.ReadUser(userId);
string hashedPassword = ComputeHash(passwordRequest.OldPassword, SHA256.Create(), user.Salt);
if (user.Password != hashedPassword)
{
return new ConflictObjectResult(new { message = "Old password is incorrect" });
}
if (!PasswordSecurity(passwordRequest.NewPassword))
{
return new ConflictObjectResult(new { message = "New password is not up to the security standard" });
}
string hashedNewPassword = ComputeHash(passwordRequest.NewPassword, SHA256.Create(), user.Salt);
return await _dbAccess.updatePassword(hashedNewPassword, userId);
}
/// <summary>
/// Just sends the userid of the user that is to be deleted
/// </summary>
/// <param name="userId">The Id of the user that is to be deleted</param>
/// <returns>returns the true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> DeleteUser(int userId)
{
return await _dbAccess.DeleteUser(userId);
}
public async Task<IActionResult> RefreshToken(string refreshToken)
{
User user = await _dbAccess.ReadUser(refreshToken);
if (user == null) { return new ConflictObjectResult(new { message = "Could not match refreshtoken" }); }
return new OkObjectResult(GenerateJwtToken(user));
}
/// <summary>
/// Generates a hash from a salt and input using the algorithm that is provided
/// </summary>
/// <param name="input">This is the input that is supposed to be hashed</param>
/// <param name="algorithm">This is the alogorithm that is used to encrypt the input</param>
/// <param name="salt">This is something extra added to make the hashed input more unpredictable</param>
/// <returns>The hashed input</returns>
private static string ComputeHash(string input, HashAlgorithm algorithm, string salt)
{
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
@ -105,6 +166,11 @@ namespace Api.BusinessLogic
return BitConverter.ToString(hashedBytes);
}
/// <summary>
/// Checks if password is up to our security standard
/// </summary>
/// <param name="password">The password that is to be checked</param>
/// <returns>true or false dependeing on if the password is up to standard</returns>
public bool PasswordSecurity(string password)
{
var hasMinimum8Chars = new Regex(@".{8,}");
@ -112,6 +178,11 @@ namespace Api.BusinessLogic
return hasMinimum8Chars.IsMatch(password);
}
/// <summary>
/// Generates a JWT token that last 2 hours
/// </summary>
/// <param name="user">Used for sending the userid and username with the token</param>
/// <returns>Returns a valid JWTToken</returns>
private string GenerateJwtToken(User user)
{
var claims = new[]
@ -129,7 +200,7 @@ namespace Api.BusinessLogic
_configuration["JwtSettings:Issuer"],
_configuration["JwtSettings:Audience"],
claims,
expires: DateTime.Now.AddMinutes(30),
expires: DateTime.Now.AddHours(2),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);

View File

@ -3,6 +3,7 @@ using Api.Models;
using Api.DBAccess;
using Microsoft.AspNetCore.Authorization;
using Api.BusinessLogic;
using System.Security.Claims;
namespace Api.Controllers
{
@ -19,29 +20,48 @@ namespace Api.Controllers
_deviceLogic = deviceLogic;
}
// Sends the userId to deviceLogic
[Authorize]
[HttpGet("{userId}")]
public async Task<IActionResult> GetDevices(int userId)
[HttpGet]
public async Task<IActionResult> GetDevices()
{
List<Device> devices = await _dbAccess.ReadDevices(userId);
if (devices.Count == 0) { return BadRequest(new { error = "There is no devices that belong to this userID" }); }
var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _deviceLogic.GetDevices(userId);
}
// Sends the device and userId to deviceLogic
[Authorize]
[HttpPost("adddevice/{userId}")]
public async Task<IActionResult> AddDevice([FromBody] Device device, int userId)
[HttpPost("adddevice")]
public async Task<IActionResult> AddDevice([FromBody] Device device)
{
var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _deviceLogic.AddDevice(device, userId);
}
// Sends the deviceId to deviceLogic
[Authorize]
[HttpGet("logs/{deviceId}")]
public async Task<IActionResult> GetLogs(int deviceId)
public async Task<IActionResult> GetLogs(int deviceId, DateTime? dateTimeStart = null, DateTime? dateTimeEnd = null)
{
return await _deviceLogic.GetLogs(deviceId);
DateTimeRange dateTimeRange = new DateTimeRange();
if (dateTimeStart != null && dateTimeEnd != null)
{
dateTimeRange.DateTimeStart = (DateTime)dateTimeStart;
dateTimeRange.DateTimeEnd= (DateTime)dateTimeEnd;
}
else
{
dateTimeRange.DateTimeStart = DateTime.Now;
dateTimeRange.DateTimeEnd = dateTimeRange.DateTimeStart;
}
return await _deviceLogic.GetLogs(dateTimeRange, deviceId);
}
// Sends the deviceId to deviceLogic
[Authorize]
[HttpPut("Edit/{deviceId}")]
public async Task<IActionResult> EditDevice([FromBody] Device device, int deviceId)

View File

@ -1,12 +1,9 @@
using Microsoft.AspNetCore.Mvc;
using Api.Models;
using Api.DBAccess;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Api.BusinessLogic;
using Api.Models.User;
namespace Api.Controllers
{
@ -21,29 +18,48 @@ namespace Api.Controllers
_userLogic = userLogic;
}
//[Authorize]
[HttpGet("Get")]
public async Task<IActionResult> GetUSer()
{
var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _userLogic.getUser(userId);
}
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] Login login)
{
return await _userLogic.Login(login);
}
// Sends the user to userLogic
[HttpPost("Create")]
public async Task<IActionResult> CreateUser([FromBody] User user)
{
return await _userLogic.RegisterUser(user);
}
// Sends the user and userId to userLogic
[Authorize]
[HttpPut("Edit/{userId}")]
public async Task<IActionResult> EditUser([FromBody] User user, int userId)
[HttpPut("Edit")]
public async Task<IActionResult> EditUser([FromBody] User user)
{
var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _userLogic.EditProfile(user, userId);
}
// Sends the userId to userLogic
[Authorize]
[HttpDelete("Delete/{userId}")]
public async Task<IActionResult> DeleteUser(int userId)
[HttpDelete("Delete")]
public async Task<IActionResult> DeleteUser()
{
var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _userLogic.DeleteUser(userId);
}

View File

@ -1,10 +1,8 @@
using Microsoft.EntityFrameworkCore;
using Api.Models;
using System.Text;
using System.Runtime.Intrinsics.Arm;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Api.Models.User;
namespace Api.DBAccess
@ -18,6 +16,16 @@ namespace Api.DBAccess
_context = context;
}
public async Task<User> getUser(int userId)
{
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
}
/// <summary>
/// Creates a user using entityframework core
/// </summary>
/// <param name="user">Need the entire user obj</param>
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> CreateUser(User user)
{
var users = await _context.Users.ToListAsync();
@ -43,6 +51,11 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to databse" });
}
/// <summary>
/// Returns a user that matches either the email or username
/// </summary>
/// <param name="login">Has a username or email and a password here the password is not used</param>
/// <returns>(user) that matches the login</returns>
public async Task<User> Login(Login login)
{
User user = new User();
@ -59,11 +72,33 @@ namespace Api.DBAccess
return user;
}
// Returns a user according to userID
public async Task<User> ReadUser(int userId)
{
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
}
// Returns a user according to refreshToken
public async Task<User> ReadUser(string refreshToken)
{
return await _context.Users.FirstOrDefaultAsync(u => u.RefreshToken == refreshToken);
}
// Updates the refreshtoken saved in DB
public async void UpdatesRefreshToken(string refreshToken, int userId)
{
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
user.RefreshToken = refreshToken;
user.RefreshTokenExpiresAt = DateTime.Now.AddDays(7);
}
/// <summary>
/// Updates the user in the database
/// </summary>
/// <param name="user">Contains the updated user info</param>
/// <param name="userId">Has the id for the user that is to be updated</param>
/// <returns>returns the updated user in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> UpdateUser(User user, int userId)
{
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
@ -73,22 +108,24 @@ namespace Api.DBAccess
foreach (var item in users)
{
if (item.UserName == user.UserName)
if (item.UserName == user.UserName && userId != item.Id)
{
return new ConflictObjectResult(new { message = "Username is already in use." });
}
if (item.Email == user.Email)
if (item.Email == user.Email && userId != item.Id)
{
return new ConflictObjectResult(new { message = "Email is being used already" });
}
}
profile.UserName = user.UserName;
if(user.Email != "" && user.Email != null)
profile.Email = user.Email;
if (user.UserName != "" && user.UserName != null)
profile.UserName = user.UserName;
profile.Email = user.Email;
profile.Password = user.Password;
bool saved = await _context.SaveChangesAsync() == 1;
@ -97,6 +134,26 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to database" });
}
public async Task<IActionResult> updatePassword(string newPassword, int userId)
{
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
if (profile == null) { return new ConflictObjectResult(new { message = "User does not exist" }); }
profile.Password = newPassword;
bool saved = await _context.SaveChangesAsync() == 1;
if (saved) { return new OkObjectResult(profile); }
return new ConflictObjectResult(new { message = "Could not save to database" });
}
/// <summary>
/// Deletes a user from the database
/// </summary>
/// <param name="userId">The Id of the user that is to be deleted</param>
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> DeleteUser(int userId)
{
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
@ -120,6 +177,7 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Invalid user" });
}
// Returns devices according to userID
public async Task<List<Device>> ReadDevices(int userId)
{
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
@ -131,6 +189,12 @@ namespace Api.DBAccess
return devices;
}
/// <summary>
/// Creates a user using entityframework core
/// </summary>
/// <param name="device">The device that is going to be created</param>
/// <param name="userId">The user that owns the device</param>
/// <returns>returns the true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> CreateDevice(Device device, int userId)
{
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
@ -148,16 +212,30 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to database" });
}
// Returns a device according to deviceId
public async Task<Device> ReadDevice(int deviceId)
{
return await _context.Devices.FirstOrDefaultAsync(d => d.Id == deviceId);
}
// Returns a device according to refenreId
public Device ReadDevice(string refenreId)
{
return _context.Devices.FirstOrDefault(d => d.ReferenceId == refenreId);
}
// Returns all devices
public List<Device> ReadDevices()
{
return _context.Devices.ToList();
}
/// <summary>
/// Updates a device in the database
/// </summary>
/// <param name="device">Contains the updated device info</param>
/// <param name="deviceId">Has the id for the device that is to be updated</param>
/// <returns>returns the updated device in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> UpdateDevice(Device device, int deviceId)
{
var device1 = await _context.Devices.FirstOrDefaultAsync(u => u.Id == deviceId);
@ -179,6 +257,11 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to database" });
}
/// <summary>
/// Returns the logs from the device
/// </summary>
/// <param name="deviceId">Has the id for the device that the los belong too</param>
/// <returns></returns>
public async Task<List<TemperatureLogs>> ReadLogs(int deviceId)
{
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.Id == deviceId);
@ -190,6 +273,11 @@ namespace Api.DBAccess
return logs;
}
/// <summary>
/// Creates a new log
/// </summary>
/// <param name="temperatureLogs">the new log</param>
/// <param name="referenceId">the referenceId that belongs too the device that recoded the log</param>
public async void CreateLog(TemperatureLogs temperatureLogs, string referenceId)
{
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.ReferenceId == referenceId);
@ -202,6 +290,7 @@ namespace Api.DBAccess
await _context.SaveChangesAsync();
}
// Does a health check on the database access
public async Task<bool> Test()
{
return _context.Database.CanConnect();

View File

@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Api.Models;
using Api.Models.User;
namespace Api
{

View File

@ -22,4 +22,6 @@ RUN dotnet publish "./Api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:Use
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Api.dll"]
RUN mkdir /app/db
RUN chmod 777 /app/db
ENTRYPOINT ["dotnet", "Api.dll"]

View File

@ -26,12 +26,14 @@ namespace Api.MQTTReciever
using (mqttClient = mqttFactory.CreateMqttClient())
{
// Entering our values for conecting to MQTT
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithTcpServer($"{_configuration["MQTT:host"]}", Convert.ToInt32(_configuration["MQTT:port"]))
.WithCredentials($"{_configuration["MQTT:username"]}", $"{_configuration["MQTT:password"]}")
.WithCleanSession()
.Build();
// Everytime a message is recieved from the queue it goes into this mqttClient.ApplicationMessageReceivedAsync
// Setup message handling before connecting so that queued messages
// are also handled properly. When there is no event handler attached all
// received messages get lost.
@ -41,35 +43,38 @@ namespace Api.MQTTReciever
string sensorData = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
var mqttMessageReceive = JsonSerializer.Deserialize<MQTTMessageReceive>(sensorData);
var messageReceive = JsonSerializer.Deserialize<MessageReceive>(sensorData);
if (mqttMessageReceive == null || mqttMessageReceive.temperature == 0 || mqttMessageReceive.device_id == null || mqttMessageReceive.timestamp == 0)
// Checks if the message has the data we need
if (messageReceive == null || messageReceive.device_id == null || messageReceive.timestamp == 0)
{
return Task.CompletedTask;
}
// Convert to the model we use in the database and gets the device from the database that is used for getting the current set temphigh and templow
TemperatureLogs newLog = new TemperatureLogs();
string refernceId = mqttMessageReceive.device_id;
string refernceId = messageReceive.device_id;
var device = _dbAccess.ReadDevice(refernceId);
// Checks if the device exist if it doesn't it throws the data away
if (device == null) { return Task.CompletedTask; }
newLog.Temperature = mqttMessageReceive.temperature;
newLog.Date = DateTimeOffset.FromUnixTimeSeconds(mqttMessageReceive.timestamp).DateTime;
newLog.Temperature = messageReceive.temperature;
newLog.Date = DateTimeOffset.FromUnixTimeSeconds(messageReceive.timestamp).DateTime;
newLog.TempHigh = device.TempHigh;
newLog.TempLow = device.TempLow;
// Send the data to dbaccess to be saved
_dbAccess.CreateLog(newLog, refernceId);
return Task.CompletedTask;
};
// Starts the connection to rabbitmq
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
Console.WriteLine("mqttClient");
//var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder().WithTopicTemplate(topic).Build();
// Subscribes to our topic
await mqttClient.SubscribeAsync("temperature");
Console.WriteLine("MQTT client subscribed to topic.");

View File

@ -0,0 +1,138 @@
// <auto-generated />
using System;
using Api;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Api.Migrations
{
[DbContext(typeof(DBContext))]
[Migration("20250327084557_AddedRefreshTokenToUser")]
partial class AddedRefreshTokenToUser
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
modelBuilder.Entity("Api.Models.Device", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReferenceId")
.HasColumnType("TEXT");
b.Property<double>("TempHigh")
.HasColumnType("REAL");
b.Property<double>("TempLow")
.HasColumnType("REAL");
b.Property<int?>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Devices");
});
modelBuilder.Entity("Api.Models.TemperatureLogs", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("Date")
.HasColumnType("TEXT");
b.Property<int?>("DeviceId")
.HasColumnType("INTEGER");
b.Property<double>("TempHigh")
.HasColumnType("REAL");
b.Property<double>("TempLow")
.HasColumnType("REAL");
b.Property<double>("Temperature")
.HasColumnType("REAL");
b.HasKey("Id");
b.HasIndex("DeviceId");
b.ToTable("TemperatureLogs");
});
modelBuilder.Entity("Api.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("RefreshToken")
.HasColumnType("TEXT");
b.Property<DateTime>("RefreshTokenExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("Salt")
.HasColumnType("TEXT");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Api.Models.Device", b =>
{
b.HasOne("Api.Models.User", null)
.WithMany("Devices")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Api.Models.TemperatureLogs", b =>
{
b.HasOne("Api.Models.Device", null)
.WithMany("Logs")
.HasForeignKey("DeviceId");
});
modelBuilder.Entity("Api.Models.Device", b =>
{
b.Navigation("Logs");
});
modelBuilder.Entity("Api.Models.User", b =>
{
b.Navigation("Devices");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Api.Migrations
{
/// <inheritdoc />
public partial class AddedRefreshTokenToUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "RefreshToken",
table: "Users",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "RefreshTokenExpiresAt",
table: "Users",
type: "TEXT",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RefreshToken",
table: "Users");
migrationBuilder.DropColumn(
name: "RefreshTokenExpiresAt",
table: "Users");
}
}
}

View File

@ -88,6 +88,12 @@ namespace Api.Migrations
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("RefreshToken")
.HasColumnType("TEXT");
b.Property<DateTime>("RefreshTokenExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("Salt")
.HasColumnType("TEXT");

View File

@ -0,0 +1,9 @@
namespace Api.Models
{
public class DateTimeRange
{
public DateTime DateTimeStart { get; set; }
public DateTime DateTimeEnd { get; set; }
}
}

View File

@ -0,0 +1,11 @@
namespace Api.Models
{
public class DeviceLimit
{
public double TempHigh { get; set; }
public double TempLow { get; set; }
public string? ReferenceId { get; set; }
}
}

View File

@ -1,6 +1,6 @@
namespace Api.Models
{
public class MQTTMessageReceive
public class MessageReceive
{
public double temperature { get; set; }

View File

@ -0,0 +1,8 @@
namespace Api.Models.User
{
public class ChangePasswordRequest
{
public string OldPassword { get; set; }
public string NewPassword { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace Api.Models.User
{
public class EditUserRequest
{
public string UserName { get; set; }
public string Email { get; set; }
}
}

View File

@ -1,4 +1,4 @@
namespace Api.Models
namespace Api.Models.User
{
public class User
{
@ -12,6 +12,10 @@
public string? Salt { get; set; }
public string? RefreshToken { get; set; }
public DateTime RefreshTokenExpiresAt { get; set; }
public List<Device>? Devices { get; set; }
}
}

View File

@ -1,10 +1,10 @@
using Api;
using Api.AMQP;
using Api.AMQPReciever;
using Api.DBAccess;
using Api.MQTTReciever;
using Microsoft.AspNetCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
class Program
{
@ -12,7 +12,7 @@ class Program
public static void Main(string[] args)
{
var app = CreateWebHostBuilder(args).Build();
string rabbitMQ = "AMQP"; // This value has to be either "AMQP" or "MQTT"
RunMigrations(app);
@ -24,11 +24,19 @@ class Program
var configuration = services.GetRequiredService<IConfiguration>();
var dbAccess = services.GetRequiredService<DbAccess>();
//AMQPReciever amqp = new AMQPReciever(configuration, dbAccess);
//amqp.Handle_Received_Application_Message().Wait();
MQTTReciever mqtt = new MQTTReciever(configuration, dbAccess);
mqtt.Handle_Received_Application_Message().Wait();
// Choose to either connect AMQP or MQTT
if (rabbitMQ == "AMQP")
{
AMQPReciever amqpReciever = new AMQPReciever(configuration, dbAccess);
amqpReciever.Handle_Received_Application_Message().Wait();
AMQPPublisher aMQPPush = new AMQPPublisher(configuration, dbAccess);
aMQPPush.Handle_Push_Device_Limits().Wait();
}
else if (rabbitMQ == "MQTT")
{
MQTTReciever mqtt = new MQTTReciever(configuration, dbAccess);
mqtt.Handle_Received_Application_Message().Wait();
}
}
});

View File

@ -66,6 +66,29 @@ namespace Api
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// Configure Swagger to use Bearer token authentication
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme",
Type = SecuritySchemeType.Http,
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
}
@ -87,6 +110,8 @@ namespace Api
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>

View File

@ -1,14 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="7.1.2" />
</ItemGroup>
</Project>

View File

@ -1,25 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34607.119
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp1", "ConsoleApp1.csproj", "{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {55EE0E94-4585-4E79-AC67-4B0E809E99AB}
EndGlobalSection
EndGlobal

View File

@ -1,52 +0,0 @@
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
var factory = new ConnectionFactory();
var queue = "test";
factory.UserName = "h5";
factory.Password = "Merc1234";
factory.HostName = "10.135.51.116";
factory.Port = 5672;
using var conn = await factory.CreateConnectionAsync();
Console.WriteLine("AMQPClien connected");
using var channel = await conn.CreateChannelAsync();
await channel.QueueDeclareAsync(queue: queue, durable: false, exclusive: false, autoDelete: false);
Console.WriteLine($"{queue} connected");
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += (model, ea) =>
{
Console.WriteLine("Received application message.");
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(message);
return Task.CompletedTask;
};
await channel.BasicConsumeAsync(queue, true, consumer);
const string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
Console.WriteLine(" Press enter to continue.");
Console.ReadLine();
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
Console.WriteLine(" Press enter to continue.");
Console.ReadLine();
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
Console.WriteLine(" Press enter to continue.");
Console.ReadLine();
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
Console.WriteLine(" Press enter to continue.");
Console.ReadLine();
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
Console.WriteLine(" Press enter to exit.");
Console.ReadLine();

0
deploy.sh Normal file → Executable file
View File

2
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
shared/constants.js

View File

@ -0,0 +1,106 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Temperature-Alarm-Web</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<link rel="stylesheet" href="/styles/auth.css">
<link rel="stylesheet" href="/styles/devices.css" />
<script defer type="module" src="/scripts/devices.js"></script>
</head>
<body>
<div id="container">
<div class="topnav">
<a href="/home/index.html">Home</a>
<div style="display: flex; justify-content: flex-end;">
<a class="active" href="/devices">Devices</a>
<a href="/profile">Profile</a>
<span class="logout-container">
<img class="logout" src="/img/logout.png">
</span>
</div>
</div>
<div class="addDeviceContainer">
<button id="addDevice">Add Device</button>
</div>
<div class="tableConatiner">
<table>
<tr>
<th>Id</th>
<th>Placement(name)</th>
<th>Set Temp High</th>
<th>Set Temp Low</th>
<th>Latest Meassurement</th>
<th></th>
</tr>
<tbody id="deviceTable"></tbody>
</table>
</div>
</div>
<div id="deleteModal" class="modal">
<form class="modal-content">
<div class="container">
<h1 class="deviceHeader" id="deleteDeviceHeader"></h1>
<p>Are you sure you want to delete this device from your account?</p>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="button" id="deletebtn">Delete</button>
</div>
</div>
</form>
</div>
<div id="editModal" class="modal">
<div class="modal-content">
<div class="container">
<h1 class="deviceHeader" id="editDeviceHeader"></h1>
<form id="editForm">
<div class="form-container">
<label for="name"><b>Name</b></label>
<input type="text" placeholder="Enter a name for the placement" id="name" required>
<label for="tempHigh"><b>High Temperature</b></label>
<input type="text" placeholder="Edit the high temperature" id="tempHigh" required>
<label for="tempLow"><b>Low Temperature</b></label>
<input type="text" placeholder="Edit the low temperature" id="tempLow" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="button" id="editbtn">Save Changes</button>
</div>
<div id="form-error"></div>
</div>
</form>
</div>
</div>
</div>
<div id="addModal" class="modal">
<div class="modal-content">
<div class="container">
<h1 class="deviceHeader">Add Device</h1>
<form id="editForm">
<div class="form-container">
<label for="referenceId"><b>Device Id</b></label>
<input type="text" placeholder="Enter the device Id" id="referenceId" required>
<div id="form-error"></div>
</div>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="button" id="addbtn">Add</button>
</div>
<div id="form-error"></div>
</form>
</div>
</div>
</div>
</body>
</html>

View File

@ -1,36 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Temperature-Alarm-Web</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<link rel="stylesheet" href="/styles/home.css" />
<script type="module" src="/scripts/home.js"></script>
</head>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Temperature-Alarm-Web</title>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script defer type="module" src="/scripts/home.js"></script>
<link rel="stylesheet" href="/styles/common.css">
<link rel="stylesheet" href="/styles/home.css" />
<link rel="stylesheet" href="/styles/auth.css" />
</head>
<body>
<div id="container">
<div class="topnav">
<a class="active" href="/home/index.html">Home</a>
<div style="display: flex; justify-content: flex-end;">
<a class="" href="/home/index.html">Devices</a>
<a class="" href="/profile/index.html">Profile</a>
<body>
<div class="topnav">
<a class="active" href="/home/index.html">Home</a>
<div style="display: flex; justify-content: flex-end;">
<a href="/devices">Devices</a>
<a href="/profile">Profile</a>
<span class="logout-container">
<img class="logout" src="/img/logout.png">
</span>
</div>
</div>
<div id="container">
<div class="chart-container">
<canvas id="myChart" style="width: 49%; height: 49%;"></canvas>
</div>
<div id="table-wrapper">
<table>
<tr>
<th>Temperature</th>
<th>Date</th>
<th>Time</th>
<th>Limits</th>
</tr>
<tbody id="TemperatureTable"></tbody>
</table>
</div>
</div>
</div>
<div class="chartContainer">
<canvas id="myChart" style="width: 49%; height: 49%;"></canvas>
</div>
<table>
<tr>
<th>Name</th>
<th>Temperature</th>
<th>Date</th>
<th>TempHigh</th>
<th>TempLow</th>
</tr>
<tbody id="TemperatureTable"></tbody>
</table>
</div>
</body>
<div id="error" class="error"></div>
</body>
</html>

BIN
frontend/img/Edit.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
frontend/img/Trash.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
frontend/img/logout.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<title>Login - Temperature alarm</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles/common.css">
<link rel="stylesheet" href="/styles/auth.css">
<script defer type="module" src="/scripts/login.js"></script>
</head>
@ -20,15 +21,12 @@
<button type="submit">Login</button>
<div class="details">
<label>
<input type="checkbox" name="remember"> Remember me
</label>
<span>
Dont have an account? <a href="/register">Register</a>
</span>
</div>
<div id="form-error"></div>
<div id="form-error" class="error"></div>
</div>
</form>
</body>

View File

@ -0,0 +1,3 @@
export const devices = [
{referenceId: "DKOFG", name: "Kitchen", tempHigh: 23.0, tempLow: 23.0, latestLog: { id: 1, temperature: 18.9, date: "2025-03-19T17:00:00Z", tempHigh: 22.0, tempLow: 18.0 }}
]

View File

@ -1,28 +0,0 @@
export const mockTemperatureLogs = [
{ id: 1, temperature: 18.9, date: "2025-03-19T17:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 19.1, date: "2025-03-19T17:10:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 19.5, date: "2025-03-19T17:20:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 19.8, date: "2025-03-19T17:30:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.1, date: "2025-03-19T17:40:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.3, date: "2025-03-19T17:50:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.6, date: "2025-03-19T18:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.9, date: "2025-03-19T18:10:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.8, date: "2025-03-19T18:20:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.7, date: "2025-03-19T18:30:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.5, date: "2025-03-19T18:40:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.3, date: "2025-03-19T18:50:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.1, date: "2025-03-19T19:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 18.9, date: "2025-03-19T20:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 19.1, date: "2025-03-19T20:10:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 19.5, date: "2025-03-19T20:20:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 19.8, date: "2025-03-19T20:30:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.1, date: "2025-03-19T20:40:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 20.3, date: "2025-03-19T20:50:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 22.6, date: "2025-03-19T21:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 22.9, date: "2025-03-19T21:10:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 22.8, date: "2025-03-19T21:20:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 22.7, date: "2025-03-19T21:30:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 22.5, date: "2025-03-19T21:40:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 23.3, date: "2025-03-19T21:50:00Z", tempHigh: 22.0, tempLow: 18.0 },
{ id: 1, temperature: 24.1, date: "2025-03-19T22:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
]

View File

@ -10,12 +10,25 @@
</head>
<body>
<div id="container">
<div id="profileCard"></div>
<div class="btnContainer">
<button class="btn" id="openEditModal">Edit</button>
<button class="btn" id="openPasswordModal">Change Password</button>
</div>
<div class="topnav">
<a href="/home/index.html">Home</a>
<div style="display: flex; justify-content: flex-end;">
<a href="/devices">Devices</a>
<a class="active" href="/profile">Profile</a>
<span class="logout-container">
<img class="logout" src="/img/logout.png">
</span>
</div>
</div>
<div style="display: flex; justify-content: center;">
<div class="profileContainer">
<div id="profileCard"></div>
<div class="btnContainer">
<button class="btn" id="openEditModal">Edit</button>
<button class="btn" id="openPasswordModal">Change Password</button>
</div>
</div>
</div>
</div>
<div id="editModal" class="modal">
@ -25,14 +38,13 @@
<form id="editForm">
<div class="form-container">
<label for="email"><b>Email</b></label>
<input type="email" placeholder="Enter email "id="email" required>
<input type="email" placeholder="Enter email "id="email">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter username" id="uname" required>
<input type="text" placeholder="Enter username" id="uname">
<button type="submit">Save Changes</button>
<div class="error-text" id="form-error-edit"></div>
</div>
</form>
</div>
@ -55,7 +67,7 @@
<button type="submit">Change Password</button>
<div class="error-text" id="form-error-password"></div>
<div id="form-error"></div>
</div>
</form>
</div>

View File

@ -4,13 +4,14 @@
<meta charset="UTF-8" />
<title>Register - Temperature Alarm</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles/common.css">
<link rel="stylesheet" href="/styles/auth.css">
<script defer type="module" src="/scripts/register.js"></script>
</head>
<body>
<form id="registerForm">
<div class="form-container">
<h1>Create Account</h1>
<h1>Sign Up</h1>
<label for="email"><b>Email</b></label>
<input type="email" placeholder="Enter email "id="email" required>
@ -33,7 +34,7 @@
</label>
</div>
<div id="form-error"></div>
<div id="form-error" class="error"></div>
</div>
</form>
</body>

View File

@ -0,0 +1,94 @@
import { getDevices, deleteDevice, update, add } from "./services/devices.service.js";
import { devices } from "../mockdata/devices.mockdata.js";
import { logout } from "../shared/utils.js";
getDevices().then(res => {
buildTable(res)
})
buildTable(devices);
let selectedReferenceId = null; // Store the selected referenceId
function buildTable(data) {
var table = document.getElementById("deviceTable");
table.innerHTML = ""; // Clear existing rows before adding new ones
data.forEach((device) => {
var row = document.createElement("tr");
row.innerHTML = `
<td>${device.referenceId}</td>
<td>${device.name}</td>
<td>${device.tempHigh}</td>
<td>${device.tempLow}</td>
<td>Temperature: ${device.latestLog.temperature}°C, Date: ${device.latestLog.date}</td>
<td style="width: 90px;">
<img class="editIconbtn tableIcons" src="/img/Edit.png" data-referenceid="${device.referenceId}">
<img class="trashBtn tableIcons" src="/img/Trash.png" data-referenceid="${device.referenceId}">
</td>
`;
table.appendChild(row);
});
document.getElementById("addDevice").onclick = () => {
document.getElementById("addModal").style.display = "block";
}
// Attach click event to all trash buttons
document.querySelectorAll(".trashBtn").forEach((btn) => {
btn.onclick = function () {
selectedReferenceId = this.getAttribute("data-referenceid"); // Store referenceId
document.getElementById("deleteDeviceHeader").innerHTML = `Delete Device ${selectedReferenceId}`;
document.getElementById("deleteModal").style.display = "block";
};
});
// Attach click event to all trash buttons
document.querySelectorAll(".editIconbtn").forEach((btn) => {
btn.onclick = function () {
selectedReferenceId = this.getAttribute("data-referenceid"); // Store referenceId
document.getElementById("editDeviceHeader").innerHTML = `Edit Device ${selectedReferenceId}`;
document.getElementById("editModal").style.display = "block";
};
});
}
document.querySelectorAll(".cancelbtn").forEach(button => {
button.onclick = () => {
document.getElementById("deleteModal").style.display = "none";
document.getElementById("editModal").style.display = "none";
document.getElementById("addModal").style.display = "none";
};
});
// Delete button logic
document.getElementById("deletebtn").onclick = () => {
if (selectedReferenceId) {
deleteDevice(selectedReferenceId); // Call delete function with referenceId
document.getElementById("deleteModal").style.display = "none";
window.location.reload();
}
};
document.getElementById("addbtn").onclick = () => {
const referenceId = document.getElementById("referenceId").value;
add(referenceId); // Call delete function with referenceId
document.getElementById("deleteModal").style.display = "none";
window.location.reload();
};
document.getElementById("editbtn").onclick = () => {
if (selectedReferenceId) {
const name = document.getElementById("name").value;
const tempHigh = document.getElementById("tempHigh").value;
const tempLow = document.getElementById("tempLow").value;
update(selectedReferenceId, name, tempHigh, tempLow); // Call delete function with referenceId
document.getElementById("deleteModal").style.display = "none";
window.location.reload();
}
};
document.querySelector(".logout-container").addEventListener("click", logout);

View File

@ -1,84 +1,87 @@
import { mockTemperatureLogs } from "../mockdata/temperature-logs.mockdata.js"; // Import data
import { logout } from "../shared/utils.js";
import { getLogsOnDeviceId } from "./services/devices.service.js";
const xValues = mockTemperatureLogs.map((log) =>
new Date(log.date).toLocaleString()
); // Full Date labels
const yValues = mockTemperatureLogs.map((log) => log.temperature); // Temperature values
buildTable(mockTemperatureLogs);
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [
{
fill: false,
lineTension: 0.4,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues,
},
],
},
options: {
tooltips: {
callbacks: {
title: function (tooltipItem) {
return `Date: ${tooltipItem[0].label}`;
},
label: function (tooltipItem) {
return `Temperature: ${tooltipItem.value}°C`;
},
},
},
},
});
async function buildChart(data) {
data.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
function buildTable(data) {
var table = document.getElementById(`TemperatureTable`);
data.forEach((log) => {
var averageTemp = (log.tempHigh + log.tempLow) / 2.0;
var color;
if (log.temperature > log.tempHigh) {
color = "tempHigh";
} else if (
log.temperature < log.tempHigh &&
log.temperature > averageTemp
) {
color = "tempMidHigh";
} else if (log.temperature < log.tempLow) {
color = "tempLow";
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) {
color = "tempMidLow";
} else {
color = "tempNormal";
}
var row = ` <tr>
<td>Name</td>
<td class="${color}">${log.temperature}</td>
<td>${log.date}</td>
<td class="tempHigh">${log.tempHigh}</td>
<td class="tempLow">${log.tempLow}</td>
</tr>`;
table.innerHTML += row;
});
const xValues = data.map((log) =>
new Date(log.date).toLocaleString()
); // Full Date labels
const yValues = data.map((log) => log.temperature); // Temperature values
buildTable(data);
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [
{
label: "Temperature",
fill: false,
lineTension: 0.4,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues,
},
],
},
options: {
tooltips: {
callbacks: {
title: function (tooltipItem) {
return `Date: ${tooltipItem[0].label}`;
},
label: function (tooltipItem) {
return `Temperature: ${tooltipItem.value}°C`;
},
},
},
},
});
}
// Get the modal
var modal = document.getElementById("chartModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function () {
modal.style.display = "block";
};
function buildTable(data) {
var table = document.getElementById(`TemperatureTable`);
data.forEach((log) => {
var averageTemp = (log.tempHigh + log.tempLow) / 2.0;
var color;
if (log.temperature >= log.tempHigh) {
color = "tempHigh";
} else if (
log.temperature < log.tempHigh &&
log.temperature > averageTemp
) {
color = "tempMidHigh";
} else if (log.temperature <= log.tempLow) {
color = "tempLow";
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) {
color = "tempMidLow";
} else {
color = "tempNormal";
}
const date = new Date(log.date).toLocaleDateString();
const time = new Date(log.date).toLocaleTimeString();
table.innerHTML += `
<tr>
<td class="temperature ${color}">${log.temperature}&deg;C</td>
<td>${date}</td>
<td width="50%">${time}</td>
<td width="50%">Min: <b class="low-limit">${log.tempLow}&deg;C</b>, Max: <b class="high-limit">${log.tempHigh}&deg;C</b></td>
</tr>
`;
});
}
// TODO change device id
getLogsOnDeviceId(1)
.then(buildChart)
.catch(err => {
document.getElementById("error").innerText = err;
document.getElementById("error").style.display = "block";
document.getElementById("container").style.display = "none";
});
document.querySelector(".logout-container").addEventListener("click", logout);
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
};
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
};

View File

@ -10,13 +10,18 @@ document.getElementById("loginForm").addEventListener("submit", function(event)
login(emailOrUsername, password)
.then(response => {
if (response.error) {
document.getElementById("form-error").innerText = response.error;
document.getElementById("form-error").style.display = "block";
document.cookie = `auth-token=${response.token}; Path=/`;
return;
}
localStorage.setItem("user", {
id: response.id,
username: response.userName,
});
location.href = "/home";
})
.catch(error => {
document.getElementById("form-error").innerText = error;
document.getElementById("form-error").style.display = "block";
});
});

View File

@ -1,23 +1,33 @@
import { profileData } from "../mockdata/profile.mockdata.js";
import { logout } from "../shared/utils.js";
import { get } from "./services/users.service.js";
import { update } from "./services/users.service.js";
import { updatePassword } from "./services/users.service.js";
var table = document.getElementById(`profileCard`);
let id = localStorage.getItem("id");
get(id).then(res => {
var table = document.getElementById(`profileCard`);
table.innerHTML += `
<div class="pfp">
<img style="width:200px; height:200px" src="${profileData.pfp}">
</div>
<div class="userData">
<h2>${profileData.username}</h2>
<h2>${profileData.email}</h2>
<h2>${res.userName}</h2>
<h2>${res.email}</h2>
</div>
</div>`;
})
var pswModal = document.getElementById("PasswordModal");
var editModal = document.getElementById("editModal");
var editBtn = document.getElementById("openEditModal");
var editIconbtn = document.getElementById("openEditModal");
var passwordBtn = document.getElementById("openPasswordModal");
// Open modals
editBtn.onclick = () => (editModal.style.display = "block");
editIconbtn.onclick = () => (editModal.style.display = "block");
passwordBtn.onclick = () => (pswModal.style.display = "block");
// Close modals when clicking on any close button
@ -25,6 +35,8 @@ document.querySelectorAll(".close").forEach(closeBtn => {
closeBtn.onclick = () => {
pswModal.style.display = "none";
editModal.style.display = "none";
document.getElementById("form-error").innerText = "";
document.getElementById("form-error").style.display = "none";
};
});
@ -33,20 +45,22 @@ window.onclick = (event) => {
if (event.target == pswModal || event.target == editModal) {
pswModal.style.display = "none";
editModal.style.display = "none";
document.getElementById("form-error").innerText = "";
document.getElementById("form-error").style.display = "none";
}
};
document.getElementById("editForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevents default form submission
document.getElementById("form-error-edit").style.display = "none";
document.getElementById("form-error").style.display = "none";
// Get form values
const email = document.getElementById("email").value;
const username = document.getElementById("uname").value;
// Call function with form values
update(email, username)
update(email, username, id)
.then(response => {
if (response?.error) {
document.getElementById("form-error").innerText = response.error;
@ -55,37 +69,36 @@ document.getElementById("editForm").addEventListener("submit", function(event) {
return;
}
location.href = "/login";
location.href = "/profile";
});
});
document.getElementById("PasswordForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevents default form submission
document.getElementById("form-error-password").style.display = "none";
document.getElementById("form-error").style.display = "none";
// Get form values
const oldPassword = document.getElementById("oldpsw").value;
const newPassword = document.getElementById("psw").value;
const repeatPassword = document.getElementById("rpsw").value;
if (newPassword !== repeatPassword) {
let errorDiv = document.getElementById("form-error-password");
let errorDiv = document.getElementById("form-error");
errorDiv.style.display = "block";
errorDiv.innerText = "Passwords do not match!";
return;
}
// Call function with form values
update(email, username)
updatePassword(oldPassword, newPassword, id)
.then(response => {
if (response?.error) {
document.getElementById("form-error").innerText = response.error;
//error messages do not work
if (response.error) {
document.getElementById("form-error").innerText = response.message;
document.getElementById("form-error").style.display = "block";
return;
}
location.href = "/login";
});
});
document.querySelector(".logout-container").addEventListener("click", logout);

View File

@ -14,13 +14,10 @@ document.getElementById("registerForm").addEventListener("submit", function(even
// Call function with form values
create(email, username, password, repeatPassword)
.then(response => {
if (response?.error) {
document.getElementById("form-error").innerText = response.error;
document.getElementById("form-error").style.display = "block";
return;
}
location.href = "/login";
})
.catch(error => {
document.getElementById("form-error").innerText = error;
document.getElementById("form-error").style.display = "block";
});
});

View File

@ -1,16 +1,7 @@
import { address } from "../../shared/constants";
import { request } from "../../shared/utils.js";
export function getDevicesOnUserId(id) {
fetch(`${address}/get-on-user-id`, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ id: id })
})
.then(response => response.json())
.then(data => console.log("Success:", data))
.catch(error => console.error("Error:", error));
export function getDevices() {
return request("GET", "/device");
}
export function update(ids) {
@ -26,15 +17,6 @@ export function update(ids) {
.catch(error => console.error("Error:", error));
}
export function getLogsOnDeviceIds(id) {
fetch(`${address}/get-on-device-ids`, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ ids: id })
})
.then(response => response.json())
.then(data => console.log("Success:", data))
.catch(error => console.error("Error:", error));
}
export function getLogsOnDeviceId(id) {
return request("GET", `/device/logs/${id}`);
}

View File

@ -1,54 +1,37 @@
import { address } from "../../shared/constants.js";
import { handleResponse } from "../../shared/utils.js";
import { request } from "../../shared/utils.js";
export function get() {
return request("GET",`/user/get`)
}
export function login(usernameOrEmail, password) {
return fetch(`${address}/user/login`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
EmailOrUsrn: usernameOrEmail,
Password: password,
}),
})
.then(handleResponse)
.catch(err => { error: err.message });
return request("POST", "/user/login", {
EmailOrUsrn: usernameOrEmail,
Password: password,
});
}
export function create(email, username, password, repeatPassword){
return fetch(`${address}/user/create`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({email: email, username: username, password: password, repeatPassword: repeatPassword})
})
.then(handleResponse)
.catch(err => { error: err.message });
return request("POST", "/user/create", {
email,
username,
password,
repeatPassword,
});
}
export function update(email, username){
return fetch(`${address}/user/update`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({email: email, username: username})
})
.then(handleResponse)
.catch(err => { error: err.message });
return request("PATCH", "/user/update", {
email,
username,
});
}
export function updatePassword(oldPassword, newPassword){
return fetch(`${address}/user/update-password`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({oldPassword: oldPassword, newPassword: newPassword})
})
.then(handleResponse)
.catch(err => { error: err.message });
return request("PATCH", "/user/update-password", {
oldPassword,
newPassword,
});
}

View File

@ -0,0 +1,3 @@
//export const address = "https://temperature.mercantec.tech/api"
export const address = "http://localhost:5000/api";

View File

@ -1 +0,0 @@
export const address = "hhttps://temperature.mercantec.tech/api"

View File

@ -1,12 +1,42 @@
export async function handleResponse(response) {
const json = await response.json();
import { address } from "./constants.js";
if (response.ok || json.error) return json;
export async function request(method, path, body = null) {
const token = document.cookie.match(/\bauth-token=([^;\s]+)/);
if (json.errors) {
return { error: Object.values(response.errors)[0][0] };
}
const headers = {};
if (body)
headers["Content-Type"] = "application/json";
if (token?.length > 1)
headers["Authorization"] = `Bearer ${token[1]}`;
return { error: "Request failed with HTTP code " + response.status };
return new Promise((resolve, reject) => {
fetch(address + path, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
})
.then(async response => {
try {
const json = await response.json();
if (response.ok) return resolve(json);
if (json.error) return reject(json.error);
if (json.message) return reject(json.message);
if (json.errors) return reject(Object.values(json.errors)[0][0]);
} finally {
reject("Request failed with HTTP code " + response.status);
}
})
.catch(err => reject(err.message));
});
}
export function logout() {
localStorage.removeItem("user");
document.cookie = "auth-token=";
window.location.href = "/";
}

View File

@ -1,5 +1,32 @@
body {
font-family: Arial, Helvetica, sans-serif;
margin: 0;
}
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
height: 20px;
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover, .topnav span:hover {
background-color: #ddd;
color: black;
cursor: pointer;
}
.topnav a.active {
background-color: #04aa6d;
color: white;
}
/* Full-width input fields */
@ -15,12 +42,12 @@ input[type=text], input[type=password], input[type=email] {
/* Set a style for all buttons */
button {
background-color: #04AA6D;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
border-radius: 20px;
}
button:hover {
@ -35,20 +62,19 @@ button:hover {
.details {
display: flex;
justify-content: space-between;
justify-content: flex-end;
margin-top: 0.5rem;
}
#form-error {
display: none;
background-color: #FFCDD2;
color: #C62828;
border: 1px solid #C62828;
border-radius: 4px;
padding: 1rem 2rem;
margin-top: 1rem;
.logout-container {
display: flex;
justify-content: center;
align-items: center;
width: 50px;
}
button{
border-radius: 20px;
.logout {
width: 20px;
height: 24px;
}

View File

@ -1,3 +1,16 @@
.error {
background-color: #EF9A9A;
display: none;
background-color: #FFCDD2;
color: #C62828;
border: 1px solid #C62828;
border-radius: 4px;
padding: 1rem 2rem;
margin-top: 1rem;
}
.logout{
width: 20px;
height: 24px;
}

150
frontend/styles/devices.css Normal file
View File

@ -0,0 +1,150 @@
table {
margin: 20px;
font-family: arial, sans-serif;
border-collapse: collapse;
width: 95%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
.addDeviceContainer{
margin-top: 20px;
display: flex;
justify-content: flex-end;
}
#addDevice{
width: 120px;
margin: 0 20px 0 0;
}
.tableConatiner{
display: flex;
justify-content: center;
}
.tableIcons{
margin-inline: 5px;
width: 30px;
height: 30px;
}
.tableIcons:hover {
background-color: #ddd;
color: black;
cursor: pointer;
}
button {
background-color: #04AA6D;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Float cancel and delete buttons and add an equal width */
.cancelbtn, #addbtn, #deletebtn, #editbtn{
float: left;
width: 50%;
}
/* Add a color to the cancel button */
.cancelbtn {
background-color: #ccc;
color: black;
}
/* Add a color to the delete button */
#deletebtn {
background-color: #f44336;
}
/* Add padding and center-align text to the container */
.container {
padding: 16px;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: #474e5d;
padding-top: 50px;
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* Style the horizontal ruler */
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* The Modal Close Button (x) */
#close {
position: absolute;
right: 35px;
top: 15px;
font-size: 40px;
font-weight: bold;
color: #f1f1f1;
}
#close:hover,
#close:focus {
color: #f44336;
cursor: pointer;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and delete button on extra small screens */
@media screen and (max-width: 300px) {
.cancelbtn, .deletebtn {
width: 100%;
}
}
.form-container{
width: 90%;
}
.deviceHeader{
display: flex;
text-align: center;
}

View File

@ -4,8 +4,8 @@
}
body {
margin: 0;
font-family: sans-serif;
margin: 0;
}
main {

View File

@ -1,79 +1,123 @@
body {
margin: 0;
margin: 0;
font-family: Arial, Helvetica, sans-serif;
background-color: #F9F9F9;
font-family: Arial, Helvetica, sans-serif;
}
#container {
background-color: white;
opacity: 100%;
margin: 0 2rem;
}
.topnav {
overflow: hidden;
background-color: #333;
overflow: hidden;
background-color: #333;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #04aa6d;
color: white;
background-color: #04aa6d;
color: white;
}
#table-wrapper {
overflow: hidden;
border-radius: 8px;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
border: 1px solid #DDD;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
background-color: white;
color: #616161;
margin: 20px;
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
width: 95%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
border-right: 1px solid #DDD;
border-bottom: 1px solid #DDD;
text-align: left;
padding: 8px;
}
th {
border-bottom: 2px solid #DDD;
}
tr:nth-child(even) {
background-color: #dddddd;
background-color: #F5F5F5;
}
table .temperature {
text-align: center;
color: white;
font-weight: bold;
width: 20px;
}
table tr:not(:last-child) .temperature {
border-bottom-color: white;
}
.tempHigh {
color: #ff0000;
width: 20px;
background-color: #ff0000;
}
.tempMidHigh {
color: #fffb00;
width: 20px;
background-color: #FFA000;
}
.tempNormal {
color: #02ed26;
width: 20px;
background-color: #AAA;
}
.tempMidLow {
color: #16fae7;
width: 20px;
background-color: #64B5F6;
}
.tempLow {
background-color: #3F51B5;
}
.tempLow {
color: #0004ff;
width: 20px;
.low-limit {
color: #3F51B5;
}
.high-limit {
color: #F00;
}
.chart-container {
margin: 2rem 0;
background-color: white;
border-radius: 8px;
border: 1px solid #DDD;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
}
#error {
margin: 2rem;
}
.chartContainer{
margin: 20px;
}
.tableConatiner{
display: flex;
justify-content: center;
}

View File

@ -49,8 +49,23 @@ h2{
padding: 20px;
border: 1px solid #888;
width: 80%;
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
@-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
@keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */
.close {
color: #aaaaaa;
@ -70,3 +85,12 @@ h2{
width: 90%;
}
.profileContainer {
margin: 2rem 0;
background-color: white;
border-radius: 8px;
border: 1px solid #DDD;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
width: 400px;
}

View File

@ -1,3 +1,5 @@
all: main.c mqtt.c temperature.c device_id.c
$(CC) -lmosquitto -lpthread -li2c main.c mqtt.c temperature.c device_id.c
FILES=main.c brokers/mqtt.c brokers/amqp.c devices/temperature.c devices/display.c device_id.c
all: $(FILES)
$(CC) -lmosquitto -lrabbitmq -lpthread -li2c $(FILES)

35
iot/brokers/amqp.c Normal file
View File

@ -0,0 +1,35 @@
#include <rabbitmq-c/amqp.h>
#include <rabbitmq-c/tcp_socket.h>
#include "../config.h"
amqp_connection_state_t conn;
amqp_socket_t *socket;
void broker_on_connect(void);
void amqp_send_message(char *queue, char *message)
{
amqp_basic_properties_t props;
props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
props.content_type = amqp_literal_bytes("text/plain");
props.delivery_mode = 2;
amqp_basic_publish(conn, 1, amqp_cstring_bytes(queue), amqp_cstring_bytes(queue), 0, 0, &props, amqp_cstring_bytes(message));
}
void init_amqp(void)
{
conn = amqp_new_connection();
socket = amqp_tcp_socket_new(conn);
amqp_socket_open(socket, AMQP_IP, AMQP_PORT);
amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, AMQP_USER, AMQP_PASSWORD);
amqp_channel_open(conn, 1);
broker_on_connect();
for (;;);
}

4
iot/brokers/amqp.h Normal file
View File

@ -0,0 +1,4 @@
void init_amqp(void);
void amqp_send_message(char *topic, char *message);

View File

@ -3,11 +3,11 @@
#include <string.h>
#include <stdbool.h>
#include "config.h"
#include "../config.h"
struct mosquitto *mosq;
void mqtt_on_connect(void);
void broker_on_connect(void);
void on_connect(struct mosquitto *client, void *obj, int rc)
{
@ -18,7 +18,7 @@ void on_connect(struct mosquitto *client, void *obj, int rc)
puts("Connected to " MQTT_IP);
mqtt_on_connect();
broker_on_connect();
}
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)

View File

@ -3,3 +3,7 @@
#define MQTT_USER "user"
#define MQTT_PASSWORD "password"
#define AMQP_IP "127.0.0.1"
#define AMQP_PORT 5672
#define AMQP_USER "user"
#define AMQP_PASSWORD "password"

60
iot/devices/display.c Normal file
View File

@ -0,0 +1,60 @@
#include <linux/i2c-dev.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <i2c/smbus.h>
#include "display.h"
#define JHD1313_BUS "/dev/i2c-2"
#define JHD1313_ADR 0x3e
void display_set_cursor_pos(display_handle_t display, int x, int y)
{
i2c_smbus_write_byte_data(display, 0x00, (y ? 0xC0 : 0x80) + x);
}
void display_write_str(display_handle_t display, char *str)
{
while (*str) {
display_write_char(display, *str);
str++;
}
}
void display_write_char(display_handle_t display, char ch)
{
i2c_smbus_write_byte_data(display, 0x40, ch);
}
display_handle_t init_display()
{
int file = open(JHD1313_BUS, O_RDWR);
if (file < 0) {
perror("Error opening display device");
exit(EXIT_FAILURE);
}
if (ioctl(file, I2C_SLAVE, JHD1313_ADR) == -1) {
fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", JHD1313_ADR, JHD1313_BUS, strerror(errno));
exit(EXIT_FAILURE);
}
// 2 line mode, 5x8
i2c_smbus_write_byte_data(file, 0x00, 0x28);
// Display on, cursor on, blink off
i2c_smbus_write_byte_data(file, 0x00, 0x0C);
// Display clear
i2c_smbus_write_byte_data(file, 0x00, 0x01);
// Entry mode set
i2c_smbus_write_byte_data(file, 0x00, 0x06);
i2c_smbus_write_byte_data(file, 0x00, 0x02);
return file;
}

10
iot/devices/display.h Normal file
View File

@ -0,0 +1,10 @@
typedef int display_handle_t;
display_handle_t init_display();
void display_set_cursor_pos(display_handle_t display, int x, int y);
void display_write_str(display_handle_t display, char *str);
void display_write_char(display_handle_t display, char ch);

View File

@ -11,8 +11,10 @@
#include "temperature.h"
#define MPC9808_BUS "/dev/i2c-2"
#define MPC9808_ADR 0x18
#define MCP9808_BUS "/dev/i2c-2"
#define MCP9808_ADR 0x18
#define MCP9808_MANID 0x0054
#define MCP9808_DEVID 0x04
#define CONFIG_REG 0x01
#define TUPPER_REG 0x02
@ -53,16 +55,16 @@ double get_temperature(temperature_handle_t file)
temperature_handle_t init_temperature(void)
{
int file = open(MPC9808_BUS, O_RDWR);
int file = open(MCP9808_BUS, O_RDWR);
if (file < 0) {
fprintf(stderr, "Error opening temperature sensor device (%s): %s\n", MPC9808_BUS, strerror(errno));
exit(1);
perror("Error opening temperature sensor device");
exit(EXIT_FAILURE);
}
if (ioctl(file, I2C_SLAVE, MPC9808_ADR) == -1) {
fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", MPC9808_ADR, MPC9808_BUS, strerror(errno));
exit(1);
if (ioctl(file, I2C_SLAVE, MCP9808_ADR) == -1) {
fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", MCP9808_ADR, MCP9808_BUS, strerror(errno));
exit(EXIT_FAILURE);
}
int32_t reg32;
@ -73,23 +75,23 @@ temperature_handle_t init_temperature(void)
reg32 = i2c_smbus_read_word_data(file, MANID_REG);
if (reg32 < 0) {
fprintf(stderr, "ERROR: Read failed on i2c bus register %d - %s\n", MANID_REG,strerror(errno));
exit(1);
fprintf(stderr, "Read failed on i2c bus register %d: %s\n", MANID_REG, strerror(errno));
exit(EXIT_FAILURE);
}
if (bswap_16(reg16poi[0]) != 0x0054) {
fprintf(stderr, "Manufactorer ID wrong is 0x%x should be 0x54\n",__bswap_16(reg16poi[0]));
exit(1);
if (bswap_16(reg16poi[0]) != MCP9808_MANID) {
fprintf(stderr, "Invalid manufacturer ID: Expected 0x%x, got 0x%x\n", MCP9808_MANID, __bswap_16(reg16poi[0]));
exit(EXIT_FAILURE);
}
// Read device ID and revision
reg32 = i2c_smbus_read_word_data(file, DEVID_REG);
if (reg32 < 0) {
fprintf(stderr, "ERROR: Read failed on i2c bus register %d - %s\n", DEVID_REG,strerror(errno) );
exit(1);
fprintf(stderr, "Read failed on i2c bus register %d - %s\n", DEVID_REG, strerror(errno));
exit(EXIT_FAILURE);
}
if (reg8poi[0] != 0x04) {
fprintf(stderr, "Manufactorer ID OK but device ID wrong is 0x%x should be 0x4\n",reg8poi[0]);
exit(1);
if (reg8poi[0] != MCP9808_DEVID) {
fprintf(stderr, "Invalid device ID - expected 0x%x, got 0x%x\n", MCP9808_DEVID, reg8poi[0]);
exit(EXIT_FAILURE);
}
return file;

View File

@ -6,8 +6,9 @@
#include <stdio.h>
#include <time.h>
#include "mqtt.h"
#include "temperature.h"
#include "brokers/amqp.h"
#include "devices/temperature.h"
#include "devices/display.h"
#include "device_id.h"
void *watch_temperature(void *arg)
@ -16,14 +17,21 @@ void *watch_temperature(void *arg)
printf("Device ID: %s\n", device_id);
temperature_handle_t temp_handle = init_temperature();
display_handle_t display = init_display();
display_write_str(display, " ");
display_set_cursor_pos(display, 0, 1);
display_write_str(display, "Device.....");
display_write_str(display, device_id);
temperature_handle_t temp_handle = init_temperature();
get_temperature(temp_handle);
while (true) {
// Retrieve data
double temperature = get_temperature(temp_handle);
size_t timestamp = time(NULL);
// Send JSON
char *format = "{"
"\"temperature\": %lf,"
"\"device_id\": \"%s\","
@ -33,7 +41,16 @@ void *watch_temperature(void *arg)
char *str = malloc(snprintf(NULL, 0, format, temperature, device_id, timestamp) + 1);
sprintf(str, format, temperature, device_id, timestamp);
mqtt_send_message("temperature", str);
amqp_send_message("temperature-logs", str);
free(str);
// Print on display
str = malloc(17);
sprintf(str, "===[ %.1lf\xDF" "C ]===", temperature);
display_set_cursor_pos(display, 0, 0);
display_write_str(display, str);
free(str);
@ -47,7 +64,7 @@ void *watch_temperature(void *arg)
return NULL;
}
void mqtt_on_connect(void)
void broker_on_connect(void)
{
pthread_t temperature_thread;
pthread_create(&temperature_thread, NULL, watch_temperature, NULL);
@ -57,7 +74,7 @@ int main(void)
{
srand(time(NULL));
init_mqtt();
init_amqp();
return EXIT_SUCCESS;
}