Compare commits

..

54 Commits

Author SHA1 Message Date
LilleBRG
c1fbebe0da Merge branches 'master', 'master' and 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-04-03 14:37:07 +02:00
LilleBRG
0c9cd6349c device crud works 2025-04-03 14:35:45 +02:00
9eaba2e77a
Use local timezone on dashboard 2025-04-03 14:09:54 +02:00
Jeas0001
a4f205290d Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-04-03 09:29:31 +02:00
Jeas0001
5dd2a5ec1d Removed temperaturelogs from being a dbset and made it so you can the correct logs from the datetimerange 2025-04-03 09:29:11 +02:00
ea485813fe
Fix device dropdown and chart units 2025-04-03 09:25:33 +02:00
eb66edb902
Fix Chrome issues 2025-04-02 13:48:59 +02:00
b390d4a108
Optimize query to fetch logs within date period 2025-04-02 13:36:51 +02:00
9686e27ba3
Fix not being able to fetch logs in a specific period 2025-04-02 13:16:17 +02:00
59c78e5eac
Fix device list and table duplication 2025-04-02 13:09:46 +02:00
4f9ecfb43d
Add period selector 2025-04-02 12:24:27 +02:00
3d014eab96
Add device dropdown 2025-04-02 09:33:53 +02:00
2516b2b086
Implement pagination in table 2025-04-02 08:58:30 +02:00
LilleBRG
f1b3c39c02 almost done with devices 2025-04-01 14:49:51 +02:00
28cffcfb42
Fix data decimation 2025-04-01 13:50:55 +02:00
96fe8a4cdf
Redirect to dashboard when accessing frontpage while logged in 2025-04-01 13:50:55 +02:00
0c532fb979
Redirect to login when not authenticated 2025-04-01 13:50:55 +02:00
LilleBRG
9529d2cdc8 renamed model folder 2025-04-01 13:15:25 +02:00
82efeff40b
Limit table to 50 rows 2025-04-01 12:50:19 +02:00
9c35f257c5
Enable data decimation 2025-04-01 12:39:53 +02:00
a12784934b
Get device list for dashboard and upgrade chart.js 2025-04-01 12:27:57 +02:00
LilleBRG
49c9a5a792 profile update and password update fixed 2025-04-01 10:30:59 +02:00
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
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
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
68 changed files with 2144 additions and 737 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

@ -5,8 +5,6 @@ VisualStudioVersion = 17.9.34607.119
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Api", "Api.csproj", "{9CCF78E1-969C-420F-BE31-F8AFCE0C6827}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Api", "Api.csproj", "{9CCF78E1-969C-420F-BE31-F8AFCE0C6827}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "..\test\test.csproj", "{5ACD3275-AE0C-458C-AACD-12FE1E165621}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -17,10 +15,6 @@ Global
{9CCF78E1-969C-420F-BE31-F8AFCE0C6827}.Debug|Any CPU.Build.0 = Debug|Any CPU {9CCF78E1-969C-420F-BE31-F8AFCE0C6827}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9CCF78E1-969C-420F-BE31-F8AFCE0C6827}.Release|Any CPU.ActiveCfg = Release|Any CPU {9CCF78E1-969C-420F-BE31-F8AFCE0C6827}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9CCF78E1-969C-420F-BE31-F8AFCE0C6827}.Release|Any CPU.Build.0 = Release|Any CPU {9CCF78E1-969C-420F-BE31-F8AFCE0C6827}.Release|Any CPU.Build.0 = Release|Any CPU
{5ACD3275-AE0C-458C-AACD-12FE1E165621}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5ACD3275-AE0C-458C-AACD-12FE1E165621}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5ACD3275-AE0C-458C-AACD-12FE1E165621}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5ACD3275-AE0C-458C-AACD-12FE1E165621}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -1,7 +1,8 @@
using Api.DBAccess; using Api.DBAccess;
using Api.Models; using Api.Models;
using Api.Models.Devices;
using Api.Models.Users;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Api.BusinessLogic namespace Api.BusinessLogic
{ {
@ -16,6 +17,12 @@ namespace Api.BusinessLogic
_configuration = configuration; _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) public async Task<IActionResult> GetDevices(int userId)
{ {
var profile = await _dbAccess.ReadUser(userId); var profile = await _dbAccess.ReadUser(userId);
@ -24,14 +31,24 @@ namespace Api.BusinessLogic
var devices = await _dbAccess.ReadDevices(userId); var devices = await _dbAccess.ReadDevices(userId);
if (devices.Count == 0) { return new ConflictObjectResult(new { message = "Could not find any devices connected to the user" }); } if (devices.Count == 0) { return new OkObjectResult(new { message = "Could not find any devices connected to the user" }); }
return new OkObjectResult(devices); 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(string referenceId, int userId) public async Task<IActionResult> AddDevice(string referenceId, int userId)
{ {
var profile = await _dbAccess.ReadUser(userId); var profile = await _dbAccess.ReadUser(userId);
var possibleDevice = _dbAccess.ReadDevice(referenceId);
if (possibleDevice != null) { return new ConflictObjectResult(new { message = "Device with given referenceId already exists" }); }
if (profile == null) { return new ConflictObjectResult(new { message = "Could not find user" }); } if (profile == null) { return new ConflictObjectResult(new { message = "Could not find user" }); }
@ -44,29 +61,49 @@ namespace Api.BusinessLogic
Logs = new List<TemperatureLogs>(), Logs = new List<TemperatureLogs>(),
}; };
return await _dbAccess.CreateDevice(device, userId); 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); var device = await _dbAccess.ReadDevice(deviceId);
if (device == null) { return new ConflictObjectResult(new { message = "Could not find device" }); } if (device == null) { return new ConflictObjectResult(new { message = "Could not find device" }); }
var logs = await _dbAccess.ReadLogs(deviceId); var logs = await _dbAccess.ReadLogs(deviceId, dateTimeRange);
if (logs.Count == 0) { return new ConflictObjectResult(new { message = "Could not find any logs connected to the device" }); }
return new OkObjectResult(logs); return new OkObjectResult(logs);
} }
public async Task<IActionResult> EditDevice(Device device, int deviceId) /// <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(EditDeviceRequest device, int deviceId)
{ {
var device1 = _dbAccess.ReadDevice(deviceId); return await _dbAccess.EditDevice(device, deviceId);
}
if (device1 == null) { return new ConflictObjectResult(new { message = "Could not find device" }); } /// <summary>
/// deletes a device
return await _dbAccess.UpdateDevice(device, deviceId); /// </summary>
/// <param name="referenceId">the id used to delete</param>
/// <param name="userId">Used for deleting device from devices list in user</param>
/// <returns>returns OK</returns>
public async Task<IActionResult> DeleteDevice(int deviceId, int userId)
{
return await _dbAccess.DeleteDevice(deviceId, userId);
} }
} }
} }

View File

@ -1,6 +1,7 @@
using Api.DBAccess; using Api.DBAccess;
using Api.Models; using Api.Models;
using Api.Models.User; using Api.Models.Devices;
using Api.Models.Users;
using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
@ -31,6 +32,14 @@ namespace Api.BusinessLogic
return new OkObjectResult(new { user.Id, user.UserName, user.Email }); 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) public async Task<IActionResult> RegisterUser(User user)
{ {
if (!new Regex(@".+@.+\..+").IsMatch(user.Email)) if (!new Regex(@".+@.+\..+").IsMatch(user.Email))
@ -56,6 +65,14 @@ namespace Api.BusinessLogic
return await _dbAccess.CreateUser(user); 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) public async Task<IActionResult> Login(Login login)
{ {
User user = await _dbAccess.Login(login); User user = await _dbAccess.Login(login);
@ -67,12 +84,23 @@ namespace Api.BusinessLogic
if (user.Password == hashedPassword) if (user.Password == hashedPassword)
{ {
var token = GenerateJwtToken(user); var token = GenerateJwtToken(user);
return new OkObjectResult(new { token, 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" }); 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(EditUserRequest userRequest, int userId) public async Task<IActionResult> EditProfile(EditUserRequest userRequest, int userId)
{ {
return await _dbAccess.UpdateUser(userRequest, userId); return await _dbAccess.UpdateUser(userRequest, userId);
@ -100,11 +128,30 @@ namespace Api.BusinessLogic
return await _dbAccess.updatePassword(hashedNewPassword, userId); 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) public async Task<IActionResult> DeleteUser(int userId)
{ {
return await _dbAccess.DeleteUser(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) private static string ComputeHash(string input, HashAlgorithm algorithm, string salt)
{ {
Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
@ -120,6 +167,11 @@ namespace Api.BusinessLogic
return BitConverter.ToString(hashedBytes); 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) public bool PasswordSecurity(string password)
{ {
var hasMinimum8Chars = new Regex(@".{8,}"); var hasMinimum8Chars = new Regex(@".{8,}");
@ -127,6 +179,11 @@ namespace Api.BusinessLogic
return hasMinimum8Chars.IsMatch(password); 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) private string GenerateJwtToken(User user)
{ {
var claims = new[] var claims = new[]
@ -144,7 +201,7 @@ namespace Api.BusinessLogic
_configuration["JwtSettings:Issuer"], _configuration["JwtSettings:Issuer"],
_configuration["JwtSettings:Audience"], _configuration["JwtSettings:Audience"],
claims, claims,
expires: DateTime.Now.AddMinutes(30), expires: DateTime.Now.AddHours(2),
signingCredentials: creds); signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token); return new JwtSecurityTokenHandler().WriteToken(token);

View File

@ -3,6 +3,8 @@ using Api.Models;
using Api.DBAccess; using Api.DBAccess;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Api.BusinessLogic; using Api.BusinessLogic;
using System.Security.Claims;
using Api.Models.Devices;
namespace Api.Controllers namespace Api.Controllers
{ {
@ -19,42 +21,64 @@ namespace Api.Controllers
_deviceLogic = deviceLogic; _deviceLogic = deviceLogic;
} }
// Sends the userId to deviceLogic
[Authorize] [Authorize]
[HttpGet("{userId}")] [HttpGet]
public async Task<IActionResult> GetDevices(int userId) public async Task<IActionResult> GetDevices()
{ {
List<Device> devices = await _dbAccess.ReadDevices(userId); var claims = HttpContext.User.Claims;
if (devices.Count == 0) { return BadRequest(new { error = "There is no devices that belong to this userID" }); } string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _deviceLogic.GetDevices(userId); return await _deviceLogic.GetDevices(userId);
} }
// Sends the device and userId to deviceLogic
[Authorize] [Authorize]
[HttpPost("adddevice/{userId}")] [HttpPost("adddevice/{referenceId}")]
public async Task<IActionResult> AddDevice([FromBody] string referenceId, int userId) public async Task<IActionResult> AddDevice(string referenceId)
{ {
var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _deviceLogic.AddDevice(referenceId, userId); return await _deviceLogic.AddDevice(referenceId, userId);
} }
// Sends the deviceId to deviceLogic
[Authorize] [Authorize]
[HttpGet("logs/{deviceId}")] [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.UnixEpoch;
dateTimeRange.DateTimeEnd = DateTime.Now;
}
return await _deviceLogic.GetLogs(dateTimeRange, deviceId);
} }
// Sends the deviceId to deviceLogic
[Authorize] [Authorize]
[HttpPut("Edit/{deviceId}")] [HttpPut("update/{deviceId}")]
public async Task<IActionResult> EditDevice([FromBody] Device device, int deviceId) public async Task<IActionResult> EditDevice([FromBody] EditDeviceRequest device, int deviceId)
{ {
return await _deviceLogic.EditDevice(device, deviceId); return await _deviceLogic.EditDevice(device, deviceId);
} }
// Sends the userId to userLogic
[Authorize] [Authorize]
[HttpDelete("Delete/{referenceId}")] [HttpDelete("Delete/{deviceId}")]
public async Task<IActionResult> EditDevice(string referenceId) public async Task<IActionResult> DeleteDevice(int deviceId)
{ {
return await _deviceLogic.EditDevice(referenceId); var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _deviceLogic.DeleteDevice(deviceId, userId);
} }
} }
} }

View File

@ -1,8 +1,9 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Api.Models; using Api.Models;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Api.BusinessLogic; using Api.BusinessLogic;
using Api.Models.User; using Api.Models.Users;
namespace Api.Controllers namespace Api.Controllers
{ {
@ -18,42 +19,60 @@ namespace Api.Controllers
} }
//[Authorize] //[Authorize]
[HttpGet("{userId}")] [HttpGet("Get")]
public async Task<IActionResult> GetUSer(int userId) 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); return await _userLogic.getUser(userId);
} }
[HttpPost("login")]
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] Login login) public async Task<IActionResult> Login([FromBody] Login login)
{ {
return await _userLogic.Login(login); return await _userLogic.Login(login);
} }
[HttpPost("create")] // Sends the user to userLogic
[HttpPost("Create")]
public async Task<IActionResult> CreateUser([FromBody] User user) public async Task<IActionResult> CreateUser([FromBody] User user)
{ {
return await _userLogic.RegisterUser(user); return await _userLogic.RegisterUser(user);
} }
//[Authorize] [Authorize]
[HttpPut("edit/{userId}")] [HttpPut("change-password")]
public async Task<IActionResult> EditUser([FromBody] EditUserRequest userRequest, int userId) public async Task<IActionResult> changePassword([FromBody] ChangePasswordRequest passwordRequest)
{
return await _userLogic.EditProfile(userRequest, userId);
}
//[Authorize]
[HttpPut("change-password/{userId}")]
public async Task<IActionResult> changePassword([FromBody] ChangePasswordRequest passwordRequest, int userId)
{ {
var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _userLogic.changePassword(passwordRequest, userId); return await _userLogic.changePassword(passwordRequest, userId);
} }
// Sends the user and userId to userLogic
[Authorize] [Authorize]
[HttpDelete("delete/{userId}")] [HttpPut("Update")]
public async Task<IActionResult> DeleteUser(int userId) public async Task<IActionResult> EditUser([FromBody] EditUserRequest userRequest)
{ {
var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _userLogic.EditProfile(userRequest, userId);
}
// Sends the userId to userLogic
[Authorize]
[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); return await _userLogic.DeleteUser(userId);
} }
} }
} }

View File

@ -1,11 +1,11 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Api.Models; using Api.Models;
using System.Text;
using System.Runtime.Intrinsics.Arm;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using static System.Runtime.InteropServices.JavaScript.JSType; using static System.Runtime.InteropServices.JavaScript.JSType;
using Api.Models.User; using Api.Models.Devices;
using Api.Models.Users;
using Microsoft.AspNetCore.Http.HttpResults;
using System.Collections.Generic;
namespace Api.DBAccess namespace Api.DBAccess
@ -24,7 +24,11 @@ namespace Api.DBAccess
return await _context.Users.FirstOrDefaultAsync(u => u.Id == 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) public async Task<IActionResult> CreateUser(User user)
{ {
var users = await _context.Users.ToListAsync(); var users = await _context.Users.ToListAsync();
@ -50,6 +54,11 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to databse" }); 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) public async Task<User> Login(Login login)
{ {
User user = new User(); User user = new User();
@ -66,11 +75,33 @@ namespace Api.DBAccess
return user; return user;
} }
// Returns a user according to userID
public async Task<User> ReadUser(int userId) public async Task<User> ReadUser(int userId)
{ {
return await _context.Users.FirstOrDefaultAsync(u => u.Id == 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(EditUserRequest user, int userId) public async Task<IActionResult> UpdateUser(EditUserRequest user, int userId)
{ {
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId); var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
@ -91,11 +122,14 @@ namespace Api.DBAccess
} }
} }
if(user.Email != "" && user.Email != null) if(user.Email == "" || user.Email == null)
profile.Email = user.Email; return new ConflictObjectResult(new { message = "Please enter an email" });
if (user.UserName != "" && user.UserName != null) if (user.UserName == "" || user.UserName == null)
profile.UserName = user.UserName; return new ConflictObjectResult(new { message = "Please enter a username" });
profile.Email = user.Email;
profile.UserName = user.UserName;
@ -121,6 +155,11 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to database" }); 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) public async Task<IActionResult> DeleteUser(int userId)
{ {
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId); var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
@ -144,25 +183,46 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Invalid user" }); return new ConflictObjectResult(new { message = "Invalid user" });
} }
public async Task<List<Device>> ReadDevices(int userId) // Returns devices according to userID
public async Task<List<GetDeviceDTO>> ReadDevices(int userId)
{ {
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId); var user = await _context.Users.Include(u => u.Devices).ThenInclude(u => u.Logs).FirstOrDefaultAsync(u => u.Id == userId);
if (user == null || user.Devices == null) { return new List<Device>(); } if (user == null || user.Devices == null) { return new List<GetDeviceDTO>(); }
var devices = user.Devices; List<GetDeviceDTO> devices = new List<GetDeviceDTO>();
foreach (var item in user.Devices)
{
var latestLog = item.Logs?.OrderByDescending(log => log.Date).FirstOrDefault(); // Get the latest log
GetDeviceDTO device = new GetDeviceDTO
{
Id = item.Id,
Name = item.Name,
TempHigh = item.TempHigh,
TempLow = item.TempLow,
ReferenceId = item.ReferenceId,
LatestLog = latestLog
};
devices.Add(device);
}
return devices; 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) public async Task<IActionResult> CreateDevice(Device device, int userId)
{ {
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId); var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
if (user == null || user.Devices == null) { return new ConflictObjectResult(new { message = "User did not have a device list" }); } if (user == null || user.Devices == null) { return new ConflictObjectResult(new { message = "User did not have a device list" }); }
if (device.Logs == null) { device.Logs = new List<TemperatureLogs>(); }
user.Devices.Add(device); user.Devices.Add(device);
bool saved = await _context.SaveChangesAsync() == 1; bool saved = await _context.SaveChangesAsync() == 1;
@ -172,48 +232,99 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to database" }); return new ConflictObjectResult(new { message = "Could not save to database" });
} }
// Returns a device according to deviceId
public async Task<Device> ReadDevice(int deviceId) public async Task<Device> ReadDevice(int deviceId)
{ {
return await _context.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); return await _context.Devices.FirstOrDefaultAsync(d => d.Id == deviceId);
} }
public Device ReadDevice(string refenreId) // Returns a device according to refenreId
public Device ReadDevice(string referenceId)
{ {
return _context.Devices.FirstOrDefault(d => d.ReferenceId == refenreId); return _context.Devices.FirstOrDefault(d => d.ReferenceId == referenceId);
} }
public async Task<IActionResult> UpdateDevice(Device device, int deviceId)
/// <summary>
/// Updates a device in the database
/// </summary>
/// <param name="request">Contains the updated device info</param>
/// <param name="referenceId">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> EditDevice(EditDeviceRequest request, int deviceId)
{ {
var device1 = await _context.Devices.FirstOrDefaultAsync(u => u.Id == deviceId); var device = await _context.Devices.FirstOrDefaultAsync(d => d.Id == deviceId);
if (device != null)
{
if (device.Name == "" || device.Name == null)
return new ConflictObjectResult(new { message = "Please enter a name" });
if (device1 == null) { return new ConflictObjectResult(new { message = "Device does not exist" }); } device.Name = request.Name;
device.TempLow = request.TempLow;
device.TempHigh = request.TempHigh;
device1.TempLow = device.TempLow; bool saved = await _context.SaveChangesAsync() >= 0;
device1.TempHigh = device.TempHigh; if (saved) { return new OkObjectResult(saved); }
device1.ReferenceId = device.ReferenceId; return new ConflictObjectResult(new { message = "Could not save to database" });
}
device1.Name = device.Name; return new ConflictObjectResult(new { message = "Invalid device. May already be deleted" });
bool saved = await _context.SaveChangesAsync() == 1;
if (saved) { return new OkObjectResult(device1); }
return new ConflictObjectResult(new { message = "Could not save to database" });
} }
public async Task<List<TemperatureLogs>> ReadLogs(int deviceId) public async Task<IActionResult> DeleteDevice(int deviceId, int userId)
{ {
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.Id == deviceId); var user = await _context.Users
.Include(u => u.Devices) // Ensure devices are loaded
.FirstOrDefaultAsync(u => u.Id == userId);
if (device == null || device.Logs == null) { return new List<TemperatureLogs>(); } if (user == null)
{
return new NotFoundObjectResult(new { message = "User not found" });
}
var logs = device.Logs; var device = user.Devices?.FirstOrDefault(d => d.Id == deviceId);
return logs; if (device != null || user.Devices != null)
{
user.Devices.Remove(device);
bool userDeviceDeleted = await _context.SaveChangesAsync() > 0;
if (userDeviceDeleted)
{
_context.Devices.Remove(device);
bool saved = await _context.SaveChangesAsync() > 0;
if (saved) return new OkObjectResult(new { message = "Device deleted successfully" });
}
return new ConflictObjectResult(new { message = "Could not save to database" });
}
return new NotFoundObjectResult(new { message = "Device not found or already deleted" });
} }
// Returns all devices
public List<Device> ReadDevices()
{
return _context.Devices.ToList();
}
/// <summary>
/// Returns the logs from the device
/// </summary>
/// <param name="deviceId">Has the id for the device that the los belong too</param>
/// <param name="range">Return only logs within the specified datetime range</param>
/// <returns></returns>
public async Task<List<TemperatureLogs>> ReadLogs(int deviceId, DateTimeRange range)
{
return _context.Devices.Include(d => d.Logs.Where(l => l.Date > range.DateTimeStart && l.Date < range.DateTimeEnd)).Where(d => d.Id == deviceId).FirstOrDefault().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) public async void CreateLog(TemperatureLogs temperatureLogs, string referenceId)
{ {
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.ReferenceId == referenceId); var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.ReferenceId == referenceId);
@ -226,6 +337,7 @@ namespace Api.DBAccess
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
} }
// Does a health check on the database access
public async Task<bool> Test() public async Task<bool> Test()
{ {
return _context.Database.CanConnect(); return _context.Database.CanConnect();

View File

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

View File

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

@ -0,0 +1,140 @@
// <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("20250402113522_ChangeModelsNamespace")]
partial class ChangeModelsNamespace
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
modelBuilder.Entity("Api.Models.Devices.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.Users.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.Devices.Device", b =>
{
b.HasOne("Api.Models.Users.User", null)
.WithMany("Devices")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Api.Models.TemperatureLogs", b =>
{
b.HasOne("Api.Models.Devices.Device", null)
.WithMany("Logs")
.HasForeignKey("DeviceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Api.Models.Devices.Device", b =>
{
b.Navigation("Logs");
});
modelBuilder.Entity("Api.Models.Users.User", b =>
{
b.Navigation("Devices");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Api.Migrations
{
/// <inheritdoc />
public partial class ChangeModelsNamespace : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_TemperatureLogs_Devices_DeviceId",
table: "TemperatureLogs");
migrationBuilder.AlterColumn<int>(
name: "DeviceId",
table: "TemperatureLogs",
type: "INTEGER",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "INTEGER",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_TemperatureLogs_Devices_DeviceId",
table: "TemperatureLogs",
column: "DeviceId",
principalTable: "Devices",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_TemperatureLogs_Devices_DeviceId",
table: "TemperatureLogs");
migrationBuilder.AlterColumn<int>(
name: "DeviceId",
table: "TemperatureLogs",
type: "INTEGER",
nullable: true,
oldClrType: typeof(int),
oldType: "INTEGER");
migrationBuilder.AddForeignKey(
name: "FK_TemperatureLogs_Devices_DeviceId",
table: "TemperatureLogs",
column: "DeviceId",
principalTable: "Devices",
principalColumn: "Id");
}
}
}

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("20250403070932_RemovedLogsFromDbset")]
partial class RemovedLogsFromDbset
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
modelBuilder.Entity("Api.Models.Devices.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.Users.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.Devices.Device", b =>
{
b.HasOne("Api.Models.Users.User", null)
.WithMany("Devices")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Api.Models.TemperatureLogs", b =>
{
b.HasOne("Api.Models.Devices.Device", null)
.WithMany("Logs")
.HasForeignKey("DeviceId");
});
modelBuilder.Entity("Api.Models.Devices.Device", b =>
{
b.Navigation("Logs");
});
modelBuilder.Entity("Api.Models.Users.User", b =>
{
b.Navigation("Devices");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Api.Migrations
{
/// <inheritdoc />
public partial class RemovedLogsFromDbset : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_TemperatureLogs_Devices_DeviceId",
table: "TemperatureLogs");
migrationBuilder.AlterColumn<int>(
name: "DeviceId",
table: "TemperatureLogs",
type: "INTEGER",
nullable: true,
oldClrType: typeof(int),
oldType: "INTEGER");
migrationBuilder.AddForeignKey(
name: "FK_TemperatureLogs_Devices_DeviceId",
table: "TemperatureLogs",
column: "DeviceId",
principalTable: "Devices",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_TemperatureLogs_Devices_DeviceId",
table: "TemperatureLogs");
migrationBuilder.AlterColumn<int>(
name: "DeviceId",
table: "TemperatureLogs",
type: "INTEGER",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "INTEGER",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_TemperatureLogs_Devices_DeviceId",
table: "TemperatureLogs",
column: "DeviceId",
principalTable: "Devices",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}

View File

@ -17,7 +17,7 @@ namespace Api.Migrations
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "9.0.3"); modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
modelBuilder.Entity("Api.Models.Device", b => modelBuilder.Entity("Api.Models.Devices.Device", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@ -74,7 +74,7 @@ namespace Api.Migrations
b.ToTable("TemperatureLogs"); b.ToTable("TemperatureLogs");
}); });
modelBuilder.Entity("Api.Models.User", b => modelBuilder.Entity("Api.Models.Users.User", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@ -88,6 +88,12 @@ namespace Api.Migrations
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("RefreshToken")
.HasColumnType("TEXT");
b.Property<DateTime>("RefreshTokenExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("Salt") b.Property<string>("Salt")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@ -100,26 +106,26 @@ namespace Api.Migrations
b.ToTable("Users"); b.ToTable("Users");
}); });
modelBuilder.Entity("Api.Models.Device", b => modelBuilder.Entity("Api.Models.Devices.Device", b =>
{ {
b.HasOne("Api.Models.User", null) b.HasOne("Api.Models.Users.User", null)
.WithMany("Devices") .WithMany("Devices")
.HasForeignKey("UserId"); .HasForeignKey("UserId");
}); });
modelBuilder.Entity("Api.Models.TemperatureLogs", b => modelBuilder.Entity("Api.Models.TemperatureLogs", b =>
{ {
b.HasOne("Api.Models.Device", null) b.HasOne("Api.Models.Devices.Device", null)
.WithMany("Logs") .WithMany("Logs")
.HasForeignKey("DeviceId"); .HasForeignKey("DeviceId");
}); });
modelBuilder.Entity("Api.Models.Device", b => modelBuilder.Entity("Api.Models.Devices.Device", b =>
{ {
b.Navigation("Logs"); b.Navigation("Logs");
}); });
modelBuilder.Entity("Api.Models.User", b => modelBuilder.Entity("Api.Models.Users.User", b =>
{ {
b.Navigation("Devices"); b.Navigation("Devices");
}); });

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,4 +1,4 @@
namespace Api.Models namespace Api.Models.Devices
{ {
public class Device public class Device
{ {

View File

@ -0,0 +1,11 @@
namespace Api.Models.Devices
{
public class EditDeviceRequest
{
public string Name { get; set; }
public double TempHigh { get; set; }
public double TempLow { get; set; }
}
}

View File

@ -0,0 +1,12 @@
namespace Api.Models.Devices
{
public class GetDeviceDTO
{
public int Id { get; set; }
public string Name { get; set; }
public double TempHigh { get; set; }
public double TempLow { get; set; }
public string? ReferenceId { get; set; }
public TemperatureLogs LatestLog { get; set; }
}
}

View File

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

View File

@ -1,4 +1,4 @@
namespace Api.Models.User namespace Api.Models.Users
{ {
public class ChangePasswordRequest public class ChangePasswordRequest
{ {

View File

@ -1,4 +1,4 @@
namespace Api.Models.User namespace Api.Models.Users
{ {
public class EditUserRequest public class EditUserRequest
{ {

View File

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

View File

@ -1,10 +1,10 @@
using Api; using Api;
using Api.AMQP;
using Api.AMQPReciever; using Api.AMQPReciever;
using Api.DBAccess; using Api.DBAccess;
using Api.MQTTReciever; using Api.MQTTReciever;
using Microsoft.AspNetCore; using Microsoft.AspNetCore;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
class Program class Program
{ {
@ -12,7 +12,7 @@ class Program
public static void Main(string[] args) public static void Main(string[] args)
{ {
var app = CreateWebHostBuilder(args).Build(); var app = CreateWebHostBuilder(args).Build();
string rabbitMQ = "AMQP"; // This value has to be either "AMQP" or "MQTT"
RunMigrations(app); RunMigrations(app);
@ -24,11 +24,19 @@ class Program
var configuration = services.GetRequiredService<IConfiguration>(); var configuration = services.GetRequiredService<IConfiguration>();
var dbAccess = services.GetRequiredService<DbAccess>(); var dbAccess = services.GetRequiredService<DbAccess>();
//AMQPReciever amqp = new AMQPReciever(configuration, dbAccess); // Choose to either connect AMQP or MQTT
//amqp.Handle_Received_Application_Message().Wait(); if (rabbitMQ == "AMQP")
{
MQTTReciever mqtt = new MQTTReciever(configuration, dbAccess); AMQPReciever amqpReciever = new AMQPReciever(configuration, dbAccess);
mqtt.Handle_Received_Application_Message().Wait(); 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 => services.AddSwaggerGen(c =>
{ {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); 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.UseRouting();
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.UseEndpoints(endpoints => 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();

BIN
docs/Domainmodel.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 136 KiB

2
frontend/.gitignore vendored Normal file
View File

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

View File

@ -8,21 +8,20 @@
<link rel="stylesheet" href="/styles/auth.css"> <link rel="stylesheet" href="/styles/auth.css">
<link rel="stylesheet" href="/styles/devices.css" /> <link rel="stylesheet" href="/styles/devices.css" />
<script defer type="module" src="/scripts/devices.js"></script> <script defer type="module" src="/scripts/devices.js"></script>
<script defer type="module" src="/shared/utils.js"></script>
</head> </head>
<body> <body>
<div id="container"> <div id="container">
<div class="topnav"> <div class="topnav">
<a href="/home/index.html">Home</a> <a href="/home/index.html">Home</a>
<a class="active" href="/devices/index.html">Devices</a> <div style="display: flex; justify-content: flex-end;">
<div style="display: flex; justify-content: flex-end;"> <a class="active" href="/devices">Devices</a>
<a href="/profile/index.html">Profile</a> <a href="/profile">Profile</a>
<span class="logoutContainer"> <span class="logout-container">
<img class="logout" src="/img/logout.png"> <img class="logout" src="/img/logout.png">
</span> </span>
</div> </div>
</div> </div>
<div class="addDeviceContainer"> <div class="addDeviceContainer">
<button id="addDevice">Add Device</button> <button id="addDevice">Add Device</button>
</div> </div>
@ -66,10 +65,10 @@
<input type="text" placeholder="Enter a name for the placement" id="name" required> <input type="text" placeholder="Enter a name for the placement" id="name" required>
<label for="tempHigh"><b>High Temperature</b></label> <label for="tempHigh"><b>High Temperature</b></label>
<input type="text" placeholder="Edit the high temperature" id="tempHigh" required> <input type="number" placeholder="Edit the high temperature" id="tempHigh" required>
<label for="tempLow"><b>Low Temperature</b></label> <label for="tempLow"><b>Low Temperature</b></label>
<input type="text" placeholder="Edit the low temperature" id="tempLow" required> <input type="number" placeholder="Edit the low temperature" id="tempLow" required>
<div class="clearfix"> <div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button> <button type="button" class="cancelbtn">Cancel</button>

View File

@ -1,43 +1,85 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Temperature-Alarm-Web</title> <title>Temperature-Alarm-Web</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <script defer src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="/styles/auth.css"> <script defer src="https://cdn.jsdelivr.net/npm/luxon"></script>
<link rel="stylesheet" href="/styles/home.css" /> <script defer src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon"></script>
<script type="module" src="/scripts/home.js"></script> <script defer type="module" src="/scripts/home.js"></script>
<script defer type="module" src="/shared/utils.js"></script> <link rel="stylesheet" href="/styles/common.css">
</head> <link rel="stylesheet" href="/styles/home.css" />
<link rel="stylesheet" href="/styles/auth.css" />
</head>
<body> <body>
<div id="container"> <div class="topnav">
<div class="topnav"> <a class="active" href="/home">Home</a>
<a class="active" href="/home/index.html">Home</a> <div style="display: flex; justify-content: flex-end;">
<a href="/devices/index.html">Devices</a> <a href="/devices">Devices</a>
<div style="display: flex; justify-content: flex-end;"> <a href="/profile">Profile</a>
<a href="/profile/index.html">Profile</a> <span class="logout-container">
<span class="logoutContainer"> <img class="logout" src="/img/logout.png">
<img class="logout" src="/img/logout.png"> </span>
</span> </div>
</div>
<div id="container">
<div class="chart-container">
<canvas id="chart" height="400"></canvas>
</div>
<div id="filters">
<div>
<div class="form-control">
<label for="device-selector">Select device</label>
<select id="device-selector"></select>
</div>
</div>
<div>
<div class="form-control">
<label>&nbsp;</label>
<div id="period-templates">
<div class="period-template last-x-days" data-days="0">Today</div>
<div class="period-template last-x-days" data-days="3">Last 3 days</div>
<div class="period-template last-x-days" data-days="7">Last week</div>
<div class="period-template" id="all-time">All time</div>
</div>
</div>
<div class="form-control">
<label for="period-start">Start</label>
<input id="period-start" type="datetime-local">
</div>
<div class="form-control">
<label for="period-end">End</label>
<input id="period-end" type="datetime-local">
</div>
</div>
</div>
<div id="table-wrapper">
<table>
<thead>
<tr>
<th>Temperature</th>
<th>Date</th>
<th>Time</th>
<th>Limits</th>
</tr>
</thead>
<tbody id="table-body"></tbody>
</table>
<div id="view-more">
&#9660; View more
(Showing <span id="shown-log-amount"></span>/<span id="total-log-amount"></span>)
</div>
</div>
</div> </div>
</div> <div id="error" class="error"></div>
<div class="chartContainer"> </body>
<canvas id="myChart" style="width: 49%; height: 49%;"></canvas>
</div>
<div class="tableConatiner">
<table>
<tr>
<th>Name</th>
<th>Temperature</th>
<th>Date</th>
<th>TempHigh</th>
<th>TempLow</th>
</tr>
<tbody id="TemperatureTable"></tbody>
</table>
</div>
</div>
</body>
</html> </html>

View File

@ -4,8 +4,13 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>Temperature Alarm</title> <title>Temperature Alarm</title>
<link rel="stylesheet" href="/styles/frontpage.css"> <link rel="stylesheet" href="/styles/frontpage.css">
<link rel="stylesheet" href="/styles/auth.css"> <script type="module">
import { isLoggedIn } from "./shared/utils.js";
if (isLoggedIn()) {
location.href = "/home";
}
</script>
</head> </head>
<body> <body>
<main> <main>

View File

@ -4,6 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>Login - Temperature alarm</title> <title>Login - Temperature alarm</title>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles/common.css">
<link rel="stylesheet" href="/styles/auth.css"> <link rel="stylesheet" href="/styles/auth.css">
<script defer type="module" src="/scripts/login.js"></script> <script defer type="module" src="/scripts/login.js"></script>
</head> </head>
@ -25,7 +26,7 @@
</span> </span>
</div> </div>
<div id="form-error"></div> <div id="form-error" class="error"></div>
</div> </div>
</form> </form>
</body> </body>

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

@ -7,26 +7,28 @@
<link rel="stylesheet" href="/styles/auth.css"> <link rel="stylesheet" href="/styles/auth.css">
<link rel="stylesheet" href="/styles/profile.css"> <link rel="stylesheet" href="/styles/profile.css">
<script defer type="module" src="/scripts/profile.js"></script> <script defer type="module" src="/scripts/profile.js"></script>
<script defer type="module" src="/shared/utils.js"></script>
</head> </head>
<body> <body>
<div id="container"> <div id="container">
<div class="topnav"> <div class="topnav">
<a href="/home/index.html">Home</a> <a href="/home/index.html">Home</a>
<a href="/devices/index.html">Devices</a>
<div style="display: flex; justify-content: flex-end;"> <div style="display: flex; justify-content: flex-end;">
<a class="active" href="/profile/index.html">Profile</a> <a href="/devices">Devices</a>
<span class="logoutContainer"> <a class="active" href="/profile">Profile</a>
<span class="logout-container">
<img class="logout" src="/img/logout.png"> <img class="logout" src="/img/logout.png">
</span> </span>
</div> </div>
</div> </div>
<div id="profileCard"></div> <div style="display: flex; justify-content: center;">
<div class="btnContainer"> <div class="profileContainer">
<button class="btn" id="openEditModal">Edit</button> <div id="profileCard"></div>
<button class="btn" id="openPasswordModal">Change Password</button> <div class="btnContainer">
<button class="btn" id="openEditModal">Edit</button>
</div> <button class="btn" id="openPasswordModal">Change Password</button>
</div>
</div>
</div>
</div> </div>
<div id="editModal" class="modal"> <div id="editModal" class="modal">
@ -36,12 +38,12 @@
<form id="editForm"> <form id="editForm">
<div class="form-container"> <div class="form-container">
<label for="email"><b>Email</b></label> <label for="email"><b>Email</b></label>
<input type="email" placeholder="Enter email "id="email"> <input type="text" placeholder="Enter email "id="email">
<label for="uname"><b>Username</b></label> <label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter username" id="uname"> <input type="text" placeholder="Enter username" id="uname">
<button type="submit">Save Changes</button> <button id="submitEditBtn" type="submit">Save Changes</button>
</div> </div>
</form> </form>

View File

@ -4,6 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>Register - Temperature Alarm</title> <title>Register - Temperature Alarm</title>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles/common.css">
<link rel="stylesheet" href="/styles/auth.css"> <link rel="stylesheet" href="/styles/auth.css">
<script defer type="module" src="/scripts/register.js"></script> <script defer type="module" src="/scripts/register.js"></script>
</head> </head>
@ -33,7 +34,7 @@
</label> </label>
</div> </div>
<div id="form-error"></div> <div id="form-error" class="error"></div>
</div> </div>
</form> </form>
</body> </body>

View File

@ -1,13 +1,17 @@
import { getDevicesOnUserId, deleteDevice, update, add } from "./services/devices.service.js"; import { add, getDevices, update, deleteDevice } from "./services/devices.service.js";
import { devices } from "../mockdata/devices.mockdata.js"; import { devices } from "../mockdata/devices.mockdata.js";
import { logout } from "../shared/utils.js";
let id = localStorage.getItem("id"); getDevices().then(res => {
// getDevicesOnUserId(id).then(res => { if(!res.message){
// buildTable(res) buildTable(res)
// }) }
buildTable(devices); })
let selectedReferenceId = null; // Store the selected referenceId let selectedId = null; // Store the selected referenceId
const nameInput = document.getElementById("name");
const tempHighInput = document.getElementById("tempHigh");
const tempLowInput = document.getElementById("tempLow");
function buildTable(data) { function buildTable(data) {
var table = document.getElementById("deviceTable"); var table = document.getElementById("deviceTable");
@ -20,25 +24,25 @@ function buildTable(data) {
<td>${device.name}</td> <td>${device.name}</td>
<td>${device.tempHigh}</td> <td>${device.tempHigh}</td>
<td>${device.tempLow}</td> <td>${device.tempLow}</td>
<td>Temperature: ${device.latestLog.temperature}°C, Date: ${device.latestLog.date}</td> <td>Temperature: ${device.latestLog}°C, Date: ${device.latestLog}</td>
<td style="width: 90px;"> <td style="width: 90px;">
<img class="editIconbtn tableIcons" src="/img/Edit.png" data-referenceid="${device.referenceId}"> <img class="editIconbtn tableIcons" src="/img/Edit.png" data-id="${device.id}" data-referenceId="${device.referenceId}" data-name="${device.name}" data-tempHigh="${device.tempHigh}" data-tempLow="${device.tempLow}">
<img class="trashBtn tableIcons" src="/img/Trash.png" data-referenceid="${device.referenceId}"> <img class="trashBtn tableIcons" src="/img/Trash.png" data-id="${device.id}" data-referenceId="${device.referenceId}">
</td> </td>
`; `;
table.appendChild(row); table.appendChild(row);
}); });
document.getElementById("addDevice").onclick = () => { document.getElementById("addDevice").onclick = () => {
document.getElementById("addModal").style.display = "block"; document.getElementById("addModal").style.display = "block";
} }
// Attach click event to all trash buttons // Attach click event to all trash buttons
document.querySelectorAll(".trashBtn").forEach((btn) => { document.querySelectorAll(".trashBtn").forEach((btn) => {
btn.onclick = function () { btn.onclick = function () {
selectedReferenceId = this.getAttribute("data-referenceid"); // Store referenceId selectedId = this.getAttribute("data-id"); // Store referenceId
document.getElementById("deleteDeviceHeader").innerHTML = `Delete Device ${selectedReferenceId}`; // document.getElementById("deleteDeviceHeader").innerHTML = `Delete Device ${this.getAttribute("data-referenceId")}`;
document.getElementById("deleteModal").style.display = "block"; document.getElementById("deleteModal").style.display = "block";
}; };
}); });
@ -46,13 +50,17 @@ function buildTable(data) {
// Attach click event to all trash buttons // Attach click event to all trash buttons
document.querySelectorAll(".editIconbtn").forEach((btn) => { document.querySelectorAll(".editIconbtn").forEach((btn) => {
btn.onclick = function () { btn.onclick = function () {
selectedReferenceId = this.getAttribute("data-referenceid"); // Store referenceId selectedId = this.getAttribute("data-id"); // Store referenceId
document.getElementById("editDeviceHeader").innerHTML = `Edit Device ${selectedReferenceId}`; // document.getElementById("editDeviceHeader").innerHTML = `Edit Device ${this.getAttribute("data-referenceId")}`;
nameInput.value = this.getAttribute("data-name");
tempHighInput.value = this.getAttribute("data-tempHigh");
tempLowInput.value = this.getAttribute("data-tempLow");
document.getElementById("editModal").style.display = "block"; document.getElementById("editModal").style.display = "block";
}; };
}); });
} }
document.querySelectorAll(".cancelbtn").forEach(button => { document.querySelectorAll(".cancelbtn").forEach(button => {
button.onclick = () => { button.onclick = () => {
document.getElementById("deleteModal").style.display = "none"; document.getElementById("deleteModal").style.display = "none";
@ -63,9 +71,8 @@ document.querySelectorAll(".cancelbtn").forEach(button => {
}); });
// Delete button logic // Delete button logic
document.getElementById("deletebtn").onclick = () => { document.getElementById("deletebtn").onclick = () => {
if (selectedReferenceId) { if (selectedId) {
deleteDevice(selectedReferenceId); // Call delete function with referenceId deleteDevice(selectedId); // Call delete function with referenceId
document.getElementById("deleteModal").style.display = "none";
window.location.reload(); window.location.reload();
} }
}; };
@ -73,18 +80,26 @@ document.getElementById("deletebtn").onclick = () => {
document.getElementById("addbtn").onclick = () => { document.getElementById("addbtn").onclick = () => {
const referenceId = document.getElementById("referenceId").value; const referenceId = document.getElementById("referenceId").value;
add(referenceId); // Call delete function with referenceId add(referenceId); // Call delete function with referenceId
document.getElementById("deleteModal").style.display = "none"; window.location.reload();
window.location.reload();
}; };
document.getElementById("editbtn").onclick = () => { document.getElementById("editbtn").onclick = () => {
if (selectedReferenceId) { if (selectedId) {
const name = document.getElementById("name").value; const name = document.getElementById("name").value;
const tempHigh = document.getElementById("tempHigh").value; const tempHigh = document.getElementById("tempHigh").value;
const tempLow = document.getElementById("tempLow").value; const tempLow = document.getElementById("tempLow").value;
update(selectedReferenceId, name, tempHigh, tempLow); // Call delete function with referenceId
document.getElementById("deleteModal").style.display = "none"; update(selectedId, name, tempHigh, tempLow).then((response) => {
window.location.reload(); if (response?.error) {
document.getElementById("form-error").innerText = response.error;
document.getElementById("form-error").style.display = "block";
return;
}
location.href = "/devices";
});
} }
}; };
document.querySelector(".logout-container").addEventListener("click", logout);

View File

@ -1,64 +1,220 @@
import { mockTemperatureLogs } from "../mockdata/temperature-logs.mockdata.js"; // Import data import { logout } from "../shared/utils.js";
import { getUser } from "../shared/utils.js";
import { getDevices, getLogsOnDeviceId } from "./services/devices.service.js";
const xValues = mockTemperatureLogs.map((log) => let chart;
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`;
},
},
},
},
});
function buildTable(data) { const TABLE_PAGINATION_SIZE = 30;
var table = document.getElementById(`TemperatureTable`);
data.forEach((log) => { function buildTable(data, offset = 0) {
var averageTemp = (log.tempHigh + log.tempLow) / 2.0; data.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
var color;
if (log.temperature > log.tempHigh) { const page = data.slice(offset, offset + TABLE_PAGINATION_SIZE);
color = "tempHigh";
} else if ( page.forEach(log => {
log.temperature < log.tempHigh && var averageTemp = (log.tempHigh + log.tempLow) / 2.0;
log.temperature > averageTemp var color;
) { if (log.temperature >= log.tempHigh) {
color = "tempMidHigh"; color = "tempHigh";
} else if (log.temperature < log.tempLow) { } else if (
color = "tempLow"; log.temperature < log.tempHigh &&
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) { log.temperature > averageTemp
color = "tempMidLow"; ) {
} else { color = "tempMidHigh";
color = "tempNormal"; } else if (log.temperature <= log.tempLow) {
color = "tempLow";
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) {
color = "tempMidLow";
} else {
color = "tempNormal";
}
const parsedDate = luxon.DateTime.fromISO(log.date).setZone("Europe/Copenhagen").setLocale("gb");
const date = parsedDate.toLocaleString(luxon.DateTime.DATE_SHORT);
const time = parsedDate.toLocaleString(luxon.DateTime.TIME_WITH_SECONDS);
document.getElementById("table-body").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>
`;
});
document.getElementById("shown-log-amount").innerText = Math.min(data.length, offset + TABLE_PAGINATION_SIZE);
document.getElementById("total-log-amount").innerText = data.length;
if (offset + TABLE_PAGINATION_SIZE >= data.length) {
document.getElementById("view-more").style.display = "none";
return;
}
document.getElementById("view-more").style.display = "block";
document.getElementById("view-more").onclick = () => {
buildTable(data, offset + TABLE_PAGINATION_SIZE);
} }
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;
});
} }
function handleError(err) {
document.getElementById("error").innerText = err;
document.getElementById("error").style.display = "block";
document.getElementById("container").style.display = "none";
}
function addDeviceToDropdown(device) {
const opt = document.createElement("option");
opt.innerText = `${device.name} (${device.referenceId})`;
opt.value = device.id;
document.getElementById("device-selector").appendChild(opt);
}
function randomColorChannelValue() {
return Math.floor(Math.random() * 256);
}
function isSameDay(a, b) {
return a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate() === b.getDate();
}
function localToUTC(date) {
if (!date) return null;
return luxon.DateTime.fromISO(date, { zone: "Europe/Copenhagen" }).setZone("UTC");
}
async function fetchData() {
document.body.classList.add("loading");
const startDate = localToUTC(document.getElementById("period-start").value);
const endDate = localToUTC(document.getElementById("period-end").value);
const deviceData = [];
for (const device of devices) {
const data = await getLogsOnDeviceId(device.id, startDate, endDate)
.catch(handleError);
deviceData.push(data);
}
if (deviceData.length === 0) {
return;
}
document.getElementById("table-body").innerHTML = "";
buildTable(deviceData[0]);
if (!chart) {
chart = new Chart("chart", {
type: "line",
data: {
datasets: [],
},
options: {
responsive: false,
parsing: false,
plugins: {
tooltip: {
callbacks: {
label: item => `Temperature: ${item.formattedValue}°C`,
},
},
decimation: {
enabled: true,
algorithm: "lttb",
samples: window.innerWidth / 2,
},
},
scales: {
x: {
type: "time",
time: {
displayFormats: {
hour: "HH:mm",
},
},
adapters: {
date: {
zone: "Europe/Copenhagen",
},
},
},
},
},
});
}
chart.options.scales.x.time.unit = isSameDay(new Date(startDate), new Date(endDate))
? "hour"
: "day";
chart.data.datasets = deviceData.map((dataset, i) => {
const color = new Array(3)
.fill(null)
.map(randomColorChannelValue)
.join(",");
return {
label: devices[i].name,
fill: false,
lineTension: 0.4,
backgroundColor: `rgba(${color}, 1.0)`,
borderColor: `rgba(${color}, 0.1)`,
data: dataset.map(log => ({
x: new Date(log.date).getTime(),
y: log.temperature,
})),
};
});
chart.update();
document.body.classList.remove("loading");
}
function setPeriod(start, end) {
const startDate = start && new Date(start);
startDate?.setMinutes(startDate.getMinutes() - startDate.getTimezoneOffset());
const endDate = start && new Date(end);
endDate?.setMinutes(endDate.getMinutes() - endDate.getTimezoneOffset());
document.getElementById("period-start").value = startDate?.toISOString().slice(0, 16);
document.getElementById("period-end").value = endDate?.toISOString().slice(0, 16);
fetchData();
}
function setPeriodLastDays(days) {
const start = new Date()
start.setDate(new Date().getDate() - days);
start.setHours(0, 0, 0, 0);
setPeriod(start, new Date().setHours(23, 59, 0, 0));
}
for (const elem of document.getElementsByClassName("last-x-days")) {
elem.onclick = event => setPeriodLastDays(event.target.dataset.days);
}
for (const elem of document.querySelectorAll("#period-start, #period-end")) {
elem.onchange = fetchData;
}
document.getElementById("all-time").onclick = () => setPeriod(null, null);
document.querySelector(".logout-container").addEventListener("click", logout);
const devices = await getDevices().catch(handleError);
for (const device of devices) {
addDeviceToDropdown(device);
}
setPeriodLastDays(3);
fetchData();

View File

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

View File

@ -1,78 +1,98 @@
import { profileData } from "../mockdata/profile.mockdata.js"; import { profileData } from "../mockdata/profile.mockdata.js";
import { logout } from "../shared/utils.js";
import { get } from "./services/users.service.js"; import { get } from "./services/users.service.js";
import { update } from "./services/users.service.js"; import { update } from "./services/users.service.js";
import { updatePassword } from "./services/users.service.js"; import { updatePassword } from "./services/users.service.js";
let id = localStorage.getItem("id"); var username;
var email;
get(id).then(res => { get().then((res) => {
var table = document.getElementById(`profileCard`); username = res.userName;
table.innerHTML += ` email = res.email;
var table = document.getElementById(`profileCard`);
table.innerHTML += `
<div class="pfp"> <div class="pfp">
<img style="width:200px; height:200px" src="${profileData.pfp}"> <img style="width:200px; height:200px" src="${profileData.pfp}">
</div> </div>
<div class="userData"> <div class="userData">
<h2>${res.userName}</h2> <h2>${username}</h2>
<h2>${res.email}</h2> <h2>${email}</h2>
</div> </div>
</div>`; </div>`;
}) });
const checkForChanges = () => {
if (emailInput.value !== email || usernameInput.value !== username) {
submitBtn.disabled = false; // Enable button if changes were made
} else {
submitBtn.disabled = true; // Disable button if no changes
}
};
const emailInput = document.getElementById("email");
const usernameInput = document.getElementById("uname");
const submitBtn = document.getElementById("submitEditBtn");
var pswModal = document.getElementById("PasswordModal"); var pswModal = document.getElementById("PasswordModal");
var editModal = document.getElementById("editModal"); var editModal = document.getElementById("editModal");
var editIconbtn = document.getElementById("openEditModal"); var editIconbtn = document.getElementById("openEditModal");
var passwordBtn = document.getElementById("openPasswordModal"); var passwordBtn = document.getElementById("openPasswordModal");
emailInput.addEventListener("input", checkForChanges);
usernameInput.addEventListener("input", checkForChanges);
// Open modals // Open modals
editIconbtn.onclick = () => (editModal.style.display = "block"); editIconbtn.onclick = () => {
document.getElementById("uname").value = username;
document.getElementById("email").value = email;
submitBtn.disabled = true;
editModal.style.display = "block";
};
passwordBtn.onclick = () => (pswModal.style.display = "block"); passwordBtn.onclick = () => (pswModal.style.display = "block");
// Close modals when clicking on any close button // Close modals when clicking on any close button
document.querySelectorAll(".close").forEach(closeBtn => { document.querySelectorAll(".close").forEach((closeBtn) => {
closeBtn.onclick = () => { closeBtn.onclick = () => {
pswModal.style.display = "none"; pswModal.style.display = "none";
editModal.style.display = "none"; editModal.style.display = "none";
document.getElementById("form-error").innerText = ""; document.getElementById("form-error").innerText = "";
document.getElementById("form-error").style.display = "none"; document.getElementById("form-error").style.display = "none";
}; };
}); });
// Close modals when clicking outside // Close modals when clicking outside
window.onclick = (event) => { window.onclick = (event) => {
if (event.target == pswModal || event.target == editModal) { if (event.target == pswModal || event.target == editModal) {
pswModal.style.display = "none"; pswModal.style.display = "none";
editModal.style.display = "none"; editModal.style.display = "none";
document.getElementById("form-error").innerText = ""; document.getElementById("form-error").innerText = "";
document.getElementById("form-error").style.display = "none"; document.getElementById("form-error").style.display = "none";
} }
}; };
document.getElementById("editForm").addEventListener("submit", function(event) { document
.getElementById("editForm")
.addEventListener("submit", function (event) {
event.preventDefault(); // Prevents default form submission event.preventDefault(); // Prevents default form submission
document.getElementById("form-error").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 // Call function with form values
update(email, username, id) update(emailInput.value, usernameInput.value).then((response) => {
.then(response => { if (response?.error) {
if (response?.error) { document.getElementById("form-error").innerText = response.error;
document.getElementById("form-error").innerText = response.error; document.getElementById("form-error").style.display = "block";
document.getElementById("form-error").style.display = "block";
return; return;
} }
location.href = "/profile"; location.href = "/profile";
}); });
}); });
document.getElementById("PasswordForm").addEventListener("submit", function(event) { document
.getElementById("PasswordForm")
.addEventListener("submit", function (event) {
event.preventDefault(); // Prevents default form submission event.preventDefault(); // Prevents default form submission
document.getElementById("form-error").style.display = "none"; document.getElementById("form-error").style.display = "none";
@ -82,19 +102,20 @@ document.getElementById("PasswordForm").addEventListener("submit", function(even
const repeatPassword = document.getElementById("rpsw").value; const repeatPassword = document.getElementById("rpsw").value;
if (newPassword !== repeatPassword) { if (newPassword !== repeatPassword) {
let errorDiv = document.getElementById("form-error"); let errorDiv = document.getElementById("form-error");
errorDiv.style.display = "block"; errorDiv.style.display = "block";
errorDiv.innerText = "Passwords do not match!"; errorDiv.innerText = "Passwords do not match!";
return; return;
} }
updatePassword(oldPassword, newPassword, id) updatePassword(oldPassword, newPassword).then((response) => {
.then(response => { //error messages do not work
//error messages do not work if (response.error) {
if (response.error) { document.getElementById("form-error").innerText = response.message;
document.getElementById("form-error").innerText = response.message; document.getElementById("form-error").style.display = "block";
document.getElementById("form-error").style.display = "block"; return;
return; }
} });
}); });
});
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 // Call function with form values
create(email, username, password, repeatPassword) create(email, username, password, repeatPassword)
.then(response => { .then(response => {
if (response?.error) {
document.getElementById("form-error").innerText = response.error;
document.getElementById("form-error").style.display = "block";
return;
}
location.href = "/login"; location.href = "/login";
})
.catch(error => {
document.getElementById("form-error").innerText = error;
document.getElementById("form-error").style.display = "block";
}); });
}); });

View File

@ -1,65 +1,26 @@
import { address } from "../../shared/constants.js"; import { request } from "../../shared/utils.js";
export function getDevicesOnUserId(userId) { export function getDevices() {
fetch(`${address}/device/${userId}`, { return request("GET", "/device");
method: "GET",
headers: {
"Content-Type": "application/json"
},
})
.then(response => response.json())
.then(data => console.log("Success:", data))
.catch(error => console.error("Error:", error));
} }
export function add(id) { export function add(referenceId) {
fetch(`${address}/device`, { return request("POST", `/device/adddevice/${referenceId}`);
method: "CREATE",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ referenceId: id})
})
.then(response => response.json())
.then(data => console.log("Success:", data))
.catch(error => console.error("Error:", error));
} }
export function update(id, name, tempHigh, tempLow) { export function deleteDevice(deviceId) {
fetch(`${address}/device/${id}`, { return request("DELETE", `/device/delete/${deviceId}`);
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: name, tempHigh: tempHigh, tempLow: tempLow })
})
.then(response => response.json())
.then(data => console.log("Success:", data))
.catch(error => console.error("Error:", error));
} }
export function deleteDevice(referenceId) { export function update(deviceId, name, temphigh, tempLow) {
console.log(referenceId) return request("PUT", `/device/update/${deviceId}`,{
fetch(`${address}/device/${referenceId}`, { name,
method: "DELETE", temphigh,
headers: { tempLow
"Content-Type": "application/json" });
},
})
.then(response => response.json())
.then(data => console.log("Success:", data))
.catch(error => console.error("Error:", error));
} }
export function getLogsOnDeviceIds(id) { export function getLogsOnDeviceId(id, startDate = null, endDate = null) {
fetch(`${address}/get-on-device-ids`, { const query = startDate && endDate ? `?dateTimeStart=${startDate}&dateTimeEnd=${endDate}` : "";
method: "GET", return request("GET", `/device/logs/${id}${query}`);
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));
} }

View File

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

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 = "http://127.0.0.1:5000/api"

View File

@ -1,18 +1,56 @@
export async function handleResponse(response) { import { address } from "./constants.js";
const json = await response.json();
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) { const headers = {};
return { error: Object.values(response.errors)[0][0] }; 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 => {
if (response.status === 401) {
location.href = "/login";
}
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.title) return reject(json.title);
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 = "/";
}
export function getUser() {
return JSON.parse(localStorage.getItem("user"));
}
export function isLoggedIn() {
return document.cookie.match(/\bauth-token=/) && localStorage.getItem("user");
} }
document.querySelectorAll(".logoutContainer").forEach(closeBtn => {
closeBtn.onclick = () => {
localStorage.clear();
window.location.href = "/index.html";
};
});

View File

@ -6,9 +6,9 @@ body {
.topnav { .topnav {
overflow: hidden; overflow: hidden;
background-color: #333; background-color: #333;
} }
.topnav a { .topnav a {
height: 20px; height: 20px;
float: left; float: left;
color: #f2f2f2; color: #f2f2f2;
@ -16,9 +16,9 @@ body {
padding: 14px 16px; padding: 14px 16px;
text-decoration: none; text-decoration: none;
font-size: 17px; font-size: 17px;
} }
.topnav a:hover, .topnav span:hover { .topnav a:hover, .topnav span:hover {
background-color: #ddd; background-color: #ddd;
color: black; color: black;
cursor: pointer; cursor: pointer;
@ -30,7 +30,7 @@ body {
} }
/* Full-width input fields */ /* Full-width input fields */
input[type=text], input[type=password], input[type=email] { input[type=text], input[type=password], input[type=email], input[type=number] {
width: 100%; width: 100%;
padding: 12px 20px; padding: 12px 20px;
margin: 8px 0; margin: 8px 0;
@ -66,25 +66,15 @@ button:hover {
margin-top: 0.5rem; margin-top: 0.5rem;
} }
#form-error { .logout-container {
display: none; display: flex;
background-color: #FFCDD2; justify-content: center;
color: #C62828; align-items: center;
border: 1px solid #C62828; width: 50px;
border-radius: 4px;
padding: 1rem 2rem;
margin-top: 1rem;
} }
.logoutContainer{ .logout {
display: flex; width: 20px;
justify-content: center; height: 24px;
align-items: center;
width: 50px;
}
.logout{
width: 20px;
height: 24px;
} }

View File

@ -1,3 +1,16 @@
.error { .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;
}

View File

@ -5,6 +5,7 @@
body { body {
font-family: sans-serif; font-family: sans-serif;
margin: 0;
} }
main { main {

View File

@ -1,60 +1,182 @@
body { body {
font-family: Arial, Helvetica, sans-serif; margin: 0;
font-family: Arial, Helvetica, sans-serif;
background-color: #F9F9F9;
}
.loading * {
pointer-events: none;
}
.loading #chart, .loading table {
opacity: 50%;
}
.loading select, .loading input {
color: rgba(0, 0, 0, 0.3);
} }
#container { #container {
background-color: white; margin: 0 2rem;
opacity: 100%; }
#table-wrapper {
overflow: hidden;
border-radius: 8px;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
border: 1px solid #DDD;
margin-bottom: 2rem;
background-color: white;
}
#filters {
margin: 2rem auto;
display: flex;
justify-content: space-between;
}
#filters > * {
display: flex;
gap: 1rem;
align-items: center;
} }
table { table {
margin: 20px; font-family: arial, sans-serif;
font-family: arial, sans-serif; border-collapse: collapse;
border-collapse: collapse; width: 100%;
width: 95%; color: #616161;
font-family: arial, sans-serif;
border-collapse: collapse;
transition: opacity ease-in 100ms;
} }
td, td,
th { th {
border: 1px solid #dddddd; border-right: 1px solid #DDD;
text-align: left; border-bottom: 1px solid #DDD;
padding: 8px; text-align: left;
padding: 8px;
}
th {
border-bottom: 2px solid #DDD;
} }
tr:nth-child(even) { 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;
}
td {
white-space: nowrap;
} }
.tempHigh { .tempHigh {
color: #ff0000; background-color: #ff0000;
width: 20px;
} }
.tempMidHigh { .tempMidHigh {
color: #fffb00; background-color: #FFA000;
width: 20px;
} }
.tempNormal { .tempNormal {
color: #02ed26; background-color: #AAA;
width: 20px;
} }
.tempMidLow { .tempMidLow {
color: #16fae7; background-color: #64B5F6;
width: 20px;
} }
.tempLow { .tempLow {
color: #0004ff; background-color: #3F51B5;
width: 20px;
} }
.chartContainer{ .low-limit {
margin: 20px; color: #3F51B5;
}
.high-limit {
color: #F00;
} }
.tableConatiner{ .chart-container {
display: flex; margin: 2rem 0;
justify-content: center; background-color: white;
border-radius: 8px;
border: 1px solid #DDD;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
} }
#chart {
width: 100%;
height: 400px;
transition: opacity ease-in 100ms;
}
#error {
margin: 2rem;
}
#view-more {
display: none;
text-align: center;
padding: 0.5rem;
color: #616161;
background-color: white;
font-size: 0.85rem;
cursor: pointer;
transition-duration: 100ms;
}
#view-more:hover {
color: #212121;
}
#view-more:active {
background-color: #FCFCFC;
}
.form-control {
display: flex;
flex-direction: column;
}
label {
font-size: 0.85rem;
padding-left: 0.2rem;
color: #616161;
}
select, input {
background-color: white;
color: #424242;
border: 1px solid #DDD;
border-radius: 8px;
padding: 0.5rem 1rem;
transition: color ease-in 100ms;
}
select:focus, input:focus {
border-color: #1E88E5;
}
#period-templates {
display: flex;
gap: 1rem;
}
.period-template {
font-size: 0.85rem;
color: #616161;
cursor: pointer;
transition-duration: 100ms;
}
.period-template:hover {
color: #212121;
}

View File

@ -85,3 +85,12 @@ h2{
width: 90%; 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 FILES=main.c brokers/mqtt.c brokers/amqp.c devices/temperature.c devices/display.c device_id.c
$(CC) -lmosquitto -lpthread -li2c main.c mqtt.c temperature.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 <string.h>
#include <stdbool.h> #include <stdbool.h>
#include "config.h" #include "../config.h"
struct mosquitto *mosq; struct mosquitto *mosq;
void mqtt_on_connect(void); void broker_on_connect(void);
void on_connect(struct mosquitto *client, void *obj, int rc) 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); puts("Connected to " MQTT_IP);
mqtt_on_connect(); broker_on_connect();
} }
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) 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_USER "user"
#define MQTT_PASSWORD "password" #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" #include "temperature.h"
#define MPC9808_BUS "/dev/i2c-2" #define MCP9808_BUS "/dev/i2c-2"
#define MPC9808_ADR 0x18 #define MCP9808_ADR 0x18
#define MCP9808_MANID 0x0054
#define MCP9808_DEVID 0x04
#define CONFIG_REG 0x01 #define CONFIG_REG 0x01
#define TUPPER_REG 0x02 #define TUPPER_REG 0x02
@ -53,16 +55,16 @@ double get_temperature(temperature_handle_t file)
temperature_handle_t init_temperature(void) temperature_handle_t init_temperature(void)
{ {
int file = open(MPC9808_BUS, O_RDWR); int file = open(MCP9808_BUS, O_RDWR);
if (file < 0) { if (file < 0) {
fprintf(stderr, "Error opening temperature sensor device (%s): %s\n", MPC9808_BUS, strerror(errno)); perror("Error opening temperature sensor device");
exit(1); exit(EXIT_FAILURE);
} }
if (ioctl(file, I2C_SLAVE, MPC9808_ADR) == -1) { if (ioctl(file, I2C_SLAVE, MCP9808_ADR) == -1) {
fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", MPC9808_ADR, MPC9808_BUS, strerror(errno)); fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", MCP9808_ADR, MCP9808_BUS, strerror(errno));
exit(1); exit(EXIT_FAILURE);
} }
int32_t reg32; int32_t reg32;
@ -73,23 +75,23 @@ temperature_handle_t init_temperature(void)
reg32 = i2c_smbus_read_word_data(file, MANID_REG); reg32 = i2c_smbus_read_word_data(file, MANID_REG);
if (reg32 < 0) { if (reg32 < 0) {
fprintf(stderr, "ERROR: Read failed on i2c bus register %d - %s\n", MANID_REG,strerror(errno)); fprintf(stderr, "Read failed on i2c bus register %d: %s\n", MANID_REG, strerror(errno));
exit(1); exit(EXIT_FAILURE);
} }
if (bswap_16(reg16poi[0]) != 0x0054) { if (bswap_16(reg16poi[0]) != MCP9808_MANID) {
fprintf(stderr, "Manufactorer ID wrong is 0x%x should be 0x54\n",__bswap_16(reg16poi[0])); fprintf(stderr, "Invalid manufacturer ID: Expected 0x%x, got 0x%x\n", MCP9808_MANID, __bswap_16(reg16poi[0]));
exit(1); exit(EXIT_FAILURE);
} }
// Read device ID and revision // Read device ID and revision
reg32 = i2c_smbus_read_word_data(file, DEVID_REG); reg32 = i2c_smbus_read_word_data(file, DEVID_REG);
if (reg32 < 0) { if (reg32 < 0) {
fprintf(stderr, "ERROR: Read failed on i2c bus register %d - %s\n", DEVID_REG,strerror(errno) ); fprintf(stderr, "Read failed on i2c bus register %d - %s\n", DEVID_REG, strerror(errno));
exit(1); exit(EXIT_FAILURE);
} }
if (reg8poi[0] != 0x04) { if (reg8poi[0] != MCP9808_DEVID) {
fprintf(stderr, "Manufactorer ID OK but device ID wrong is 0x%x should be 0x4\n",reg8poi[0]); fprintf(stderr, "Invalid device ID - expected 0x%x, got 0x%x\n", MCP9808_DEVID, reg8poi[0]);
exit(1); exit(EXIT_FAILURE);
} }
return file; return file;

View File

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