Compare commits
4 Commits
master
...
profileand
Author | SHA1 | Date | |
---|---|---|---|
|
8202885870 | ||
|
8f6f332292 | ||
|
a3f3d8f861 | ||
|
f42dcd743a |
@ -1,111 +0,0 @@
|
||||
using Api.DBAccess;
|
||||
using Api.Models;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using RabbitMQ.Client;
|
||||
using RabbitMQ.Client.Events;
|
||||
using System.Security.Cryptography;
|
||||
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"]);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,110 +0,0 @@
|
||||
using Api.DBAccess;
|
||||
using Api.Models;
|
||||
using RabbitMQ.Client;
|
||||
using RabbitMQ.Client.Events;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
|
||||
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);
|
||||
|
||||
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"]);
|
||||
}
|
||||
}
|
||||
}
|
74
backend/Api/AMQPReciever/AMQPReciever.cs
Normal file
74
backend/Api/AMQPReciever/AMQPReciever.cs
Normal file
@ -0,0 +1,74 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
@ -16,12 +16,6 @@ namespace Api.BusinessLogic
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user from dbaccess using the userId and checks if the user exists
|
||||
/// Gets all devices that match the userId and checks if there are any devices connected to the user
|
||||
/// </summary>
|
||||
/// <param name="userId">UserId that matches a user that owns the devices</param>
|
||||
/// <returns>returns the devices in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||
public async Task<IActionResult> GetDevices(int userId)
|
||||
{
|
||||
var profile = await _dbAccess.ReadUser(userId);
|
||||
@ -35,28 +29,24 @@ namespace Api.BusinessLogic
|
||||
return new OkObjectResult(devices);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the user that the device is trying to be added to exists
|
||||
/// Then it is send to dbaccess
|
||||
/// </summary>
|
||||
/// <param name="device">The new device</param>
|
||||
/// <param name="userId">The user that owns the device</param>
|
||||
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||
public async Task<IActionResult> AddDevice(Device device, int userId)
|
||||
public async Task<IActionResult> AddDevice(string referenceId, int userId)
|
||||
{
|
||||
var profile = await _dbAccess.ReadUser(userId);
|
||||
|
||||
if (profile == null) { return new ConflictObjectResult(new { message = "Could not find user" }); }
|
||||
|
||||
Device device = new Device
|
||||
{
|
||||
Name = "Undefined",
|
||||
TempHigh = 0,
|
||||
TempLow = 0,
|
||||
ReferenceId = referenceId,
|
||||
Logs = new List<TemperatureLogs>(),
|
||||
};
|
||||
|
||||
return await _dbAccess.CreateDevice(device, userId);
|
||||
}
|
||||
|
||||
/// <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
|
||||
/// </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(int deviceId)
|
||||
{
|
||||
var device = await _dbAccess.ReadDevice(deviceId);
|
||||
@ -70,12 +60,6 @@ namespace Api.BusinessLogic
|
||||
return new OkObjectResult(logs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the deviceId matches a device
|
||||
/// </summary>
|
||||
/// <param name="device">The updated info</param>
|
||||
/// <param name="deviceId">The device to be edited</param>
|
||||
/// <returns>returns the updated device in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||
public async Task<IActionResult> EditDevice(Device device, int deviceId)
|
||||
{
|
||||
var device1 = _dbAccess.ReadDevice(deviceId);
|
||||
|
@ -1,5 +1,6 @@
|
||||
using Api.DBAccess;
|
||||
using Api.Models;
|
||||
using Api.Models.User;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
@ -22,14 +23,14 @@ namespace Api.BusinessLogic
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
/// <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> getUser(int userId)
|
||||
{
|
||||
User user = await _dbAccess.getUser(userId);
|
||||
|
||||
if (user == null || user.Id == 0) { return new ConflictObjectResult(new { message = "Could not find user" }); }
|
||||
return new OkObjectResult(new { user.Id, user.UserName, user.Email });
|
||||
}
|
||||
|
||||
public async Task<IActionResult> RegisterUser(User user)
|
||||
{
|
||||
if (!new Regex(@".+@.+\..+").IsMatch(user.Email))
|
||||
@ -49,20 +50,12 @@ namespace Api.BusinessLogic
|
||||
|
||||
string salt = Guid.NewGuid().ToString();
|
||||
string hashedPassword = ComputeHash(user.Password, SHA256.Create(), salt);
|
||||
|
||||
|
||||
user.Salt = salt;
|
||||
user.Password = hashedPassword;
|
||||
|
||||
return await _dbAccess.CreateUser(user);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user that matches the login
|
||||
/// Hashes the login password with the users salt
|
||||
/// checks if the hashed password that the login has is the same as the one saved in the database
|
||||
/// </summary>
|
||||
/// <param name="login">Has a username or email and a password</param>
|
||||
/// <returns>Returns a jwt token, username and userid</returns>
|
||||
public async Task<IActionResult> Login(Login login)
|
||||
{
|
||||
User user = await _dbAccess.Login(login);
|
||||
@ -74,67 +67,44 @@ namespace Api.BusinessLogic
|
||||
if (user.Password == hashedPassword)
|
||||
{
|
||||
var token = GenerateJwtToken(user);
|
||||
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 OkObjectResult(new { token, user.Id});
|
||||
}
|
||||
|
||||
return new ConflictObjectResult(new { message = "Invalid password" });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// First checks if the mail is a valid one with regex so if there is something before the @ and after and it has a domain
|
||||
/// Then it checks if the password is to our security standard
|
||||
/// Finds the user that matches the userId and hashes a new hash with the old salt
|
||||
/// Then the updated user and the userId is being send to dbaccess
|
||||
/// </summary>
|
||||
/// <param name="user">Contains the updated user info</param>
|
||||
/// <param name="userId">Has the id for the user that is to be updated</param>
|
||||
/// <returns>returns the updated user in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||
public async Task<IActionResult> EditProfile(User user, int userId)
|
||||
public async Task<IActionResult> EditProfile(EditUserRequest userRequest, int userId)
|
||||
{
|
||||
if (!new Regex(@".+@.+\..+").IsMatch(user.Email))
|
||||
{
|
||||
return new ConflictObjectResult(new { message = "Invalid email address" });
|
||||
}
|
||||
|
||||
if (!PasswordSecurity(user.Password))
|
||||
{
|
||||
return new ConflictObjectResult(new { message = "Password is not up to the security standard" });
|
||||
}
|
||||
|
||||
var profile = await _dbAccess.ReadUser(userId);
|
||||
|
||||
string hashedPassword = ComputeHash(user.Password, SHA256.Create(), profile.Salt);
|
||||
user.Password = hashedPassword;
|
||||
|
||||
return await _dbAccess.UpdateUser(user, userId);
|
||||
return await _dbAccess.UpdateUser(userRequest, userId);
|
||||
}
|
||||
|
||||
public async Task<IActionResult> changePassword(ChangePasswordRequest passwordRequest, int userId)
|
||||
{
|
||||
var user = await _dbAccess.ReadUser(userId);
|
||||
|
||||
string hashedPassword = ComputeHash(passwordRequest.OldPassword, SHA256.Create(), user.Salt);
|
||||
|
||||
if (user.Password != hashedPassword)
|
||||
{
|
||||
return new ConflictObjectResult(new { message = "Old password is incorrect" });
|
||||
|
||||
}
|
||||
|
||||
if (!PasswordSecurity(passwordRequest.NewPassword))
|
||||
{
|
||||
return new ConflictObjectResult(new { message = "New password is not up to the security standard" });
|
||||
}
|
||||
|
||||
string hashedNewPassword = ComputeHash(passwordRequest.NewPassword, SHA256.Create(), user.Salt);
|
||||
|
||||
return await _dbAccess.updatePassword(hashedNewPassword, userId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Just sends the userid of the user that is to be deleted
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that is to be deleted</param>
|
||||
/// <returns>returns the true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||
public async Task<IActionResult> DeleteUser(int userId)
|
||||
{
|
||||
return await _dbAccess.DeleteUser(userId);
|
||||
}
|
||||
|
||||
public async Task<IActionResult> RefreshToken(string refreshToken)
|
||||
{
|
||||
User user = await _dbAccess.ReadUser(refreshToken);
|
||||
if (user == null) { return new ConflictObjectResult(new { message = "Could not match refreshtoken" }); }
|
||||
return new OkObjectResult(GenerateJwtToken(user));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a hash from a salt and input using the algorithm that is provided
|
||||
/// </summary>
|
||||
/// <param name="input">This is the input that is supposed to be hashed</param>
|
||||
/// <param name="algorithm">This is the alogorithm that is used to encrypt the input</param>
|
||||
/// <param name="salt">This is something extra added to make the hashed input more unpredictable</param>
|
||||
/// <returns>The hashed input</returns>
|
||||
private static string ComputeHash(string input, HashAlgorithm algorithm, string salt)
|
||||
{
|
||||
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
|
||||
@ -150,11 +120,6 @@ namespace Api.BusinessLogic
|
||||
return BitConverter.ToString(hashedBytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if password is up to our security standard
|
||||
/// </summary>
|
||||
/// <param name="password">The password that is to be checked</param>
|
||||
/// <returns>true or false dependeing on if the password is up to standard</returns>
|
||||
public bool PasswordSecurity(string password)
|
||||
{
|
||||
var hasMinimum8Chars = new Regex(@".{8,}");
|
||||
@ -162,11 +127,6 @@ namespace Api.BusinessLogic
|
||||
return hasMinimum8Chars.IsMatch(password);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a JWT token that last 2 hours
|
||||
/// </summary>
|
||||
/// <param name="user">Used for sending the userid and username with the token</param>
|
||||
/// <returns>Returns a valid JWTToken</returns>
|
||||
private string GenerateJwtToken(User user)
|
||||
{
|
||||
var claims = new[]
|
||||
@ -184,7 +144,7 @@ namespace Api.BusinessLogic
|
||||
_configuration["JwtSettings:Issuer"],
|
||||
_configuration["JwtSettings:Audience"],
|
||||
claims,
|
||||
expires: DateTime.Now.AddHours(2),
|
||||
expires: DateTime.Now.AddMinutes(30),
|
||||
signingCredentials: creds);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
|
@ -19,23 +19,22 @@ namespace Api.Controllers
|
||||
_deviceLogic = deviceLogic;
|
||||
}
|
||||
|
||||
// Sends the userId to deviceLogic
|
||||
[Authorize]
|
||||
[HttpGet("{userId}")]
|
||||
public async Task<IActionResult> GetDevices(int userId)
|
||||
{
|
||||
List<Device> devices = await _dbAccess.ReadDevices(userId);
|
||||
if (devices.Count == 0) { return BadRequest(new { error = "There is no devices that belong to this userID" }); }
|
||||
return await _deviceLogic.GetDevices(userId);
|
||||
}
|
||||
|
||||
// Sends the device and userId to deviceLogic
|
||||
[Authorize]
|
||||
[HttpPost("adddevice/{userId}")]
|
||||
public async Task<IActionResult> AddDevice([FromBody] Device device, int userId)
|
||||
public async Task<IActionResult> AddDevice([FromBody] string referenceId, int userId)
|
||||
{
|
||||
return await _deviceLogic.AddDevice(device, userId);
|
||||
return await _deviceLogic.AddDevice(referenceId, userId);
|
||||
}
|
||||
|
||||
// Sends the deviceId to deviceLogic
|
||||
[Authorize]
|
||||
[HttpGet("logs/{deviceId}")]
|
||||
public async Task<IActionResult> GetLogs(int deviceId)
|
||||
@ -43,12 +42,19 @@ namespace Api.Controllers
|
||||
return await _deviceLogic.GetLogs(deviceId);
|
||||
}
|
||||
|
||||
// Sends the deviceId to deviceLogic
|
||||
[Authorize]
|
||||
[HttpPut("Edit/{deviceId}")]
|
||||
public async Task<IActionResult> EditDevice([FromBody] Device device, int deviceId)
|
||||
{
|
||||
return await _deviceLogic.EditDevice(device, deviceId);
|
||||
}
|
||||
|
||||
|
||||
[Authorize]
|
||||
[HttpDelete("Delete/{referenceId}")]
|
||||
public async Task<IActionResult> EditDevice(string referenceId)
|
||||
{
|
||||
return await _deviceLogic.EditDevice(referenceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,8 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Api.Models;
|
||||
using Api.DBAccess;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Api.BusinessLogic;
|
||||
using Api.Models.User;
|
||||
|
||||
namespace Api.Controllers
|
||||
{
|
||||
@ -21,41 +17,43 @@ namespace Api.Controllers
|
||||
_userLogic = userLogic;
|
||||
}
|
||||
|
||||
// Sends the login to userLogic
|
||||
[HttpPost("Login")]
|
||||
//[Authorize]
|
||||
[HttpGet("{userId}")]
|
||||
public async Task<IActionResult> GetUSer(int userId)
|
||||
{
|
||||
return await _userLogic.getUser(userId);
|
||||
}
|
||||
[HttpPost("login")]
|
||||
public async Task<IActionResult> Login([FromBody] Login login)
|
||||
{
|
||||
return await _userLogic.Login(login);
|
||||
}
|
||||
|
||||
// Sends the user to userLogic
|
||||
[HttpPost("Create")]
|
||||
[HttpPost("create")]
|
||||
public async Task<IActionResult> CreateUser([FromBody] User user)
|
||||
{
|
||||
return await _userLogic.RegisterUser(user);
|
||||
}
|
||||
|
||||
// Sends the user and userId to userLogic
|
||||
[Authorize]
|
||||
[HttpPut("Edit/{userId}")]
|
||||
public async Task<IActionResult> EditUser([FromBody] User user, int userId)
|
||||
//[Authorize]
|
||||
[HttpPut("edit/{userId}")]
|
||||
public async Task<IActionResult> EditUser([FromBody] EditUserRequest userRequest, int userId)
|
||||
{
|
||||
return await _userLogic.EditProfile(user, userId);
|
||||
return await _userLogic.EditProfile(userRequest, userId);
|
||||
}
|
||||
|
||||
//[Authorize]
|
||||
[HttpPut("change-password/{userId}")]
|
||||
public async Task<IActionResult> changePassword([FromBody] ChangePasswordRequest passwordRequest, int userId)
|
||||
{
|
||||
return await _userLogic.changePassword(passwordRequest, userId);
|
||||
}
|
||||
|
||||
// Sends the userId to userLogic
|
||||
[Authorize]
|
||||
[HttpDelete("Delete/{userId}")]
|
||||
[HttpDelete("delete/{userId}")]
|
||||
public async Task<IActionResult> DeleteUser(int userId)
|
||||
{
|
||||
return await _userLogic.DeleteUser(userId);
|
||||
}
|
||||
|
||||
[HttpGet("RefreshToken")]
|
||||
public async Task<IActionResult> RefreshToken(string refreshToken)
|
||||
{
|
||||
return await _userLogic.RefreshToken(refreshToken);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -5,6 +5,7 @@ using System.Runtime.Intrinsics.Arm;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||
using Api.Models.User;
|
||||
|
||||
|
||||
namespace Api.DBAccess
|
||||
@ -18,11 +19,12 @@ namespace Api.DBAccess
|
||||
_context = context;
|
||||
}
|
||||
|
||||
/// <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<User> getUser(int userId)
|
||||
{
|
||||
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||
}
|
||||
|
||||
|
||||
public async Task<IActionResult> CreateUser(User user)
|
||||
{
|
||||
var users = await _context.Users.ToListAsync();
|
||||
@ -48,11 +50,6 @@ namespace Api.DBAccess
|
||||
return new ConflictObjectResult(new { message = "Could not save to databse" });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a user that matches either the email or username
|
||||
/// </summary>
|
||||
/// <param name="login">Has a username or email and a password here the password is not used</param>
|
||||
/// <returns>(user) that matches the login</returns>
|
||||
public async Task<User> Login(Login login)
|
||||
{
|
||||
User user = new User();
|
||||
@ -69,33 +66,12 @@ namespace Api.DBAccess
|
||||
return user;
|
||||
}
|
||||
|
||||
// Returns a user according to userID
|
||||
public async Task<User> ReadUser(int userId)
|
||||
{
|
||||
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||
}
|
||||
|
||||
// Returns a user according to refreshToken
|
||||
public async Task<User> ReadUser(string refreshToken)
|
||||
{
|
||||
return await _context.Users.FirstOrDefaultAsync(u => u.RefreshToken == refreshToken);
|
||||
}
|
||||
|
||||
public async void UpdatesRefreshToken(string refreshToken, int userId)
|
||||
{
|
||||
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||
|
||||
user.RefreshToken = refreshToken;
|
||||
user.RefreshTokenExpiresAt = DateTime.Now.AddDays(7);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the user in the database
|
||||
/// </summary>
|
||||
/// <param name="user">Contains the updated user info</param>
|
||||
/// <param name="userId">Has the id for the user that is to be updated</param>
|
||||
/// <returns>returns the updated user in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||
public async Task<IActionResult> UpdateUser(User user, int userId)
|
||||
public async Task<IActionResult> UpdateUser(EditUserRequest user, int userId)
|
||||
{
|
||||
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||
var users = await _context.Users.ToListAsync();
|
||||
@ -104,22 +80,24 @@ namespace Api.DBAccess
|
||||
|
||||
foreach (var item in users)
|
||||
{
|
||||
if (item.UserName == user.UserName)
|
||||
if (item.UserName == user.UserName && userId != item.Id)
|
||||
{
|
||||
return new ConflictObjectResult(new { message = "Username is already in use." });
|
||||
}
|
||||
|
||||
if (item.Email == user.Email)
|
||||
if (item.Email == user.Email && userId != item.Id)
|
||||
{
|
||||
return new ConflictObjectResult(new { message = "Email is being used already" });
|
||||
}
|
||||
}
|
||||
|
||||
profile.UserName = user.UserName;
|
||||
if(user.Email != "" && user.Email != null)
|
||||
profile.Email = user.Email;
|
||||
|
||||
if (user.UserName != "" && user.UserName != null)
|
||||
profile.UserName = user.UserName;
|
||||
|
||||
profile.Email = user.Email;
|
||||
|
||||
profile.Password = user.Password;
|
||||
|
||||
bool saved = await _context.SaveChangesAsync() == 1;
|
||||
|
||||
@ -128,11 +106,21 @@ namespace Api.DBAccess
|
||||
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> updatePassword(string newPassword, int userId)
|
||||
{
|
||||
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||
|
||||
if (profile == null) { return new ConflictObjectResult(new { message = "User does not exist" }); }
|
||||
|
||||
profile.Password = newPassword;
|
||||
|
||||
bool saved = await _context.SaveChangesAsync() == 1;
|
||||
|
||||
if (saved) { return new OkObjectResult(profile); }
|
||||
|
||||
return new ConflictObjectResult(new { message = "Could not save to database" });
|
||||
}
|
||||
|
||||
public async Task<IActionResult> DeleteUser(int userId)
|
||||
{
|
||||
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
|
||||
@ -156,7 +144,6 @@ namespace Api.DBAccess
|
||||
return new ConflictObjectResult(new { message = "Invalid user" });
|
||||
}
|
||||
|
||||
// Returns devices according to userID
|
||||
public async Task<List<Device>> ReadDevices(int userId)
|
||||
{
|
||||
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
|
||||
@ -168,12 +155,6 @@ namespace Api.DBAccess
|
||||
return devices;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a user using entityframework core
|
||||
/// </summary>
|
||||
/// <param name="device">The device that is going to be created</param>
|
||||
/// <param name="userId">The user that owns the device</param>
|
||||
/// <returns>returns the true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||
public async Task<IActionResult> CreateDevice(Device device, int userId)
|
||||
{
|
||||
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
|
||||
@ -190,31 +171,17 @@ namespace Api.DBAccess
|
||||
|
||||
return new ConflictObjectResult(new { message = "Could not save to database" });
|
||||
}
|
||||
|
||||
// Returns a device according to userID
|
||||
|
||||
public async Task<Device> ReadDevice(int deviceId)
|
||||
{
|
||||
return await _context.Devices.FirstOrDefaultAsync(d => d.Id == deviceId);
|
||||
}
|
||||
|
||||
// Returns a device according to userID
|
||||
public Device ReadDevice(string refenreId)
|
||||
{
|
||||
return _context.Devices.FirstOrDefault(d => d.ReferenceId == refenreId);
|
||||
}
|
||||
|
||||
// Returns all devices
|
||||
public List<Device> ReadDevices()
|
||||
{
|
||||
return _context.Devices.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a device in the database
|
||||
/// </summary>
|
||||
/// <param name="device">Contains the updated device info</param>
|
||||
/// <param name="deviceId">Has the id for the device that is to be updated</param>
|
||||
/// <returns>returns the updated device in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||
public async Task<IActionResult> UpdateDevice(Device device, int deviceId)
|
||||
{
|
||||
var device1 = await _context.Devices.FirstOrDefaultAsync(u => u.Id == deviceId);
|
||||
@ -236,11 +203,6 @@ namespace Api.DBAccess
|
||||
return new ConflictObjectResult(new { message = "Could not save to database" });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the logs from the device
|
||||
/// </summary>
|
||||
/// <param name="deviceId">Has the id for the device that the los belong too</param>
|
||||
/// <returns></returns>
|
||||
public async Task<List<TemperatureLogs>> ReadLogs(int deviceId)
|
||||
{
|
||||
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.Id == deviceId);
|
||||
@ -252,11 +214,6 @@ namespace Api.DBAccess
|
||||
return logs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new log
|
||||
/// </summary>
|
||||
/// <param name="temperatureLogs">the new log</param>
|
||||
/// <param name="referenceId">the referenceId that belongs too the device that recoded the log</param>
|
||||
public async void CreateLog(TemperatureLogs temperatureLogs, string referenceId)
|
||||
{
|
||||
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.ReferenceId == referenceId);
|
||||
@ -269,7 +226,6 @@ namespace Api.DBAccess
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Does a health check on the database access
|
||||
public async Task<bool> Test()
|
||||
{
|
||||
return _context.Database.CanConnect();
|
||||
|
@ -1,5 +1,6 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Api.Models;
|
||||
using Api.Models.User;
|
||||
|
||||
namespace Api
|
||||
{
|
||||
|
@ -26,14 +26,12 @@ namespace Api.MQTTReciever
|
||||
|
||||
using (mqttClient = mqttFactory.CreateMqttClient())
|
||||
{
|
||||
// Entering our values for conecting to MQTT
|
||||
var mqttClientOptions = new MqttClientOptionsBuilder()
|
||||
.WithTcpServer($"{_configuration["MQTT:host"]}", Convert.ToInt32(_configuration["MQTT:port"]))
|
||||
.WithCredentials($"{_configuration["MQTT:username"]}", $"{_configuration["MQTT:password"]}")
|
||||
.WithCleanSession()
|
||||
.Build();
|
||||
|
||||
// Everytime a message is recieved from the queue it goes into this mqttClient.ApplicationMessageReceivedAsync
|
||||
// Setup message handling before connecting so that queued messages
|
||||
// are also handled properly. When there is no event handler attached all
|
||||
// received messages get lost.
|
||||
@ -43,38 +41,35 @@ namespace Api.MQTTReciever
|
||||
|
||||
string sensorData = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
|
||||
|
||||
var messageReceive = JsonSerializer.Deserialize<MessageReceive>(sensorData);
|
||||
var mqttMessageReceive = JsonSerializer.Deserialize<MQTTMessageReceive>(sensorData);
|
||||
|
||||
// Checks if the message has the data we need
|
||||
if (messageReceive == null || messageReceive.device_id == null || messageReceive.timestamp == 0)
|
||||
if (mqttMessageReceive == null || mqttMessageReceive.temperature == 0 || mqttMessageReceive.device_id == null || mqttMessageReceive.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;
|
||||
string refernceId = mqttMessageReceive.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.Temperature = mqttMessageReceive.temperature;
|
||||
newLog.Date = DateTimeOffset.FromUnixTimeSeconds(mqttMessageReceive.timestamp).DateTime;
|
||||
newLog.TempHigh = device.TempHigh;
|
||||
newLog.TempLow = device.TempLow;
|
||||
|
||||
// Send the data to dbaccess to be saved
|
||||
_dbAccess.CreateLog(newLog, refernceId);
|
||||
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
// Starts the connection to rabbitmq
|
||||
|
||||
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
||||
Console.WriteLine("mqttClient");
|
||||
|
||||
// Subscribes to our topic
|
||||
//var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder().WithTopicTemplate(topic).Build();
|
||||
|
||||
await mqttClient.SubscribeAsync("temperature");
|
||||
|
||||
Console.WriteLine("MQTT client subscribed to topic.");
|
||||
|
@ -1,138 +0,0 @@
|
||||
// <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
|
||||
}
|
||||
}
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
@ -88,12 +88,6 @@ namespace Api.Migrations
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("RefreshToken")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("RefreshTokenExpiresAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Salt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
|
@ -1,11 +0,0 @@
|
||||
namespace Api.Models
|
||||
{
|
||||
public class DeviceLimit
|
||||
{
|
||||
public double TempHigh { get; set; }
|
||||
|
||||
public double TempLow { get; set; }
|
||||
|
||||
public string? ReferenceId { get; set; }
|
||||
}
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
namespace Api.Models
|
||||
{
|
||||
public class MessageReceive
|
||||
public class MQTTMessageReceive
|
||||
{
|
||||
public double temperature { get; set; }
|
||||
|
8
backend/Api/Models/User/ChangePasswordRequest.cs
Normal file
8
backend/Api/Models/User/ChangePasswordRequest.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace Api.Models.User
|
||||
{
|
||||
public class ChangePasswordRequest
|
||||
{
|
||||
public string OldPassword { get; set; }
|
||||
public string NewPassword { get; set; }
|
||||
}
|
||||
}
|
8
backend/Api/Models/User/EditUserRequest.cs
Normal file
8
backend/Api/Models/User/EditUserRequest.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace Api.Models.User
|
||||
{
|
||||
public class EditUserRequest
|
||||
{
|
||||
public string UserName { get; set; }
|
||||
public string Email { get; set; }
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
namespace Api.Models
|
||||
namespace Api.Models.User
|
||||
{
|
||||
public class User
|
||||
{
|
||||
@ -12,10 +12,6 @@
|
||||
|
||||
public string? Salt { get; set; }
|
||||
|
||||
public string? RefreshToken { get; set; }
|
||||
|
||||
public DateTime RefreshTokenExpiresAt { get; set; }
|
||||
|
||||
public List<Device>? Devices { get; set; }
|
||||
}
|
||||
}
|
@ -1,5 +1,4 @@
|
||||
using Api;
|
||||
using Api.AMQP;
|
||||
using Api.AMQPReciever;
|
||||
using Api.DBAccess;
|
||||
using Api.MQTTReciever;
|
||||
@ -13,7 +12,7 @@ class Program
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var app = CreateWebHostBuilder(args).Build();
|
||||
string rabbitMQ = "AMQP"; // This value has to be either "AMQP" or "MQTT"
|
||||
|
||||
|
||||
RunMigrations(app);
|
||||
|
||||
@ -25,19 +24,11 @@ class Program
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
var dbAccess = services.GetRequiredService<DbAccess>();
|
||||
|
||||
// Choose to either connect AMQP or MQTT
|
||||
if (rabbitMQ == "AMQP")
|
||||
{
|
||||
AMQPReciever amqpReciever = new AMQPReciever(configuration, dbAccess);
|
||||
amqpReciever.Handle_Received_Application_Message().Wait();
|
||||
AMQPPublisher aMQPPush = new AMQPPublisher(configuration, dbAccess);
|
||||
aMQPPush.Handle_Push_Device_Limits().Wait();
|
||||
}
|
||||
else if (rabbitMQ == "MQTT")
|
||||
{
|
||||
MQTTReciever mqtt = new MQTTReciever(configuration, dbAccess);
|
||||
mqtt.Handle_Received_Application_Message().Wait();
|
||||
}
|
||||
//AMQPReciever amqp = new AMQPReciever(configuration, dbAccess);
|
||||
//amqp.Handle_Received_Application_Message().Wait();
|
||||
|
||||
MQTTReciever mqtt = new MQTTReciever(configuration, dbAccess);
|
||||
mqtt.Handle_Received_Application_Message().Wait();
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -66,29 +66,6 @@ namespace Api
|
||||
services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
|
||||
|
||||
// Configure Swagger to use Bearer token authentication
|
||||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||
{
|
||||
Description = "JWT Authorization header using the Bearer scheme",
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer"
|
||||
});
|
||||
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||
{
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference
|
||||
{
|
||||
Type = ReferenceType.SecurityScheme,
|
||||
Id = "Bearer"
|
||||
}
|
||||
},
|
||||
new string[] { }
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@ -110,8 +87,6 @@ namespace Api
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthentication();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.UseEndpoints(endpoints =>
|
||||
|
14
backend/ConsoleApp1/ConsoleApp1.csproj
Normal file
14
backend/ConsoleApp1/ConsoleApp1.csproj
Normal file
@ -0,0 +1,14 @@
|
||||
<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>
|
25
backend/ConsoleApp1/ConsoleApp1.sln
Normal file
25
backend/ConsoleApp1/ConsoleApp1.sln
Normal file
@ -0,0 +1,25 @@
|
||||
|
||||
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
|
52
backend/ConsoleApp1/Program.cs
Normal file
52
backend/ConsoleApp1/Program.cs
Normal file
@ -0,0 +1,52 @@
|
||||
using RabbitMQ.Client;
|
||||
using RabbitMQ.Client.Events;
|
||||
using System.Text;
|
||||
|
||||
|
||||
var factory = new ConnectionFactory();
|
||||
var queue = "test";
|
||||
|
||||
|
||||
factory.UserName = "h5";
|
||||
factory.Password = "Merc1234";
|
||||
factory.HostName = "10.135.51.116";
|
||||
factory.Port = 5672;
|
||||
|
||||
using var conn = await factory.CreateConnectionAsync();
|
||||
Console.WriteLine("AMQPClien connected");
|
||||
using var channel = await conn.CreateChannelAsync();
|
||||
|
||||
await channel.QueueDeclareAsync(queue: queue, durable: false, exclusive: false, autoDelete: false);
|
||||
Console.WriteLine($"{queue} connected");
|
||||
|
||||
var consumer = new AsyncEventingBasicConsumer(channel);
|
||||
consumer.ReceivedAsync += (model, ea) =>
|
||||
{
|
||||
Console.WriteLine("Received application message.");
|
||||
var body = ea.Body.ToArray();
|
||||
var message = Encoding.UTF8.GetString(body);
|
||||
Console.WriteLine(message);
|
||||
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
await channel.BasicConsumeAsync(queue, true, consumer);
|
||||
|
||||
|
||||
const string message = "Hello World!";
|
||||
var body = Encoding.UTF8.GetBytes(message);
|
||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
||||
Console.WriteLine(" Press enter to continue.");
|
||||
Console.ReadLine();
|
||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
||||
Console.WriteLine(" Press enter to continue.");
|
||||
Console.ReadLine();
|
||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
||||
Console.WriteLine(" Press enter to continue.");
|
||||
Console.ReadLine();
|
||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
||||
Console.WriteLine(" Press enter to continue.");
|
||||
Console.ReadLine();
|
||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
||||
Console.WriteLine(" Press enter to exit.");
|
||||
Console.ReadLine();
|
@ -0,0 +1,107 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Temperature-Alarm-Web</title>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
|
||||
<link rel="stylesheet" href="/styles/auth.css">
|
||||
<link rel="stylesheet" href="/styles/devices.css" />
|
||||
<script defer type="module" src="/scripts/devices.js"></script>
|
||||
<script defer type="module" src="/shared/utils.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="container">
|
||||
<div class="topnav">
|
||||
<a href="/home/index.html">Home</a>
|
||||
<a class="active" href="/devices/index.html">Devices</a>
|
||||
<div style="display: flex; justify-content: flex-end;">
|
||||
<a href="/profile/index.html">Profile</a>
|
||||
<span class="logoutContainer">
|
||||
<img class="logout" src="/img/logout.png">
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="addDeviceContainer">
|
||||
<button id="addDevice">Add Device</button>
|
||||
</div>
|
||||
<div class="tableConatiner">
|
||||
<table>
|
||||
<tr>
|
||||
<th>Id</th>
|
||||
<th>Placement(name)</th>
|
||||
<th>Set Temp High</th>
|
||||
<th>Set Temp Low</th>
|
||||
<th>Latest Meassurement</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
<tbody id="deviceTable"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div id="deleteModal" class="modal">
|
||||
<form class="modal-content">
|
||||
<div class="container">
|
||||
<h1 class="deviceHeader" id="deleteDeviceHeader"></h1>
|
||||
<p>Are you sure you want to delete this device from your account?</p>
|
||||
|
||||
<div class="clearfix">
|
||||
<button type="button" class="cancelbtn">Cancel</button>
|
||||
<button type="button" id="deletebtn">Delete</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="editModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="container">
|
||||
<h1 class="deviceHeader" id="editDeviceHeader"></h1>
|
||||
<form id="editForm">
|
||||
<div class="form-container">
|
||||
<label for="name"><b>Name</b></label>
|
||||
<input type="text" placeholder="Enter a name for the placement" id="name" required>
|
||||
|
||||
<label for="tempHigh"><b>High Temperature</b></label>
|
||||
<input type="text" placeholder="Edit the high temperature" id="tempHigh" required>
|
||||
|
||||
<label for="tempLow"><b>Low Temperature</b></label>
|
||||
<input type="text" placeholder="Edit the low temperature" id="tempLow" required>
|
||||
|
||||
<div class="clearfix">
|
||||
<button type="button" class="cancelbtn">Cancel</button>
|
||||
<button type="button" id="editbtn">Save Changes</button>
|
||||
</div>
|
||||
|
||||
<div id="form-error"></div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="addModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="container">
|
||||
<h1 class="deviceHeader">Add Device</h1>
|
||||
<form id="editForm">
|
||||
<div class="form-container">
|
||||
<label for="referenceId"><b>Device Id</b></label>
|
||||
<input type="text" placeholder="Enter the device Id" id="referenceId" required>
|
||||
<div id="form-error"></div>
|
||||
</div>
|
||||
<div class="clearfix">
|
||||
<button type="button" class="cancelbtn">Cancel</button>
|
||||
<button type="button" id="addbtn">Add</button>
|
||||
</div>
|
||||
|
||||
<div id="form-error"></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -1,37 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Temperature-Alarm-Web</title>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
|
||||
<link rel="stylesheet" href="/styles/home.css" />
|
||||
<script defer type="module" src="/scripts/home.js"></script>
|
||||
</head>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Temperature-Alarm-Web</title>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
|
||||
<link rel="stylesheet" href="/styles/auth.css">
|
||||
<link rel="stylesheet" href="/styles/home.css" />
|
||||
<script type="module" src="/scripts/home.js"></script>
|
||||
<script defer type="module" src="/shared/utils.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="container">
|
||||
<div class="topnav">
|
||||
<a class="active" href="/home/index.html">Home</a>
|
||||
<div style="display: flex; justify-content: flex-end;">
|
||||
<a class="" href="/home/index.html">Devices</a>
|
||||
<a class="" href="/profile/index.html">Profile</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chartContainer">
|
||||
<canvas id="myChart" style="width: 49%; height: 49%;"></canvas>
|
||||
</div>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Temperature</th>
|
||||
<th>Date</th>
|
||||
<th>TempHigh</th>
|
||||
<th>TempLow</th>
|
||||
</tr>
|
||||
<tbody id="TemperatureTable"></tbody>
|
||||
</table>
|
||||
<body>
|
||||
<div id="container">
|
||||
<div class="topnav">
|
||||
<a class="active" href="/home/index.html">Home</a>
|
||||
<a href="/devices/index.html">Devices</a>
|
||||
<div style="display: flex; justify-content: flex-end;">
|
||||
<a href="/profile/index.html">Profile</a>
|
||||
<span class="logoutContainer">
|
||||
<img class="logout" src="/img/logout.png">
|
||||
</span>
|
||||
</div>
|
||||
</body>
|
||||
</div>
|
||||
<div class="chartContainer">
|
||||
<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>
|
||||
|
||||
|
BIN
frontend/img/Edit.png
Normal file
BIN
frontend/img/Edit.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 11 KiB |
BIN
frontend/img/Trash.png
Normal file
BIN
frontend/img/Trash.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 30 KiB |
BIN
frontend/img/logout.png
Normal file
BIN
frontend/img/logout.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 9.8 KiB |
@ -4,6 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<title>Temperature Alarm</title>
|
||||
<link rel="stylesheet" href="/styles/frontpage.css">
|
||||
<link rel="stylesheet" href="/styles/auth.css">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
|
@ -20,9 +20,6 @@
|
||||
|
||||
<button type="submit">Login</button>
|
||||
<div class="details">
|
||||
<label>
|
||||
<input type="checkbox" name="remember"> Remember me
|
||||
</label>
|
||||
<span>
|
||||
Dont have an account? <a href="/register">Register</a>
|
||||
</span>
|
||||
|
3
frontend/mockdata/devices.mockdata.js
Normal file
3
frontend/mockdata/devices.mockdata.js
Normal file
@ -0,0 +1,3 @@
|
||||
export const devices = [
|
||||
{referenceId: "DKOFG", name: "Kitchen", tempHigh: 23.0, tempLow: 23.0, latestLog: { id: 1, temperature: 18.9, date: "2025-03-19T17:00:00Z", tempHigh: 22.0, tempLow: 18.0 }}
|
||||
]
|
@ -7,9 +7,20 @@
|
||||
<link rel="stylesheet" href="/styles/auth.css">
|
||||
<link rel="stylesheet" href="/styles/profile.css">
|
||||
<script defer type="module" src="/scripts/profile.js"></script>
|
||||
<script defer type="module" src="/shared/utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="container">
|
||||
<div class="topnav">
|
||||
<a href="/home/index.html">Home</a>
|
||||
<a href="/devices/index.html">Devices</a>
|
||||
<div style="display: flex; justify-content: flex-end;">
|
||||
<a class="active" href="/profile/index.html">Profile</a>
|
||||
<span class="logoutContainer">
|
||||
<img class="logout" src="/img/logout.png">
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="profileCard"></div>
|
||||
<div class="btnContainer">
|
||||
<button class="btn" id="openEditModal">Edit</button>
|
||||
@ -25,14 +36,13 @@
|
||||
<form id="editForm">
|
||||
<div class="form-container">
|
||||
<label for="email"><b>Email</b></label>
|
||||
<input type="email" placeholder="Enter email "id="email" required>
|
||||
<input type="email" placeholder="Enter email "id="email">
|
||||
|
||||
<label for="uname"><b>Username</b></label>
|
||||
<input type="text" placeholder="Enter username" id="uname" required>
|
||||
<input type="text" placeholder="Enter username" id="uname">
|
||||
|
||||
<button type="submit">Save Changes</button>
|
||||
|
||||
<div class="error-text" id="form-error-edit"></div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@ -55,7 +65,7 @@
|
||||
|
||||
<button type="submit">Change Password</button>
|
||||
|
||||
<div class="error-text" id="form-error-password"></div>
|
||||
<div id="form-error"></div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
@ -10,7 +10,7 @@
|
||||
<body>
|
||||
<form id="registerForm">
|
||||
<div class="form-container">
|
||||
<h1>Create Account</h1>
|
||||
<h1>Sign Up</h1>
|
||||
|
||||
<label for="email"><b>Email</b></label>
|
||||
<input type="email" placeholder="Enter email "id="email" required>
|
||||
|
90
frontend/scripts/devices.js
Normal file
90
frontend/scripts/devices.js
Normal file
@ -0,0 +1,90 @@
|
||||
import { getDevicesOnUserId, deleteDevice, update, add } from "./services/devices.service.js";
|
||||
import { devices } from "../mockdata/devices.mockdata.js";
|
||||
|
||||
let id = localStorage.getItem("id");
|
||||
// getDevicesOnUserId(id).then(res => {
|
||||
// buildTable(res)
|
||||
// })
|
||||
buildTable(devices);
|
||||
|
||||
let selectedReferenceId = null; // Store the selected referenceId
|
||||
|
||||
function buildTable(data) {
|
||||
var table = document.getElementById("deviceTable");
|
||||
table.innerHTML = ""; // Clear existing rows before adding new ones
|
||||
|
||||
data.forEach((device) => {
|
||||
var row = document.createElement("tr");
|
||||
row.innerHTML = `
|
||||
<td>${device.referenceId}</td>
|
||||
<td>${device.name}</td>
|
||||
<td>${device.tempHigh}</td>
|
||||
<td>${device.tempLow}</td>
|
||||
<td>Temperature: ${device.latestLog.temperature}°C, Date: ${device.latestLog.date}</td>
|
||||
<td style="width: 90px;">
|
||||
<img class="editIconbtn tableIcons" src="/img/Edit.png" data-referenceid="${device.referenceId}">
|
||||
<img class="trashBtn tableIcons" src="/img/Trash.png" data-referenceid="${device.referenceId}">
|
||||
</td>
|
||||
`;
|
||||
table.appendChild(row);
|
||||
});
|
||||
|
||||
document.getElementById("addDevice").onclick = () => {
|
||||
document.getElementById("addModal").style.display = "block";
|
||||
|
||||
}
|
||||
|
||||
// Attach click event to all trash buttons
|
||||
document.querySelectorAll(".trashBtn").forEach((btn) => {
|
||||
btn.onclick = function () {
|
||||
selectedReferenceId = this.getAttribute("data-referenceid"); // Store referenceId
|
||||
document.getElementById("deleteDeviceHeader").innerHTML = `Delete Device ${selectedReferenceId}`;
|
||||
document.getElementById("deleteModal").style.display = "block";
|
||||
};
|
||||
});
|
||||
|
||||
// Attach click event to all trash buttons
|
||||
document.querySelectorAll(".editIconbtn").forEach((btn) => {
|
||||
btn.onclick = function () {
|
||||
selectedReferenceId = this.getAttribute("data-referenceid"); // Store referenceId
|
||||
document.getElementById("editDeviceHeader").innerHTML = `Edit Device ${selectedReferenceId}`;
|
||||
document.getElementById("editModal").style.display = "block";
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll(".cancelbtn").forEach(button => {
|
||||
button.onclick = () => {
|
||||
document.getElementById("deleteModal").style.display = "none";
|
||||
document.getElementById("editModal").style.display = "none";
|
||||
document.getElementById("addModal").style.display = "none";
|
||||
|
||||
};
|
||||
});
|
||||
// Delete button logic
|
||||
document.getElementById("deletebtn").onclick = () => {
|
||||
if (selectedReferenceId) {
|
||||
deleteDevice(selectedReferenceId); // Call delete function with referenceId
|
||||
document.getElementById("deleteModal").style.display = "none";
|
||||
window.location.reload();
|
||||
}
|
||||
};
|
||||
|
||||
document.getElementById("addbtn").onclick = () => {
|
||||
const referenceId = document.getElementById("referenceId").value;
|
||||
add(referenceId); // Call delete function with referenceId
|
||||
document.getElementById("deleteModal").style.display = "none";
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
document.getElementById("editbtn").onclick = () => {
|
||||
if (selectedReferenceId) {
|
||||
const name = document.getElementById("name").value;
|
||||
const tempHigh = document.getElementById("tempHigh").value;
|
||||
const tempLow = document.getElementById("tempLow").value;
|
||||
|
||||
update(selectedReferenceId, name, tempHigh, tempLow); // Call delete function with referenceId
|
||||
document.getElementById("deleteModal").style.display = "none";
|
||||
window.location.reload();
|
||||
}
|
||||
};
|
@ -1,71 +1,64 @@
|
||||
import { mockTemperatureLogs } from "../mockdata/temperature-logs.mockdata.js"; // Import data
|
||||
import { getLogsOnDeviceId } from "./services/devices.service.js";
|
||||
|
||||
async function buildChart() {
|
||||
const data = await getLogsOnDeviceId(1);
|
||||
|
||||
const xValues = mockTemperatureLogs.map((log) =>
|
||||
new Date(log.date).toLocaleString()
|
||||
); // Full Date labels
|
||||
const yValues = mockTemperatureLogs.map((log) => log.temperature); // Temperature values
|
||||
buildTable(mockTemperatureLogs);
|
||||
new Chart("myChart", {
|
||||
type: "line",
|
||||
data: {
|
||||
labels: xValues,
|
||||
datasets: [
|
||||
{
|
||||
fill: false,
|
||||
lineTension: 0.4,
|
||||
backgroundColor: "rgba(0,0,255,1.0)",
|
||||
borderColor: "rgba(0,0,255,0.1)",
|
||||
data: yValues,
|
||||
},
|
||||
],
|
||||
const xValues = mockTemperatureLogs.map((log) =>
|
||||
new Date(log.date).toLocaleString()
|
||||
); // Full Date labels
|
||||
const yValues = mockTemperatureLogs.map((log) => log.temperature); // Temperature values
|
||||
buildTable(mockTemperatureLogs);
|
||||
new Chart("myChart", {
|
||||
type: "line",
|
||||
data: {
|
||||
labels: xValues,
|
||||
datasets: [
|
||||
{
|
||||
fill: false,
|
||||
lineTension: 0.4,
|
||||
backgroundColor: "rgba(0,0,255,1.0)",
|
||||
borderColor: "rgba(0,0,255,0.1)",
|
||||
data: yValues,
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
tooltips: {
|
||||
callbacks: {
|
||||
title: function (tooltipItem) {
|
||||
return `Date: ${tooltipItem[0].label}`;
|
||||
},
|
||||
options: {
|
||||
tooltips: {
|
||||
callbacks: {
|
||||
title: function (tooltipItem) {
|
||||
return `Date: ${tooltipItem[0].label}`;
|
||||
},
|
||||
label: function (tooltipItem) {
|
||||
return `Temperature: ${tooltipItem.value}°C`;
|
||||
},
|
||||
},
|
||||
},
|
||||
label: function (tooltipItem) {
|
||||
return `Temperature: ${tooltipItem.value}°C`;
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function buildTable(data) {
|
||||
var table = document.getElementById(`TemperatureTable`);
|
||||
data.forEach((log) => {
|
||||
var averageTemp = (log.tempHigh + log.tempLow) / 2.0;
|
||||
var color;
|
||||
if (log.temperature > log.tempHigh) {
|
||||
color = "tempHigh";
|
||||
} else if (
|
||||
log.temperature < log.tempHigh &&
|
||||
log.temperature > averageTemp
|
||||
) {
|
||||
color = "tempMidHigh";
|
||||
} else if (log.temperature < log.tempLow) {
|
||||
color = "tempLow";
|
||||
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) {
|
||||
color = "tempMidLow";
|
||||
} else {
|
||||
color = "tempNormal";
|
||||
}
|
||||
var row = ` <tr>
|
||||
var table = document.getElementById(`TemperatureTable`);
|
||||
data.forEach((log) => {
|
||||
var averageTemp = (log.tempHigh + log.tempLow) / 2.0;
|
||||
var color;
|
||||
if (log.temperature > log.tempHigh) {
|
||||
color = "tempHigh";
|
||||
} else if (
|
||||
log.temperature < log.tempHigh &&
|
||||
log.temperature > averageTemp
|
||||
) {
|
||||
color = "tempMidHigh";
|
||||
} else if (log.temperature < log.tempLow) {
|
||||
color = "tempLow";
|
||||
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) {
|
||||
color = "tempMidLow";
|
||||
} else {
|
||||
color = "tempNormal";
|
||||
}
|
||||
var row = ` <tr>
|
||||
<td>Name</td>
|
||||
<td class="${color}">${log.temperature}</td>
|
||||
<td>${log.date}</td>
|
||||
<td class="tempHigh">${log.tempHigh}</td>
|
||||
<td class="tempLow">${log.tempLow}</td>
|
||||
</tr>`;
|
||||
table.innerHTML += row;
|
||||
});
|
||||
}
|
||||
|
||||
buildChart();
|
||||
table.innerHTML += row;
|
||||
});
|
||||
}
|
@ -10,18 +10,17 @@ document.getElementById("loginForm").addEventListener("submit", function(event)
|
||||
|
||||
login(emailOrUsername, password)
|
||||
.then(response => {
|
||||
document.cookie = `auth-token=${response.token}`;
|
||||
|
||||
localStorage.setItem("user", {
|
||||
id: response.id,
|
||||
username: response.userName,
|
||||
});
|
||||
if (response.error) {
|
||||
document.getElementById("form-error").innerText = response.error;
|
||||
document.getElementById("form-error").style.display = "block";
|
||||
return;
|
||||
}
|
||||
else{
|
||||
if (typeof(Storage) !== "undefined") {
|
||||
localStorage.setItem("id", response.id);
|
||||
}
|
||||
}
|
||||
|
||||
location.href = "/home";
|
||||
})
|
||||
.catch(error => {
|
||||
document.getElementById("form-error").innerText = error;
|
||||
document.getElementById("form-error").style.display = "block";
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -1,23 +1,32 @@
|
||||
import { profileData } from "../mockdata/profile.mockdata.js";
|
||||
import { get } from "./services/users.service.js";
|
||||
import { update } from "./services/users.service.js";
|
||||
import { updatePassword } from "./services/users.service.js";
|
||||
|
||||
var table = document.getElementById(`profileCard`);
|
||||
let id = localStorage.getItem("id");
|
||||
|
||||
get(id).then(res => {
|
||||
var table = document.getElementById(`profileCard`);
|
||||
table.innerHTML += `
|
||||
<div class="pfp">
|
||||
<img style="width:200px; height:200px" src="${profileData.pfp}">
|
||||
</div>
|
||||
<div class="userData">
|
||||
<h2>${profileData.username}</h2>
|
||||
<h2>${profileData.email}</h2>
|
||||
<h2>${res.userName}</h2>
|
||||
<h2>${res.email}</h2>
|
||||
</div>
|
||||
</div>`;
|
||||
})
|
||||
|
||||
|
||||
|
||||
var pswModal = document.getElementById("PasswordModal");
|
||||
var editModal = document.getElementById("editModal");
|
||||
var editBtn = document.getElementById("openEditModal");
|
||||
var editIconbtn = document.getElementById("openEditModal");
|
||||
var passwordBtn = document.getElementById("openPasswordModal");
|
||||
|
||||
// Open modals
|
||||
editBtn.onclick = () => (editModal.style.display = "block");
|
||||
editIconbtn.onclick = () => (editModal.style.display = "block");
|
||||
passwordBtn.onclick = () => (pswModal.style.display = "block");
|
||||
|
||||
// Close modals when clicking on any close button
|
||||
@ -25,6 +34,8 @@ document.querySelectorAll(".close").forEach(closeBtn => {
|
||||
closeBtn.onclick = () => {
|
||||
pswModal.style.display = "none";
|
||||
editModal.style.display = "none";
|
||||
document.getElementById("form-error").innerText = "";
|
||||
document.getElementById("form-error").style.display = "none";
|
||||
};
|
||||
});
|
||||
|
||||
@ -33,20 +44,22 @@ window.onclick = (event) => {
|
||||
if (event.target == pswModal || event.target == editModal) {
|
||||
pswModal.style.display = "none";
|
||||
editModal.style.display = "none";
|
||||
document.getElementById("form-error").innerText = "";
|
||||
document.getElementById("form-error").style.display = "none";
|
||||
}
|
||||
};
|
||||
|
||||
document.getElementById("editForm").addEventListener("submit", function(event) {
|
||||
event.preventDefault(); // Prevents default form submission
|
||||
|
||||
document.getElementById("form-error-edit").style.display = "none";
|
||||
document.getElementById("form-error").style.display = "none";
|
||||
|
||||
// Get form values
|
||||
const email = document.getElementById("email").value;
|
||||
const username = document.getElementById("uname").value;
|
||||
|
||||
// Call function with form values
|
||||
update(email, username)
|
||||
update(email, username, id)
|
||||
.then(response => {
|
||||
if (response?.error) {
|
||||
document.getElementById("form-error").innerText = response.error;
|
||||
@ -55,37 +68,33 @@ document.getElementById("editForm").addEventListener("submit", function(event) {
|
||||
return;
|
||||
}
|
||||
|
||||
location.href = "/login";
|
||||
location.href = "/profile";
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById("PasswordForm").addEventListener("submit", function(event) {
|
||||
event.preventDefault(); // Prevents default form submission
|
||||
|
||||
document.getElementById("form-error-password").style.display = "none";
|
||||
document.getElementById("form-error").style.display = "none";
|
||||
|
||||
// Get form values
|
||||
const oldPassword = document.getElementById("oldpsw").value;
|
||||
const newPassword = document.getElementById("psw").value;
|
||||
const repeatPassword = document.getElementById("rpsw").value;
|
||||
|
||||
if (newPassword !== repeatPassword) {
|
||||
let errorDiv = document.getElementById("form-error-password");
|
||||
let errorDiv = document.getElementById("form-error");
|
||||
errorDiv.style.display = "block";
|
||||
errorDiv.innerText = "Passwords do not match!";
|
||||
return;
|
||||
}
|
||||
|
||||
// Call function with form values
|
||||
update(email, username)
|
||||
updatePassword(oldPassword, newPassword, id)
|
||||
.then(response => {
|
||||
if (response?.error) {
|
||||
document.getElementById("form-error").innerText = response.error;
|
||||
//error messages do not work
|
||||
if (response.error) {
|
||||
document.getElementById("form-error").innerText = response.message;
|
||||
document.getElementById("form-error").style.display = "block";
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
location.href = "/login";
|
||||
});
|
||||
});
|
||||
|
@ -14,10 +14,13 @@ document.getElementById("registerForm").addEventListener("submit", function(even
|
||||
// Call function with form values
|
||||
create(email, username, password, repeatPassword)
|
||||
.then(response => {
|
||||
if (response?.error) {
|
||||
document.getElementById("form-error").innerText = response.error;
|
||||
document.getElementById("form-error").style.display = "block";
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
location.href = "/login";
|
||||
})
|
||||
.catch(error => {
|
||||
document.getElementById("form-error").innerText = error;
|
||||
document.getElementById("form-error").style.display = "block";
|
||||
});
|
||||
});
|
||||
|
@ -1,33 +1,7 @@
|
||||
import { address } from "../../shared/constants.js";
|
||||
|
||||
export function getDevicesOnUserId(id) {
|
||||
fetch(`${address}/get-on-user-id`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({ id: id })
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => console.log("Success:", data))
|
||||
.catch(error => console.error("Error:", error));
|
||||
}
|
||||
|
||||
export function update(ids) {
|
||||
fetch(`${address}/get-on-user-id`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({ ids: ids })
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => console.log("Success:", data))
|
||||
.catch(error => console.error("Error:", error));
|
||||
}
|
||||
|
||||
export function getLogsOnDeviceId(id) {
|
||||
fetch(`${address}/device/logs/${id}`, {
|
||||
export function getDevicesOnUserId(userId) {
|
||||
fetch(`${address}/device/${userId}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
@ -37,3 +11,55 @@ export function getLogsOnDeviceId(id) {
|
||||
.then(data => console.log("Success:", data))
|
||||
.catch(error => console.error("Error:", error));
|
||||
}
|
||||
|
||||
export function add(id) {
|
||||
fetch(`${address}/device`, {
|
||||
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) {
|
||||
fetch(`${address}/device/${id}`, {
|
||||
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) {
|
||||
console.log(referenceId)
|
||||
fetch(`${address}/device/${referenceId}`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => console.log("Success:", data))
|
||||
.catch(error => console.error("Error:", error));
|
||||
}
|
||||
|
||||
export function getLogsOnDeviceIds(id) {
|
||||
fetch(`${address}/get-on-device-ids`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({ ids: id })
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => console.log("Success:", data))
|
||||
.catch(error => console.error("Error:", error));
|
||||
}
|
@ -1,32 +1,66 @@
|
||||
import { request } from "../../shared/utils.js";
|
||||
import { address } from "../../shared/constants.js";
|
||||
import { handleResponse } from "../../shared/utils.js";
|
||||
|
||||
|
||||
export function get(userId) {
|
||||
return fetch(`${address}/user/${userId}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
})
|
||||
.then(handleResponse)
|
||||
.catch(err => { error: err.message });
|
||||
}
|
||||
|
||||
export function login(usernameOrEmail, password) {
|
||||
return request("POST", "/user/login", {
|
||||
EmailOrUsrn: usernameOrEmail,
|
||||
Password: password,
|
||||
});
|
||||
return fetch(`${address}/user/login`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
EmailOrUsrn: usernameOrEmail,
|
||||
Password: password,
|
||||
}),
|
||||
})
|
||||
.then(handleResponse)
|
||||
.catch(err => { error: err.message });
|
||||
}
|
||||
|
||||
export function create(email, username, password, repeatPassword){
|
||||
return request("POST", "/user/create", {
|
||||
email,
|
||||
username,
|
||||
password,
|
||||
repeatPassword,
|
||||
});
|
||||
return fetch(`${address}/user/create`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({email: email, username: username, password: password, repeatPassword: repeatPassword})
|
||||
})
|
||||
.then(handleResponse)
|
||||
.catch(err => { error: err.message });
|
||||
}
|
||||
|
||||
export function update(email, username){
|
||||
return request("PATCH", "/user/update", {
|
||||
email,
|
||||
username,
|
||||
});
|
||||
export function update(email, username, userId){
|
||||
return fetch(`${address}/user/edit/${userId}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({email: email, username: username})
|
||||
})
|
||||
.then(handleResponse)
|
||||
.catch(err => { error: err.message });
|
||||
}
|
||||
|
||||
export function updatePassword(oldPassword, newPassword){
|
||||
return request("PATCH", "/user/update-password", {
|
||||
oldPassword,
|
||||
newPassword,
|
||||
});
|
||||
export function updatePassword(oldPassword, newPassword, userId){
|
||||
return fetch(`${address}/user/change-password/${userId}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({oldPassword: oldPassword, newPassword: newPassword})
|
||||
})
|
||||
.then(handleResponse)
|
||||
.catch(err => { error: err.message });
|
||||
}
|
||||
|
||||
|
@ -1 +1 @@
|
||||
export const address = "hhttps://temperature.mercantec.tech/api"
|
||||
export const address = "http://127.0.0.1:5000/api"
|
||||
|
@ -1,31 +1,18 @@
|
||||
import { address } from "./constants.js";
|
||||
export async function handleResponse(response) {
|
||||
const json = await response.json();
|
||||
|
||||
export async function request(method, path, body = null) {
|
||||
const token = document.cookie.match(/\bauth-token=([^;\s]+)/);
|
||||
if (response.ok || json.error) return json;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
fetch(address + path, {
|
||||
method,
|
||||
headers: {
|
||||
"Content-Type": body ? "application/json" : undefined,
|
||||
"Authorization": token?.length > 1 ? `Bearer ${token[1]}` : undefined,
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
})
|
||||
.then(async response => {
|
||||
const json = await response.json();
|
||||
if (json.errors) {
|
||||
return { error: Object.values(response.errors)[0][0] };
|
||||
}
|
||||
|
||||
if (response.ok) return resolve(json);
|
||||
|
||||
if (json.error) return reject(json.error);
|
||||
|
||||
if (json.message) return reject(json.message);
|
||||
|
||||
if (json.errors) return reject(Object.values(response.errors)[0][0]);
|
||||
|
||||
reject("Request failed with HTTP code " + response.status);
|
||||
})
|
||||
.catch(err => reject(err.message));
|
||||
});
|
||||
return { error: "Request failed with HTTP code " + response.status };
|
||||
}
|
||||
|
||||
document.querySelectorAll(".logoutContainer").forEach(closeBtn => {
|
||||
closeBtn.onclick = () => {
|
||||
localStorage.clear();
|
||||
window.location.href = "/index.html";
|
||||
};
|
||||
});
|
||||
|
@ -1,5 +1,32 @@
|
||||
body {
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.topnav {
|
||||
overflow: hidden;
|
||||
background-color: #333;
|
||||
}
|
||||
|
||||
.topnav a {
|
||||
height: 20px;
|
||||
float: left;
|
||||
color: #f2f2f2;
|
||||
text-align: center;
|
||||
padding: 14px 16px;
|
||||
text-decoration: none;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.topnav a:hover, .topnav span:hover {
|
||||
background-color: #ddd;
|
||||
color: black;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.topnav a.active {
|
||||
background-color: #04aa6d;
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Full-width input fields */
|
||||
@ -15,12 +42,12 @@ input[type=text], input[type=password], input[type=email] {
|
||||
/* Set a style for all buttons */
|
||||
button {
|
||||
background-color: #04AA6D;
|
||||
color: white;
|
||||
padding: 14px 20px;
|
||||
margin: 8px 0;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
@ -35,7 +62,7 @@ button:hover {
|
||||
|
||||
.details {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
justify-content: flex-end;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
@ -49,6 +76,15 @@ button:hover {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
button{
|
||||
border-radius: 20px;
|
||||
.logoutContainer{
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 50px;
|
||||
}
|
||||
|
||||
.logout{
|
||||
width: 20px;
|
||||
height: 24px;
|
||||
}
|
||||
|
||||
|
150
frontend/styles/devices.css
Normal file
150
frontend/styles/devices.css
Normal file
@ -0,0 +1,150 @@
|
||||
table {
|
||||
margin: 20px;
|
||||
font-family: arial, sans-serif;
|
||||
border-collapse: collapse;
|
||||
width: 95%;
|
||||
}
|
||||
|
||||
td,
|
||||
th {
|
||||
border: 1px solid #dddddd;
|
||||
text-align: left;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
tr:nth-child(even) {
|
||||
background-color: #dddddd;
|
||||
}
|
||||
|
||||
.addDeviceContainer{
|
||||
margin-top: 20px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
#addDevice{
|
||||
width: 120px;
|
||||
margin: 0 20px 0 0;
|
||||
}
|
||||
|
||||
.tableConatiner{
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.tableIcons{
|
||||
margin-inline: 5px;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
}
|
||||
|
||||
.tableIcons:hover {
|
||||
background-color: #ddd;
|
||||
color: black;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
|
||||
button {
|
||||
background-color: #04AA6D;
|
||||
color: white;
|
||||
padding: 14px 20px;
|
||||
margin: 8px 0;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
opacity:1;
|
||||
}
|
||||
|
||||
/* Float cancel and delete buttons and add an equal width */
|
||||
.cancelbtn, #addbtn, #deletebtn, #editbtn{
|
||||
float: left;
|
||||
width: 50%;
|
||||
}
|
||||
|
||||
/* Add a color to the cancel button */
|
||||
.cancelbtn {
|
||||
background-color: #ccc;
|
||||
color: black;
|
||||
}
|
||||
|
||||
/* Add a color to the delete button */
|
||||
#deletebtn {
|
||||
background-color: #f44336;
|
||||
}
|
||||
|
||||
/* Add padding and center-align text to the container */
|
||||
.container {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
/* The Modal (background) */
|
||||
.modal {
|
||||
display: none; /* Hidden by default */
|
||||
position: fixed; /* Stay in place */
|
||||
z-index: 1; /* Sit on top */
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%; /* Full width */
|
||||
height: 100%; /* Full height */
|
||||
overflow: auto; /* Enable scroll if needed */
|
||||
background-color: #474e5d;
|
||||
padding-top: 50px;
|
||||
}
|
||||
|
||||
/* Modal Content/Box */
|
||||
.modal-content {
|
||||
background-color: #fefefe;
|
||||
margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
|
||||
border: 1px solid #888;
|
||||
width: 80%; /* Could be more or less, depending on screen size */
|
||||
}
|
||||
|
||||
/* Style the horizontal ruler */
|
||||
hr {
|
||||
border: 1px solid #f1f1f1;
|
||||
margin-bottom: 25px;
|
||||
}
|
||||
|
||||
/* The Modal Close Button (x) */
|
||||
#close {
|
||||
position: absolute;
|
||||
right: 35px;
|
||||
top: 15px;
|
||||
font-size: 40px;
|
||||
font-weight: bold;
|
||||
color: #f1f1f1;
|
||||
}
|
||||
|
||||
#close:hover,
|
||||
#close:focus {
|
||||
color: #f44336;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Clear floats */
|
||||
.clearfix::after {
|
||||
content: "";
|
||||
clear: both;
|
||||
display: table;
|
||||
}
|
||||
|
||||
/* Change styles for cancel button and delete button on extra small screens */
|
||||
@media screen and (max-width: 300px) {
|
||||
.cancelbtn, .deletebtn {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.form-container{
|
||||
width: 90%;
|
||||
}
|
||||
|
||||
.deviceHeader{
|
||||
display: flex;
|
||||
text-align: center;
|
||||
}
|
@ -4,7 +4,6 @@
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
|
||||
|
@ -1,5 +1,4 @@
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
@ -8,34 +7,11 @@ body {
|
||||
opacity: 100%;
|
||||
}
|
||||
|
||||
.topnav {
|
||||
overflow: hidden;
|
||||
background-color: #333;
|
||||
}
|
||||
|
||||
.topnav a {
|
||||
float: left;
|
||||
color: #f2f2f2;
|
||||
text-align: center;
|
||||
padding: 14px 16px;
|
||||
text-decoration: none;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.topnav a:hover {
|
||||
background-color: #ddd;
|
||||
color: black;
|
||||
}
|
||||
|
||||
.topnav a.active {
|
||||
background-color: #04aa6d;
|
||||
color: white;
|
||||
}
|
||||
|
||||
table {
|
||||
margin: 20px;
|
||||
font-family: arial, sans-serif;
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
width: 95%;
|
||||
}
|
||||
|
||||
td,
|
||||
@ -77,3 +53,8 @@ tr:nth-child(even) {
|
||||
.chartContainer{
|
||||
margin: 20px;
|
||||
}
|
||||
|
||||
.tableConatiner{
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
@ -49,8 +49,23 @@ h2{
|
||||
padding: 20px;
|
||||
border: 1px solid #888;
|
||||
width: 80%;
|
||||
-webkit-animation-name: animatetop;
|
||||
-webkit-animation-duration: 0.4s;
|
||||
animation-name: animatetop;
|
||||
animation-duration: 0.4s
|
||||
}
|
||||
|
||||
|
||||
/* Add Animation */
|
||||
@-webkit-keyframes animatetop {
|
||||
from {top:-300px; opacity:0}
|
||||
to {top:0; opacity:1}
|
||||
}
|
||||
|
||||
@keyframes animatetop {
|
||||
from {top:-300px; opacity:0}
|
||||
to {top:0; opacity:1}
|
||||
}
|
||||
|
||||
/* The Close Button */
|
||||
.close {
|
||||
color: #aaaaaa;
|
||||
|
@ -1,5 +1,3 @@
|
||||
FILES=main.c brokers/mqtt.c brokers/amqp.c devices/temperature.c devices/display.c device_id.c
|
||||
|
||||
all: $(FILES)
|
||||
$(CC) -lmosquitto -lrabbitmq -lpthread -li2c $(FILES)
|
||||
all: main.c mqtt.c temperature.c device_id.c
|
||||
$(CC) -lmosquitto -lpthread -li2c main.c mqtt.c temperature.c device_id.c
|
||||
|
||||
|
@ -1,35 +0,0 @@
|
||||
#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 (;;);
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
void init_amqp(void);
|
||||
|
||||
void amqp_send_message(char *topic, char *message);
|
||||
|
@ -3,7 +3,3 @@
|
||||
#define MQTT_USER "user"
|
||||
#define MQTT_PASSWORD "password"
|
||||
|
||||
#define AMQP_IP "127.0.0.1"
|
||||
#define AMQP_PORT 5672
|
||||
#define AMQP_USER "user"
|
||||
#define AMQP_PASSWORD "password"
|
||||
|
@ -1,60 +0,0 @@
|
||||
#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;
|
||||
}
|
||||
|
@ -1,10 +0,0 @@
|
||||
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);
|
||||
|
29
iot/main.c
29
iot/main.c
@ -6,9 +6,8 @@
|
||||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "brokers/amqp.h"
|
||||
#include "devices/temperature.h"
|
||||
#include "devices/display.h"
|
||||
#include "mqtt.h"
|
||||
#include "temperature.h"
|
||||
#include "device_id.h"
|
||||
|
||||
void *watch_temperature(void *arg)
|
||||
@ -17,21 +16,14 @@ void *watch_temperature(void *arg)
|
||||
|
||||
printf("Device ID: %s\n", device_id);
|
||||
|
||||
display_handle_t display = init_display();
|
||||
display_write_str(display, " ");
|
||||
display_set_cursor_pos(display, 0, 1);
|
||||
display_write_str(display, "Device.....");
|
||||
display_write_str(display, device_id);
|
||||
|
||||
temperature_handle_t temp_handle = init_temperature();
|
||||
|
||||
get_temperature(temp_handle);
|
||||
|
||||
while (true) {
|
||||
// Retrieve data
|
||||
double temperature = get_temperature(temp_handle);
|
||||
size_t timestamp = time(NULL);
|
||||
|
||||
// Send JSON
|
||||
char *format = "{"
|
||||
"\"temperature\": %lf,"
|
||||
"\"device_id\": \"%s\","
|
||||
@ -41,16 +33,7 @@ void *watch_temperature(void *arg)
|
||||
char *str = malloc(snprintf(NULL, 0, format, temperature, device_id, timestamp) + 1);
|
||||
sprintf(str, format, temperature, device_id, timestamp);
|
||||
|
||||
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);
|
||||
mqtt_send_message("temperature", str);
|
||||
|
||||
free(str);
|
||||
|
||||
@ -64,7 +47,7 @@ void *watch_temperature(void *arg)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void broker_on_connect(void)
|
||||
void mqtt_on_connect(void)
|
||||
{
|
||||
pthread_t temperature_thread;
|
||||
pthread_create(&temperature_thread, NULL, watch_temperature, NULL);
|
||||
@ -74,7 +57,7 @@ int main(void)
|
||||
{
|
||||
srand(time(NULL));
|
||||
|
||||
init_amqp();
|
||||
init_mqtt();
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
@ -3,11 +3,11 @@
|
||||
#include <string.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#include "../config.h"
|
||||
#include "config.h"
|
||||
|
||||
struct mosquitto *mosq;
|
||||
|
||||
void broker_on_connect(void);
|
||||
void mqtt_on_connect(void);
|
||||
|
||||
void on_connect(struct mosquitto *client, void *obj, int rc)
|
||||
{
|
||||
@ -18,7 +18,7 @@ void on_connect(struct mosquitto *client, void *obj, int rc)
|
||||
|
||||
puts("Connected to " MQTT_IP);
|
||||
|
||||
broker_on_connect();
|
||||
mqtt_on_connect();
|
||||
}
|
||||
|
||||
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
|
@ -11,10 +11,8 @@
|
||||
|
||||
#include "temperature.h"
|
||||
|
||||
#define MCP9808_BUS "/dev/i2c-2"
|
||||
#define MCP9808_ADR 0x18
|
||||
#define MCP9808_MANID 0x0054
|
||||
#define MCP9808_DEVID 0x04
|
||||
#define MPC9808_BUS "/dev/i2c-2"
|
||||
#define MPC9808_ADR 0x18
|
||||
|
||||
#define CONFIG_REG 0x01
|
||||
#define TUPPER_REG 0x02
|
||||
@ -55,16 +53,16 @@ double get_temperature(temperature_handle_t file)
|
||||
|
||||
temperature_handle_t init_temperature(void)
|
||||
{
|
||||
int file = open(MCP9808_BUS, O_RDWR);
|
||||
int file = open(MPC9808_BUS, O_RDWR);
|
||||
|
||||
if (file < 0) {
|
||||
perror("Error opening temperature sensor device");
|
||||
exit(EXIT_FAILURE);
|
||||
fprintf(stderr, "Error opening temperature sensor device (%s): %s\n", MPC9808_BUS, strerror(errno));
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (ioctl(file, I2C_SLAVE, MCP9808_ADR) == -1) {
|
||||
fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", MCP9808_ADR, MCP9808_BUS, strerror(errno));
|
||||
exit(EXIT_FAILURE);
|
||||
if (ioctl(file, I2C_SLAVE, MPC9808_ADR) == -1) {
|
||||
fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", MPC9808_ADR, MPC9808_BUS, strerror(errno));
|
||||
exit(1);
|
||||
}
|
||||
|
||||
int32_t reg32;
|
||||
@ -75,23 +73,23 @@ temperature_handle_t init_temperature(void)
|
||||
reg32 = i2c_smbus_read_word_data(file, MANID_REG);
|
||||
|
||||
if (reg32 < 0) {
|
||||
fprintf(stderr, "Read failed on i2c bus register %d: %s\n", MANID_REG, strerror(errno));
|
||||
exit(EXIT_FAILURE);
|
||||
fprintf(stderr, "ERROR: Read failed on i2c bus register %d - %s\n", MANID_REG,strerror(errno));
|
||||
exit(1);
|
||||
}
|
||||
if (bswap_16(reg16poi[0]) != MCP9808_MANID) {
|
||||
fprintf(stderr, "Invalid manufacturer ID: Expected 0x%x, got 0x%x\n", MCP9808_MANID, __bswap_16(reg16poi[0]));
|
||||
exit(EXIT_FAILURE);
|
||||
if (bswap_16(reg16poi[0]) != 0x0054) {
|
||||
fprintf(stderr, "Manufactorer ID wrong is 0x%x should be 0x54\n",__bswap_16(reg16poi[0]));
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// Read device ID and revision
|
||||
reg32 = i2c_smbus_read_word_data(file, DEVID_REG);
|
||||
if (reg32 < 0) {
|
||||
fprintf(stderr, "Read failed on i2c bus register %d - %s\n", DEVID_REG, strerror(errno));
|
||||
exit(EXIT_FAILURE);
|
||||
fprintf(stderr, "ERROR: Read failed on i2c bus register %d - %s\n", DEVID_REG,strerror(errno) );
|
||||
exit(1);
|
||||
}
|
||||
if (reg8poi[0] != MCP9808_DEVID) {
|
||||
fprintf(stderr, "Invalid device ID - expected 0x%x, got 0x%x\n", MCP9808_DEVID, reg8poi[0]);
|
||||
exit(EXIT_FAILURE);
|
||||
if (reg8poi[0] != 0x04) {
|
||||
fprintf(stderr, "Manufactorer ID OK but device ID wrong is 0x%x should be 0x4\n",reg8poi[0]);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
return file;
|
Loading…
Reference in New Issue
Block a user