Compare commits
31 Commits
profileand
...
master
Author | SHA1 | Date | |
---|---|---|---|
|
c9155d582b | ||
|
db023ac84e | ||
|
1ca64702d7 | ||
|
6cb36947cb | ||
fb3705690d | |||
e2dd9d9e6e | |||
|
668b29c068 | ||
|
d9205d425c | ||
fe85e1ff23 | |||
|
7a3d5b4f71 | ||
|
9dc19efd83 | ||
6fe0841cbc | |||
df130b312c | |||
dd2a3cf150 | |||
|
f6e2c8f450 | ||
b8bb86edca | |||
|
595ade2d79 | ||
02bfbabcfc | |||
0f1b10d2d7 | |||
|
8ad863b781 | ||
|
46de83dc42 | ||
|
edc195b234 | ||
|
bce48fe8d1 | ||
|
998cb90acc | ||
|
47797d18a0 | ||
|
6f311fabd4 | ||
2f5f753ab6 | |||
|
60c0fc9475 | ||
|
507e156f17 | ||
90cbf7ae81 | |||
8c6037b010 |
109
backend/Api/AMQP/AMQPPublisher.cs
Normal file
109
backend/Api/AMQP/AMQPPublisher.cs
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
using Api.DBAccess;
|
||||||
|
using Api.Models;
|
||||||
|
using RabbitMQ.Client;
|
||||||
|
using RabbitMQ.Client.Events;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace Api.AMQP
|
||||||
|
{
|
||||||
|
public class AMQPPublisher
|
||||||
|
{
|
||||||
|
private readonly IConfiguration _configuration;
|
||||||
|
private readonly DbAccess _dbAccess;
|
||||||
|
private IConnection _conn;
|
||||||
|
private IChannel _channel;
|
||||||
|
private ConnectionFactory _factory;
|
||||||
|
private string _queue;
|
||||||
|
|
||||||
|
public AMQPPublisher(IConfiguration configuration, DbAccess dbAccess)
|
||||||
|
{
|
||||||
|
_dbAccess = dbAccess;
|
||||||
|
_configuration = configuration;
|
||||||
|
_factory = new ConnectionFactory();
|
||||||
|
_queue = "temperature-limits";
|
||||||
|
|
||||||
|
InitFactory();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Handle_Push_Device_Limits()
|
||||||
|
{
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
await Connect();
|
||||||
|
|
||||||
|
// Publishes all devices limits
|
||||||
|
var devices = _dbAccess.ReadDevices();
|
||||||
|
foreach (var device in devices)
|
||||||
|
{
|
||||||
|
var deviceLimit = new DeviceLimit();
|
||||||
|
deviceLimit.ReferenceId = device.ReferenceId;
|
||||||
|
deviceLimit.TempHigh = device.TempHigh;
|
||||||
|
deviceLimit.TempLow = device.TempLow;
|
||||||
|
string message = JsonSerializer.Serialize(deviceLimit);
|
||||||
|
var body = Encoding.UTF8.GetBytes(message);
|
||||||
|
await _channel.BasicPublishAsync(exchange: string.Empty, routingKey: _queue, body: body);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Short delay before disconnecting from rabbitMQ
|
||||||
|
await Task.Delay(1000);
|
||||||
|
|
||||||
|
// Disconnecting from rabbitMQ to save resources
|
||||||
|
await Dispose();
|
||||||
|
// 1 hour delay
|
||||||
|
await Task.Delay(3600000);
|
||||||
|
|
||||||
|
await Connect();
|
||||||
|
|
||||||
|
// Here all messages is consumed so the queue is empty
|
||||||
|
var consumer = new AsyncEventingBasicConsumer(_channel);
|
||||||
|
consumer.ReceivedAsync += (model, ea) =>
|
||||||
|
{
|
||||||
|
Console.WriteLine("Emptying queue");
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Consumes the data in the queue
|
||||||
|
await _channel.BasicConsumeAsync(_queue, true, consumer);
|
||||||
|
|
||||||
|
// Short delay before disconnecting from rabbitMQ
|
||||||
|
await Task.Delay(1000);
|
||||||
|
await Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disconnects from rabbitMQ
|
||||||
|
private async Task<bool> Dispose()
|
||||||
|
{
|
||||||
|
await _channel.CloseAsync();
|
||||||
|
await _conn.CloseAsync();
|
||||||
|
await _channel.DisposeAsync();
|
||||||
|
await _conn.DisposeAsync();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connects to rabbitMQ
|
||||||
|
private async Task<bool> Connect()
|
||||||
|
{
|
||||||
|
// Creating a new connection to rabbitMQ
|
||||||
|
_conn = await _factory.CreateConnectionAsync();
|
||||||
|
Console.WriteLine("AMQPClient connected");
|
||||||
|
_channel = await _conn.CreateChannelAsync();
|
||||||
|
|
||||||
|
// Here we connect to the queue through the channel that got created earlier
|
||||||
|
await _channel.QueueDeclareAsync(queue: _queue, durable: false, exclusive: false, autoDelete: false);
|
||||||
|
Console.WriteLine($"{_queue} connected");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The info for the factory
|
||||||
|
private void InitFactory()
|
||||||
|
{
|
||||||
|
_factory.UserName = _configuration["AMQP:username"];
|
||||||
|
_factory.Password = _configuration["AMQP:password"];
|
||||||
|
_factory.HostName = _configuration["AMQP:host"];
|
||||||
|
_factory.Port = Convert.ToInt32(_configuration["AMQP:port"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
97
backend/Api/AMQP/AMQPReciever.cs
Normal file
97
backend/Api/AMQP/AMQPReciever.cs
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
using Api.DBAccess;
|
||||||
|
using Api.Models;
|
||||||
|
using RabbitMQ.Client;
|
||||||
|
using RabbitMQ.Client.Events;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace Api.AMQPReciever
|
||||||
|
{
|
||||||
|
public class AMQPReciever
|
||||||
|
{
|
||||||
|
private readonly IConfiguration _configuration;
|
||||||
|
private readonly DbAccess _dbAccess;
|
||||||
|
private IConnection _conn;
|
||||||
|
private IChannel _channel;
|
||||||
|
private ConnectionFactory _factory;
|
||||||
|
private string _queue;
|
||||||
|
|
||||||
|
public AMQPReciever(IConfiguration configuration, DbAccess dbAccess)
|
||||||
|
{
|
||||||
|
_dbAccess = dbAccess;
|
||||||
|
_configuration = configuration;
|
||||||
|
_factory = new ConnectionFactory();
|
||||||
|
_queue = "temperature-logs";
|
||||||
|
|
||||||
|
InitFactory();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Handle_Received_Application_Message()
|
||||||
|
{
|
||||||
|
await Connect();
|
||||||
|
|
||||||
|
// Everytime a message is recieved from the queue it goes into this consumer.ReceivedAsync
|
||||||
|
var consumer = new AsyncEventingBasicConsumer(_channel);
|
||||||
|
consumer.ReceivedAsync += (model, ea) =>
|
||||||
|
{
|
||||||
|
Console.WriteLine("Received application message.");
|
||||||
|
var body = ea.Body.ToArray();
|
||||||
|
var message = Encoding.UTF8.GetString(body);
|
||||||
|
|
||||||
|
var messageReceive = JsonSerializer.Deserialize<MessageReceive>(message);
|
||||||
|
|
||||||
|
// Checks if the message has the data we need
|
||||||
|
if (messageReceive == null || messageReceive.device_id == null || messageReceive.timestamp == 0)
|
||||||
|
{
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to the model we use in the database and gets the device from the database that is used for getting the current set temphigh and templow
|
||||||
|
TemperatureLogs newLog = new TemperatureLogs();
|
||||||
|
string refernceId = messageReceive.device_id;
|
||||||
|
var device = _dbAccess.ReadDevice(refernceId);
|
||||||
|
|
||||||
|
// Checks if the device exist if it doesn't it throws the data away
|
||||||
|
if (device == null) { return Task.CompletedTask; }
|
||||||
|
|
||||||
|
newLog.Temperature = messageReceive.temperature;
|
||||||
|
newLog.Date = DateTimeOffset.FromUnixTimeSeconds(messageReceive.timestamp).DateTime;
|
||||||
|
newLog.TempHigh = device.TempHigh;
|
||||||
|
newLog.TempLow = device.TempLow;
|
||||||
|
|
||||||
|
// Send the data to dbaccess to be saved
|
||||||
|
_dbAccess.CreateLog(newLog, refernceId);
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Consumes the data in the queue
|
||||||
|
await _channel.BasicConsumeAsync(_queue, true, consumer);
|
||||||
|
|
||||||
|
while (true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connects to rabbitMQ
|
||||||
|
private async Task<bool> Connect()
|
||||||
|
{
|
||||||
|
// Creating a new connection to rabbitMQ
|
||||||
|
_conn = await _factory.CreateConnectionAsync();
|
||||||
|
Console.WriteLine("AMQPClient connected");
|
||||||
|
_channel = await _conn.CreateChannelAsync();
|
||||||
|
|
||||||
|
// Here we connect to the queue through the channel that got created earlier
|
||||||
|
await _channel.QueueDeclareAsync(queue: _queue, durable: false, exclusive: false, autoDelete: false);
|
||||||
|
Console.WriteLine($"{_queue} connected");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The info for the factory
|
||||||
|
private void InitFactory()
|
||||||
|
{
|
||||||
|
_factory.UserName = _configuration["AMQP:username"];
|
||||||
|
_factory.Password = _configuration["AMQP:password"];
|
||||||
|
_factory.HostName = _configuration["AMQP:host"];
|
||||||
|
_factory.Port = Convert.ToInt32(_configuration["AMQP:port"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,74 +0,0 @@
|
|||||||
using Api.DBAccess;
|
|
||||||
using Api.Models;
|
|
||||||
using RabbitMQ.Client;
|
|
||||||
using RabbitMQ.Client.Events;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.Json;
|
|
||||||
|
|
||||||
namespace Api.AMQPReciever
|
|
||||||
{
|
|
||||||
public class AMQPReciever
|
|
||||||
{
|
|
||||||
private readonly IConfiguration _configuration;
|
|
||||||
private readonly DbAccess _dbAccess;
|
|
||||||
|
|
||||||
public AMQPReciever(IConfiguration configuration, DbAccess dbAccess)
|
|
||||||
{
|
|
||||||
_dbAccess = dbAccess;
|
|
||||||
_configuration = configuration;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Handle_Received_Application_Message()
|
|
||||||
{
|
|
||||||
var factory = new ConnectionFactory();
|
|
||||||
var queue = "temperature-logs";
|
|
||||||
|
|
||||||
factory.UserName = _configuration["AMQP:username"];
|
|
||||||
factory.Password = _configuration["AMQP:password"];
|
|
||||||
factory.HostName = _configuration["AMQP:host"];
|
|
||||||
factory.Port = Convert.ToInt32(_configuration["AMQP:port"]);
|
|
||||||
|
|
||||||
using var conn = await factory.CreateConnectionAsync();
|
|
||||||
Console.WriteLine("AMQPClien connected");
|
|
||||||
using var channel = await conn.CreateChannelAsync();
|
|
||||||
|
|
||||||
await channel.QueueDeclareAsync(queue: queue, durable: false, exclusive: false, autoDelete: false);
|
|
||||||
Console.WriteLine($"{queue} connected");
|
|
||||||
|
|
||||||
var consumer = new AsyncEventingBasicConsumer(channel);
|
|
||||||
consumer.ReceivedAsync += (model, ea) =>
|
|
||||||
{
|
|
||||||
Console.WriteLine("Received application message.");
|
|
||||||
var body = ea.Body.ToArray();
|
|
||||||
var message = Encoding.UTF8.GetString(body);
|
|
||||||
|
|
||||||
var messageReceive = JsonSerializer.Deserialize<MQTTMessageReceive>(message);
|
|
||||||
|
|
||||||
if (messageReceive == null || messageReceive.temperature == 0 || messageReceive.device_id == null || messageReceive.timestamp == 0)
|
|
||||||
{
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
TemperatureLogs newLog = new TemperatureLogs();
|
|
||||||
string refernceId = messageReceive.device_id;
|
|
||||||
var device = _dbAccess.ReadDevice(refernceId);
|
|
||||||
|
|
||||||
if (device == null) { return Task.CompletedTask; }
|
|
||||||
|
|
||||||
newLog.Temperature = messageReceive.temperature;
|
|
||||||
newLog.Date = DateTimeOffset.FromUnixTimeSeconds(messageReceive.timestamp).DateTime;
|
|
||||||
newLog.TempHigh = device.TempHigh;
|
|
||||||
newLog.TempLow = device.TempLow;
|
|
||||||
|
|
||||||
_dbAccess.CreateLog(newLog, refernceId);
|
|
||||||
|
|
||||||
return Task.CompletedTask;
|
|
||||||
};
|
|
||||||
|
|
||||||
await channel.BasicConsumeAsync(queue, true, consumer);
|
|
||||||
|
|
||||||
Console.WriteLine("Press enter to exit.");
|
|
||||||
Console.ReadLine();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,7 +1,6 @@
|
|||||||
using Api.DBAccess;
|
using Api.DBAccess;
|
||||||
using Api.Models;
|
using Api.Models;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
|
||||||
|
|
||||||
namespace Api.BusinessLogic
|
namespace Api.BusinessLogic
|
||||||
{
|
{
|
||||||
@ -16,6 +15,12 @@ namespace Api.BusinessLogic
|
|||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the user from dbaccess using the userId and checks if the user exists
|
||||||
|
/// Gets all devices that match the userId and checks if there are any devices connected to the user
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId">UserId that matches a user that owns the devices</param>
|
||||||
|
/// <returns>returns the devices in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
public async Task<IActionResult> GetDevices(int userId)
|
public async Task<IActionResult> GetDevices(int userId)
|
||||||
{
|
{
|
||||||
var profile = await _dbAccess.ReadUser(userId);
|
var profile = await _dbAccess.ReadUser(userId);
|
||||||
@ -29,25 +34,31 @@ namespace Api.BusinessLogic
|
|||||||
return new OkObjectResult(devices);
|
return new OkObjectResult(devices);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IActionResult> AddDevice(string referenceId, int userId)
|
/// <summary>
|
||||||
|
/// Checks if the user that the device is trying to be added to exists
|
||||||
|
/// Then it is send to dbaccess
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="device">The new device</param>
|
||||||
|
/// <param name="userId">The user that owns the device</param>
|
||||||
|
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
|
public async Task<IActionResult> AddDevice(Device device, int userId)
|
||||||
{
|
{
|
||||||
var profile = await _dbAccess.ReadUser(userId);
|
var profile = await _dbAccess.ReadUser(userId);
|
||||||
|
|
||||||
if (profile == null) { return new ConflictObjectResult(new { message = "Could not find user" }); }
|
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);
|
return await _dbAccess.CreateDevice(device, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IActionResult> GetLogs(int deviceId)
|
/// <summary>
|
||||||
|
/// Checks if the device exist that is trying to be read from
|
||||||
|
/// Gets the logs and checks if there are any in the list
|
||||||
|
/// Checks if the datetimeRange have 2 values that are the same bc that means they want all logs
|
||||||
|
/// Then it makes a new list with all data that are in the range of the 2 datetimes
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="deviceId">The deviceId that you want from the logs</param>
|
||||||
|
/// <returns>returns the logs in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
|
public async Task<IActionResult> GetLogs(DateTimeRange dateTimeRange, int deviceId)
|
||||||
{
|
{
|
||||||
var device = await _dbAccess.ReadDevice(deviceId);
|
var device = await _dbAccess.ReadDevice(deviceId);
|
||||||
|
|
||||||
@ -57,9 +68,23 @@ namespace Api.BusinessLogic
|
|||||||
|
|
||||||
if (logs.Count == 0) { return new ConflictObjectResult(new { message = "Could not find any logs connected to the device" }); }
|
if (logs.Count == 0) { return new ConflictObjectResult(new { message = "Could not find any logs connected to the device" }); }
|
||||||
|
|
||||||
return new OkObjectResult(logs);
|
if (dateTimeRange.DateTimeStart == dateTimeRange.DateTimeEnd) { return new OkObjectResult(logs); }
|
||||||
|
|
||||||
|
List<TemperatureLogs> rangedLogs = new List<TemperatureLogs>();
|
||||||
|
foreach (var log in logs)
|
||||||
|
{
|
||||||
|
if (log.Date <= dateTimeRange.DateTimeStart && log.Date >= dateTimeRange.DateTimeEnd) { rangedLogs.Add(log); }
|
||||||
|
}
|
||||||
|
|
||||||
|
return new OkObjectResult(rangedLogs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks if the deviceId matches a device
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="device">The updated info</param>
|
||||||
|
/// <param name="deviceId">The device to be edited</param>
|
||||||
|
/// <returns>returns the updated device in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
public async Task<IActionResult> EditDevice(Device device, int deviceId)
|
public async Task<IActionResult> EditDevice(Device device, int deviceId)
|
||||||
{
|
{
|
||||||
var device1 = _dbAccess.ReadDevice(deviceId);
|
var device1 = _dbAccess.ReadDevice(deviceId);
|
||||||
|
@ -31,6 +31,14 @@ namespace Api.BusinessLogic
|
|||||||
return new OkObjectResult(new { user.Id, user.UserName, user.Email });
|
return new OkObjectResult(new { user.Id, user.UserName, user.Email });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// First checks if the mail is a valid one with regex so if there is something before the @ and after and it has a domain
|
||||||
|
/// Then it checks if the password is to our security standard
|
||||||
|
/// Then it makes sure the user has a device list
|
||||||
|
/// The last thing before it saves the user is creating a salt and then hashing of the password
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="user">The new user</param>
|
||||||
|
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
public async Task<IActionResult> RegisterUser(User user)
|
public async Task<IActionResult> RegisterUser(User user)
|
||||||
{
|
{
|
||||||
if (!new Regex(@".+@.+\..+").IsMatch(user.Email))
|
if (!new Regex(@".+@.+\..+").IsMatch(user.Email))
|
||||||
@ -50,12 +58,20 @@ namespace Api.BusinessLogic
|
|||||||
|
|
||||||
string salt = Guid.NewGuid().ToString();
|
string salt = Guid.NewGuid().ToString();
|
||||||
string hashedPassword = ComputeHash(user.Password, SHA256.Create(), salt);
|
string hashedPassword = ComputeHash(user.Password, SHA256.Create(), salt);
|
||||||
|
|
||||||
user.Salt = salt;
|
user.Salt = salt;
|
||||||
user.Password = hashedPassword;
|
user.Password = hashedPassword;
|
||||||
|
|
||||||
return await _dbAccess.CreateUser(user);
|
return await _dbAccess.CreateUser(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the user that matches the login
|
||||||
|
/// Hashes the login password with the users salt
|
||||||
|
/// checks if the hashed password that the login has is the same as the one saved in the database
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="login">Has a username or email and a password</param>
|
||||||
|
/// <returns>Returns a jwt token, username and userid</returns>
|
||||||
public async Task<IActionResult> Login(Login login)
|
public async Task<IActionResult> Login(Login login)
|
||||||
{
|
{
|
||||||
User user = await _dbAccess.Login(login);
|
User user = await _dbAccess.Login(login);
|
||||||
@ -67,15 +83,26 @@ namespace Api.BusinessLogic
|
|||||||
if (user.Password == hashedPassword)
|
if (user.Password == hashedPassword)
|
||||||
{
|
{
|
||||||
var token = GenerateJwtToken(user);
|
var token = GenerateJwtToken(user);
|
||||||
return new OkObjectResult(new { token, user.Id});
|
user.RefreshToken = Guid.NewGuid().ToString();
|
||||||
|
_dbAccess.UpdatesRefreshToken(user.RefreshToken, user.Id);
|
||||||
|
return new OkObjectResult(new { token, user.UserName, user.Id, refreshToken = user.RefreshToken });
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ConflictObjectResult(new { message = "Invalid password" });
|
return new ConflictObjectResult(new { message = "Invalid password" });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IActionResult> EditProfile(EditUserRequest userRequest, int userId)
|
/// <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)
|
||||||
{
|
{
|
||||||
return await _dbAccess.UpdateUser(userRequest, userId);
|
return await _dbAccess.UpdateUser(user, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IActionResult> changePassword(ChangePasswordRequest passwordRequest, int userId)
|
public async Task<IActionResult> changePassword(ChangePasswordRequest passwordRequest, int userId)
|
||||||
@ -100,11 +127,30 @@ namespace Api.BusinessLogic
|
|||||||
return await _dbAccess.updatePassword(hashedNewPassword, userId);
|
return await _dbAccess.updatePassword(hashedNewPassword, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Just sends the userid of the user that is to be deleted
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId">The Id of the user that is to be deleted</param>
|
||||||
|
/// <returns>returns the true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
public async Task<IActionResult> DeleteUser(int userId)
|
public async Task<IActionResult> DeleteUser(int userId)
|
||||||
{
|
{
|
||||||
return await _dbAccess.DeleteUser(userId);
|
return await _dbAccess.DeleteUser(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IActionResult> RefreshToken(string refreshToken)
|
||||||
|
{
|
||||||
|
User user = await _dbAccess.ReadUser(refreshToken);
|
||||||
|
if (user == null) { return new ConflictObjectResult(new { message = "Could not match refreshtoken" }); }
|
||||||
|
return new OkObjectResult(GenerateJwtToken(user));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a hash from a salt and input using the algorithm that is provided
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="input">This is the input that is supposed to be hashed</param>
|
||||||
|
/// <param name="algorithm">This is the alogorithm that is used to encrypt the input</param>
|
||||||
|
/// <param name="salt">This is something extra added to make the hashed input more unpredictable</param>
|
||||||
|
/// <returns>The hashed input</returns>
|
||||||
private static string ComputeHash(string input, HashAlgorithm algorithm, string salt)
|
private static string ComputeHash(string input, HashAlgorithm algorithm, string salt)
|
||||||
{
|
{
|
||||||
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
|
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
|
||||||
@ -120,6 +166,11 @@ namespace Api.BusinessLogic
|
|||||||
return BitConverter.ToString(hashedBytes);
|
return BitConverter.ToString(hashedBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks if password is up to our security standard
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="password">The password that is to be checked</param>
|
||||||
|
/// <returns>true or false dependeing on if the password is up to standard</returns>
|
||||||
public bool PasswordSecurity(string password)
|
public bool PasswordSecurity(string password)
|
||||||
{
|
{
|
||||||
var hasMinimum8Chars = new Regex(@".{8,}");
|
var hasMinimum8Chars = new Regex(@".{8,}");
|
||||||
@ -127,6 +178,11 @@ namespace Api.BusinessLogic
|
|||||||
return hasMinimum8Chars.IsMatch(password);
|
return hasMinimum8Chars.IsMatch(password);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a JWT token that last 2 hours
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="user">Used for sending the userid and username with the token</param>
|
||||||
|
/// <returns>Returns a valid JWTToken</returns>
|
||||||
private string GenerateJwtToken(User user)
|
private string GenerateJwtToken(User user)
|
||||||
{
|
{
|
||||||
var claims = new[]
|
var claims = new[]
|
||||||
@ -144,7 +200,7 @@ namespace Api.BusinessLogic
|
|||||||
_configuration["JwtSettings:Issuer"],
|
_configuration["JwtSettings:Issuer"],
|
||||||
_configuration["JwtSettings:Audience"],
|
_configuration["JwtSettings:Audience"],
|
||||||
claims,
|
claims,
|
||||||
expires: DateTime.Now.AddMinutes(30),
|
expires: DateTime.Now.AddHours(2),
|
||||||
signingCredentials: creds);
|
signingCredentials: creds);
|
||||||
|
|
||||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||||
|
@ -3,6 +3,7 @@ using Api.Models;
|
|||||||
using Api.DBAccess;
|
using Api.DBAccess;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Api.BusinessLogic;
|
using Api.BusinessLogic;
|
||||||
|
using System.Security.Claims;
|
||||||
|
|
||||||
namespace Api.Controllers
|
namespace Api.Controllers
|
||||||
{
|
{
|
||||||
@ -19,42 +20,53 @@ namespace Api.Controllers
|
|||||||
_deviceLogic = deviceLogic;
|
_deviceLogic = deviceLogic;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sends the userId to deviceLogic
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpGet("{userId}")]
|
[HttpGet]
|
||||||
public async Task<IActionResult> GetDevices(int userId)
|
public async Task<IActionResult> GetDevices()
|
||||||
{
|
{
|
||||||
List<Device> devices = await _dbAccess.ReadDevices(userId);
|
var claims = HttpContext.User.Claims;
|
||||||
if (devices.Count == 0) { return BadRequest(new { error = "There is no devices that belong to this userID" }); }
|
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
|
||||||
|
int userId = Convert.ToInt32(userIdString);
|
||||||
return await _deviceLogic.GetDevices(userId);
|
return await _deviceLogic.GetDevices(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sends the device and userId to deviceLogic
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpPost("adddevice/{userId}")]
|
[HttpPost("adddevice")]
|
||||||
public async Task<IActionResult> AddDevice([FromBody] string referenceId, int userId)
|
public async Task<IActionResult> AddDevice([FromBody] Device device)
|
||||||
{
|
{
|
||||||
return await _deviceLogic.AddDevice(referenceId, userId);
|
var claims = HttpContext.User.Claims;
|
||||||
|
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
|
||||||
|
int userId = Convert.ToInt32(userIdString);
|
||||||
|
return await _deviceLogic.AddDevice(device, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sends the deviceId to deviceLogic
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpGet("logs/{deviceId}")]
|
[HttpGet("logs/{deviceId}")]
|
||||||
public async Task<IActionResult> GetLogs(int deviceId)
|
public async Task<IActionResult> GetLogs(int deviceId, DateTime? dateTimeStart = null, DateTime? dateTimeEnd = null)
|
||||||
{
|
{
|
||||||
return await _deviceLogic.GetLogs(deviceId);
|
DateTimeRange dateTimeRange = new DateTimeRange();
|
||||||
|
if (dateTimeStart != null && dateTimeEnd != null)
|
||||||
|
{
|
||||||
|
dateTimeRange.DateTimeStart = (DateTime)dateTimeStart;
|
||||||
|
dateTimeRange.DateTimeEnd= (DateTime)dateTimeEnd;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
dateTimeRange.DateTimeStart = DateTime.Now;
|
||||||
|
dateTimeRange.DateTimeEnd = dateTimeRange.DateTimeStart;
|
||||||
|
}
|
||||||
|
return await _deviceLogic.GetLogs(dateTimeRange, deviceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sends the deviceId to deviceLogic
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpPut("Edit/{deviceId}")]
|
[HttpPut("Edit/{deviceId}")]
|
||||||
public async Task<IActionResult> EditDevice([FromBody] Device device, int deviceId)
|
public async Task<IActionResult> EditDevice([FromBody] Device device, int deviceId)
|
||||||
{
|
{
|
||||||
return await _deviceLogic.EditDevice(device, deviceId);
|
return await _deviceLogic.EditDevice(device, deviceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
[Authorize]
|
|
||||||
[HttpDelete("Delete/{referenceId}")]
|
|
||||||
public async Task<IActionResult> EditDevice(string referenceId)
|
|
||||||
{
|
|
||||||
return await _deviceLogic.EditDevice(referenceId);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Api.Models;
|
using Api.Models;
|
||||||
|
using System.Security.Claims;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Api.BusinessLogic;
|
using Api.BusinessLogic;
|
||||||
using Api.Models.User;
|
using Api.Models.User;
|
||||||
@ -18,42 +19,49 @@ namespace Api.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
//[Authorize]
|
//[Authorize]
|
||||||
[HttpGet("{userId}")]
|
[HttpGet("Get")]
|
||||||
public async Task<IActionResult> GetUSer(int userId)
|
public async Task<IActionResult> GetUSer()
|
||||||
{
|
{
|
||||||
|
var claims = HttpContext.User.Claims;
|
||||||
|
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
|
||||||
|
int userId = Convert.ToInt32(userIdString);
|
||||||
return await _userLogic.getUser(userId);
|
return await _userLogic.getUser(userId);
|
||||||
}
|
}
|
||||||
[HttpPost("login")]
|
|
||||||
|
[HttpPost("Login")]
|
||||||
public async Task<IActionResult> Login([FromBody] Login login)
|
public async Task<IActionResult> Login([FromBody] Login login)
|
||||||
{
|
{
|
||||||
return await _userLogic.Login(login);
|
return await _userLogic.Login(login);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("create")]
|
// Sends the user to userLogic
|
||||||
|
[HttpPost("Create")]
|
||||||
public async Task<IActionResult> CreateUser([FromBody] User user)
|
public async Task<IActionResult> CreateUser([FromBody] User user)
|
||||||
{
|
{
|
||||||
return await _userLogic.RegisterUser(user);
|
return await _userLogic.RegisterUser(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
//[Authorize]
|
// Sends the user and userId to userLogic
|
||||||
[HttpPut("edit/{userId}")]
|
|
||||||
public async Task<IActionResult> EditUser([FromBody] EditUserRequest userRequest, int 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpDelete("delete/{userId}")]
|
[HttpPut("Edit")]
|
||||||
public async Task<IActionResult> DeleteUser(int userId)
|
public async Task<IActionResult> EditUser([FromBody] User user)
|
||||||
{
|
{
|
||||||
|
var claims = HttpContext.User.Claims;
|
||||||
|
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
|
||||||
|
int userId = Convert.ToInt32(userIdString);
|
||||||
|
return await _userLogic.EditProfile(user, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sends the userId to userLogic
|
||||||
|
[Authorize]
|
||||||
|
[HttpDelete("Delete")]
|
||||||
|
public async Task<IActionResult> DeleteUser()
|
||||||
|
{
|
||||||
|
var claims = HttpContext.User.Claims;
|
||||||
|
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
|
||||||
|
int userId = Convert.ToInt32(userIdString);
|
||||||
return await _userLogic.DeleteUser(userId);
|
return await _userLogic.DeleteUser(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,5 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Api.Models;
|
using Api.Models;
|
||||||
using System.Text;
|
|
||||||
using System.Runtime.Intrinsics.Arm;
|
|
||||||
using System.Security.Cryptography;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||||
using Api.Models.User;
|
using Api.Models.User;
|
||||||
@ -24,7 +21,11 @@ namespace Api.DBAccess
|
|||||||
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a user using entityframework core
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="user">Need the entire user obj</param>
|
||||||
|
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
public async Task<IActionResult> CreateUser(User user)
|
public async Task<IActionResult> CreateUser(User user)
|
||||||
{
|
{
|
||||||
var users = await _context.Users.ToListAsync();
|
var users = await _context.Users.ToListAsync();
|
||||||
@ -50,6 +51,11 @@ namespace Api.DBAccess
|
|||||||
return new ConflictObjectResult(new { message = "Could not save to databse" });
|
return new ConflictObjectResult(new { message = "Could not save to databse" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns a user that matches either the email or username
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="login">Has a username or email and a password here the password is not used</param>
|
||||||
|
/// <returns>(user) that matches the login</returns>
|
||||||
public async Task<User> Login(Login login)
|
public async Task<User> Login(Login login)
|
||||||
{
|
{
|
||||||
User user = new User();
|
User user = new User();
|
||||||
@ -66,12 +72,34 @@ namespace Api.DBAccess
|
|||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Returns a user according to userID
|
||||||
public async Task<User> ReadUser(int userId)
|
public async Task<User> ReadUser(int userId)
|
||||||
{
|
{
|
||||||
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IActionResult> UpdateUser(EditUserRequest user, int userId)
|
// Returns a user according to refreshToken
|
||||||
|
public async Task<User> ReadUser(string refreshToken)
|
||||||
|
{
|
||||||
|
return await _context.Users.FirstOrDefaultAsync(u => u.RefreshToken == refreshToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Updates the refreshtoken saved in DB
|
||||||
|
public async void UpdatesRefreshToken(string refreshToken, int userId)
|
||||||
|
{
|
||||||
|
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||||
|
|
||||||
|
user.RefreshToken = refreshToken;
|
||||||
|
user.RefreshTokenExpiresAt = DateTime.Now.AddDays(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Updates the user in the database
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="user">Contains the updated user info</param>
|
||||||
|
/// <param name="userId">Has the id for the user that is to be updated</param>
|
||||||
|
/// <returns>returns the updated user in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
|
public async Task<IActionResult> UpdateUser(User user, int userId)
|
||||||
{
|
{
|
||||||
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||||
var users = await _context.Users.ToListAsync();
|
var users = await _context.Users.ToListAsync();
|
||||||
@ -121,6 +149,11 @@ namespace Api.DBAccess
|
|||||||
return new ConflictObjectResult(new { message = "Could not save to database" });
|
return new ConflictObjectResult(new { message = "Could not save to database" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Deletes a user from the database
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId">The Id of the user that is to be deleted</param>
|
||||||
|
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
public async Task<IActionResult> DeleteUser(int userId)
|
public async Task<IActionResult> DeleteUser(int userId)
|
||||||
{
|
{
|
||||||
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
|
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
|
||||||
@ -144,6 +177,7 @@ namespace Api.DBAccess
|
|||||||
return new ConflictObjectResult(new { message = "Invalid user" });
|
return new ConflictObjectResult(new { message = "Invalid user" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Returns devices according to userID
|
||||||
public async Task<List<Device>> ReadDevices(int userId)
|
public async Task<List<Device>> ReadDevices(int userId)
|
||||||
{
|
{
|
||||||
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
|
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
|
||||||
@ -155,6 +189,12 @@ namespace Api.DBAccess
|
|||||||
return devices;
|
return devices;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a user using entityframework core
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="device">The device that is going to be created</param>
|
||||||
|
/// <param name="userId">The user that owns the device</param>
|
||||||
|
/// <returns>returns the true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
|
||||||
public async Task<IActionResult> CreateDevice(Device device, int userId)
|
public async Task<IActionResult> CreateDevice(Device device, int userId)
|
||||||
{
|
{
|
||||||
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
|
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
|
||||||
@ -172,16 +212,30 @@ namespace Api.DBAccess
|
|||||||
return new ConflictObjectResult(new { message = "Could not save to database" });
|
return new ConflictObjectResult(new { message = "Could not save to database" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Returns a device according to deviceId
|
||||||
public async Task<Device> ReadDevice(int deviceId)
|
public async Task<Device> ReadDevice(int deviceId)
|
||||||
{
|
{
|
||||||
return await _context.Devices.FirstOrDefaultAsync(d => d.Id == deviceId);
|
return await _context.Devices.FirstOrDefaultAsync(d => d.Id == deviceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Returns a device according to refenreId
|
||||||
public Device ReadDevice(string refenreId)
|
public Device ReadDevice(string refenreId)
|
||||||
{
|
{
|
||||||
return _context.Devices.FirstOrDefault(d => d.ReferenceId == 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)
|
public async Task<IActionResult> UpdateDevice(Device device, int deviceId)
|
||||||
{
|
{
|
||||||
var device1 = await _context.Devices.FirstOrDefaultAsync(u => u.Id == deviceId);
|
var device1 = await _context.Devices.FirstOrDefaultAsync(u => u.Id == deviceId);
|
||||||
@ -203,6 +257,11 @@ namespace Api.DBAccess
|
|||||||
return new ConflictObjectResult(new { message = "Could not save to database" });
|
return new ConflictObjectResult(new { message = "Could not save to database" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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)
|
public async Task<List<TemperatureLogs>> ReadLogs(int deviceId)
|
||||||
{
|
{
|
||||||
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.Id == deviceId);
|
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.Id == deviceId);
|
||||||
@ -214,6 +273,11 @@ namespace Api.DBAccess
|
|||||||
return logs;
|
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)
|
public async void CreateLog(TemperatureLogs temperatureLogs, string referenceId)
|
||||||
{
|
{
|
||||||
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.ReferenceId == referenceId);
|
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.ReferenceId == referenceId);
|
||||||
@ -226,6 +290,7 @@ namespace Api.DBAccess
|
|||||||
await _context.SaveChangesAsync();
|
await _context.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Does a health check on the database access
|
||||||
public async Task<bool> Test()
|
public async Task<bool> Test()
|
||||||
{
|
{
|
||||||
return _context.Database.CanConnect();
|
return _context.Database.CanConnect();
|
||||||
|
@ -26,12 +26,14 @@ namespace Api.MQTTReciever
|
|||||||
|
|
||||||
using (mqttClient = mqttFactory.CreateMqttClient())
|
using (mqttClient = mqttFactory.CreateMqttClient())
|
||||||
{
|
{
|
||||||
|
// Entering our values for conecting to MQTT
|
||||||
var mqttClientOptions = new MqttClientOptionsBuilder()
|
var mqttClientOptions = new MqttClientOptionsBuilder()
|
||||||
.WithTcpServer($"{_configuration["MQTT:host"]}", Convert.ToInt32(_configuration["MQTT:port"]))
|
.WithTcpServer($"{_configuration["MQTT:host"]}", Convert.ToInt32(_configuration["MQTT:port"]))
|
||||||
.WithCredentials($"{_configuration["MQTT:username"]}", $"{_configuration["MQTT:password"]}")
|
.WithCredentials($"{_configuration["MQTT:username"]}", $"{_configuration["MQTT:password"]}")
|
||||||
.WithCleanSession()
|
.WithCleanSession()
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
|
// Everytime a message is recieved from the queue it goes into this mqttClient.ApplicationMessageReceivedAsync
|
||||||
// Setup message handling before connecting so that queued messages
|
// Setup message handling before connecting so that queued messages
|
||||||
// are also handled properly. When there is no event handler attached all
|
// are also handled properly. When there is no event handler attached all
|
||||||
// received messages get lost.
|
// received messages get lost.
|
||||||
@ -41,35 +43,38 @@ namespace Api.MQTTReciever
|
|||||||
|
|
||||||
string sensorData = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
|
string sensorData = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
|
||||||
|
|
||||||
var mqttMessageReceive = JsonSerializer.Deserialize<MQTTMessageReceive>(sensorData);
|
var messageReceive = JsonSerializer.Deserialize<MessageReceive>(sensorData);
|
||||||
|
|
||||||
if (mqttMessageReceive == null || mqttMessageReceive.temperature == 0 || mqttMessageReceive.device_id == null || mqttMessageReceive.timestamp == 0)
|
// Checks if the message has the data we need
|
||||||
|
if (messageReceive == null || messageReceive.device_id == null || messageReceive.timestamp == 0)
|
||||||
{
|
{
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Convert to the model we use in the database and gets the device from the database that is used for getting the current set temphigh and templow
|
||||||
TemperatureLogs newLog = new TemperatureLogs();
|
TemperatureLogs newLog = new TemperatureLogs();
|
||||||
string refernceId = mqttMessageReceive.device_id;
|
string refernceId = messageReceive.device_id;
|
||||||
var device = _dbAccess.ReadDevice(refernceId);
|
var device = _dbAccess.ReadDevice(refernceId);
|
||||||
|
|
||||||
|
// Checks if the device exist if it doesn't it throws the data away
|
||||||
if (device == null) { return Task.CompletedTask; }
|
if (device == null) { return Task.CompletedTask; }
|
||||||
|
|
||||||
newLog.Temperature = mqttMessageReceive.temperature;
|
newLog.Temperature = messageReceive.temperature;
|
||||||
newLog.Date = DateTimeOffset.FromUnixTimeSeconds(mqttMessageReceive.timestamp).DateTime;
|
newLog.Date = DateTimeOffset.FromUnixTimeSeconds(messageReceive.timestamp).DateTime;
|
||||||
newLog.TempHigh = device.TempHigh;
|
newLog.TempHigh = device.TempHigh;
|
||||||
newLog.TempLow = device.TempLow;
|
newLog.TempLow = device.TempLow;
|
||||||
|
|
||||||
|
// Send the data to dbaccess to be saved
|
||||||
_dbAccess.CreateLog(newLog, refernceId);
|
_dbAccess.CreateLog(newLog, refernceId);
|
||||||
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Starts the connection to rabbitmq
|
||||||
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
||||||
Console.WriteLine("mqttClient");
|
Console.WriteLine("mqttClient");
|
||||||
|
|
||||||
//var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder().WithTopicTemplate(topic).Build();
|
// Subscribes to our topic
|
||||||
|
|
||||||
await mqttClient.SubscribeAsync("temperature");
|
await mqttClient.SubscribeAsync("temperature");
|
||||||
|
|
||||||
Console.WriteLine("MQTT client subscribed to topic.");
|
Console.WriteLine("MQTT client subscribed to topic.");
|
||||||
|
138
backend/Api/Migrations/20250327084557_AddedRefreshTokenToUser.Designer.cs
generated
Normal file
138
backend/Api/Migrations/20250327084557_AddedRefreshTokenToUser.Designer.cs
generated
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Api;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Api.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(DBContext))]
|
||||||
|
[Migration("20250327084557_AddedRefreshTokenToUser")]
|
||||||
|
partial class AddedRefreshTokenToUser
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
|
||||||
|
|
||||||
|
modelBuilder.Entity("Api.Models.Device", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("ReferenceId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<double>("TempHigh")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b.Property<double>("TempLow")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b.Property<int?>("UserId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId");
|
||||||
|
|
||||||
|
b.ToTable("Devices");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Api.Models.TemperatureLogs", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("Date")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<int?>("DeviceId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<double>("TempHigh")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b.Property<double>("TempLow")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b.Property<double>("Temperature")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("DeviceId");
|
||||||
|
|
||||||
|
b.ToTable("TemperatureLogs");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Api.Models.User", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Email")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Password")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("RefreshToken")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("RefreshTokenExpiresAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Salt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("UserName")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Users");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Api.Models.Device", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("Api.Models.User", null)
|
||||||
|
.WithMany("Devices")
|
||||||
|
.HasForeignKey("UserId");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Api.Models.TemperatureLogs", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("Api.Models.Device", null)
|
||||||
|
.WithMany("Logs")
|
||||||
|
.HasForeignKey("DeviceId");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Api.Models.Device", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Logs");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Api.Models.User", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Devices");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Api.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddedRefreshTokenToUser : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "RefreshToken",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<DateTime>(
|
||||||
|
name: "RefreshTokenExpiresAt",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "RefreshToken",
|
||||||
|
table: "Users");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "RefreshTokenExpiresAt",
|
||||||
|
table: "Users");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -88,6 +88,12 @@ namespace Api.Migrations
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnType("TEXT");
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("RefreshToken")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("RefreshTokenExpiresAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
b.Property<string>("Salt")
|
b.Property<string>("Salt")
|
||||||
.HasColumnType("TEXT");
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
9
backend/Api/Models/DateTimeRange.cs
Normal file
9
backend/Api/Models/DateTimeRange.cs
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
namespace Api.Models
|
||||||
|
{
|
||||||
|
public class DateTimeRange
|
||||||
|
{
|
||||||
|
public DateTime DateTimeStart { get; set; }
|
||||||
|
|
||||||
|
public DateTime DateTimeEnd { get; set; }
|
||||||
|
}
|
||||||
|
}
|
11
backend/Api/Models/DeviceLimit.cs
Normal file
11
backend/Api/Models/DeviceLimit.cs
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
namespace Api.Models
|
||||||
|
{
|
||||||
|
public class DeviceLimit
|
||||||
|
{
|
||||||
|
public double TempHigh { get; set; }
|
||||||
|
|
||||||
|
public double TempLow { get; set; }
|
||||||
|
|
||||||
|
public string? ReferenceId { get; set; }
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,6 @@
|
|||||||
namespace Api.Models
|
namespace Api.Models
|
||||||
{
|
{
|
||||||
public class MQTTMessageReceive
|
public class MessageReceive
|
||||||
{
|
{
|
||||||
public double temperature { get; set; }
|
public double temperature { get; set; }
|
||||||
|
|
@ -12,6 +12,10 @@
|
|||||||
|
|
||||||
public string? Salt { get; set; }
|
public string? Salt { get; set; }
|
||||||
|
|
||||||
|
public string? RefreshToken { get; set; }
|
||||||
|
|
||||||
|
public DateTime RefreshTokenExpiresAt { get; set; }
|
||||||
|
|
||||||
public List<Device>? Devices { get; set; }
|
public List<Device>? Devices { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
using Api;
|
using Api;
|
||||||
|
using Api.AMQP;
|
||||||
using Api.AMQPReciever;
|
using Api.AMQPReciever;
|
||||||
using Api.DBAccess;
|
using Api.DBAccess;
|
||||||
using Api.MQTTReciever;
|
using Api.MQTTReciever;
|
||||||
using Microsoft.AspNetCore;
|
using Microsoft.AspNetCore;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
|
|
||||||
class Program
|
class Program
|
||||||
{
|
{
|
||||||
@ -12,7 +12,7 @@ class Program
|
|||||||
public static void Main(string[] args)
|
public static void Main(string[] args)
|
||||||
{
|
{
|
||||||
var app = CreateWebHostBuilder(args).Build();
|
var app = CreateWebHostBuilder(args).Build();
|
||||||
|
string rabbitMQ = "AMQP"; // This value has to be either "AMQP" or "MQTT"
|
||||||
|
|
||||||
RunMigrations(app);
|
RunMigrations(app);
|
||||||
|
|
||||||
@ -24,11 +24,19 @@ class Program
|
|||||||
var configuration = services.GetRequiredService<IConfiguration>();
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
var dbAccess = services.GetRequiredService<DbAccess>();
|
var dbAccess = services.GetRequiredService<DbAccess>();
|
||||||
|
|
||||||
//AMQPReciever amqp = new AMQPReciever(configuration, dbAccess);
|
// Choose to either connect AMQP or MQTT
|
||||||
//amqp.Handle_Received_Application_Message().Wait();
|
if (rabbitMQ == "AMQP")
|
||||||
|
{
|
||||||
MQTTReciever mqtt = new MQTTReciever(configuration, dbAccess);
|
AMQPReciever amqpReciever = new AMQPReciever(configuration, dbAccess);
|
||||||
mqtt.Handle_Received_Application_Message().Wait();
|
amqpReciever.Handle_Received_Application_Message().Wait();
|
||||||
|
AMQPPublisher aMQPPush = new AMQPPublisher(configuration, dbAccess);
|
||||||
|
aMQPPush.Handle_Push_Device_Limits().Wait();
|
||||||
|
}
|
||||||
|
else if (rabbitMQ == "MQTT")
|
||||||
|
{
|
||||||
|
MQTTReciever mqtt = new MQTTReciever(configuration, dbAccess);
|
||||||
|
mqtt.Handle_Received_Application_Message().Wait();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -66,6 +66,29 @@ namespace Api
|
|||||||
services.AddSwaggerGen(c =>
|
services.AddSwaggerGen(c =>
|
||||||
{
|
{
|
||||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
|
||||||
|
|
||||||
|
// Configure Swagger to use Bearer token authentication
|
||||||
|
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Description = "JWT Authorization header using the Bearer scheme",
|
||||||
|
Type = SecuritySchemeType.Http,
|
||||||
|
Scheme = "bearer"
|
||||||
|
});
|
||||||
|
|
||||||
|
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||||
|
{
|
||||||
|
{
|
||||||
|
new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Reference = new OpenApiReference
|
||||||
|
{
|
||||||
|
Type = ReferenceType.SecurityScheme,
|
||||||
|
Id = "Bearer"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
new string[] { }
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -87,6 +110,8 @@ namespace Api
|
|||||||
|
|
||||||
app.UseRouting();
|
app.UseRouting();
|
||||||
|
|
||||||
|
app.UseAuthentication();
|
||||||
|
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
app.UseEndpoints(endpoints =>
|
app.UseEndpoints(endpoints =>
|
||||||
|
@ -1,14 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<OutputType>Exe</OutputType>
|
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="RabbitMQ.Client" Version="7.1.2" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
@ -1,25 +0,0 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
|
||||||
# Visual Studio Version 17
|
|
||||||
VisualStudioVersion = 17.9.34607.119
|
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp1", "ConsoleApp1.csproj", "{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}"
|
|
||||||
EndProject
|
|
||||||
Global
|
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
|
||||||
Debug|Any CPU = Debug|Any CPU
|
|
||||||
Release|Any CPU = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
|
||||||
{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{0BC93CF2-F92D-4DD6-83BE-A985CBB74960}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
|
||||||
HideSolutionNode = FALSE
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
|
||||||
SolutionGuid = {55EE0E94-4585-4E79-AC67-4B0E809E99AB}
|
|
||||||
EndGlobalSection
|
|
||||||
EndGlobal
|
|
@ -1,52 +0,0 @@
|
|||||||
using RabbitMQ.Client;
|
|
||||||
using RabbitMQ.Client.Events;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
|
|
||||||
var factory = new ConnectionFactory();
|
|
||||||
var queue = "test";
|
|
||||||
|
|
||||||
|
|
||||||
factory.UserName = "h5";
|
|
||||||
factory.Password = "Merc1234";
|
|
||||||
factory.HostName = "10.135.51.116";
|
|
||||||
factory.Port = 5672;
|
|
||||||
|
|
||||||
using var conn = await factory.CreateConnectionAsync();
|
|
||||||
Console.WriteLine("AMQPClien connected");
|
|
||||||
using var channel = await conn.CreateChannelAsync();
|
|
||||||
|
|
||||||
await channel.QueueDeclareAsync(queue: queue, durable: false, exclusive: false, autoDelete: false);
|
|
||||||
Console.WriteLine($"{queue} connected");
|
|
||||||
|
|
||||||
var consumer = new AsyncEventingBasicConsumer(channel);
|
|
||||||
consumer.ReceivedAsync += (model, ea) =>
|
|
||||||
{
|
|
||||||
Console.WriteLine("Received application message.");
|
|
||||||
var body = ea.Body.ToArray();
|
|
||||||
var message = Encoding.UTF8.GetString(body);
|
|
||||||
Console.WriteLine(message);
|
|
||||||
|
|
||||||
return Task.CompletedTask;
|
|
||||||
};
|
|
||||||
|
|
||||||
await channel.BasicConsumeAsync(queue, true, consumer);
|
|
||||||
|
|
||||||
|
|
||||||
const string message = "Hello World!";
|
|
||||||
var body = Encoding.UTF8.GetBytes(message);
|
|
||||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
|
||||||
Console.WriteLine(" Press enter to continue.");
|
|
||||||
Console.ReadLine();
|
|
||||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
|
||||||
Console.WriteLine(" Press enter to continue.");
|
|
||||||
Console.ReadLine();
|
|
||||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
|
||||||
Console.WriteLine(" Press enter to continue.");
|
|
||||||
Console.ReadLine();
|
|
||||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
|
||||||
Console.WriteLine(" Press enter to continue.");
|
|
||||||
Console.ReadLine();
|
|
||||||
await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queue, body: body);
|
|
||||||
Console.WriteLine(" Press enter to exit.");
|
|
||||||
Console.ReadLine();
|
|
2
frontend/.gitignore
vendored
Normal file
2
frontend/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
shared/constants.js
|
||||||
|
|
@ -13,16 +13,16 @@
|
|||||||
|
|
||||||
<body>
|
<body>
|
||||||
<div id="container">
|
<div id="container">
|
||||||
<div class="topnav">
|
<div class="topnav">
|
||||||
<a href="/home/index.html">Home</a>
|
<a href="/home/index.html">Home</a>
|
||||||
|
<div style="display: flex; justify-content: flex-end;">
|
||||||
<a class="active" href="/devices/index.html">Devices</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>
|
||||||
<a href="/profile/index.html">Profile</a>
|
<span class="logoutContainer">
|
||||||
<span class="logoutContainer">
|
<img class="logout" src="/img/logout.png">
|
||||||
<img class="logout" src="/img/logout.png">
|
</span>
|
||||||
</span>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
<div class="addDeviceContainer">
|
<div class="addDeviceContainer">
|
||||||
<button id="addDevice">Add Device</button>
|
<button id="addDevice">Add Device</button>
|
||||||
</div>
|
</div>
|
||||||
|
@ -1,43 +1,44 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Temperature-Alarm-Web</title>
|
<title>Temperature-Alarm-Web</title>
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
|
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
|
||||||
<link rel="stylesheet" href="/styles/auth.css">
|
<script defer type="module" src="/scripts/home.js"></script>
|
||||||
<link rel="stylesheet" href="/styles/home.css" />
|
<link rel="stylesheet" href="/styles/common.css">
|
||||||
<script type="module" src="/scripts/home.js"></script>
|
<link rel="stylesheet" href="/styles/home.css" />
|
||||||
<script defer type="module" src="/shared/utils.js"></script>
|
<link rel="stylesheet" href="/styles/auth.css" />
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<div id="container">
|
<div class="topnav">
|
||||||
<div class="topnav">
|
<a class="active" href="/home/index.html">Home</a>
|
||||||
<a class="active" href="/home/index.html">Home</a>
|
<div style="display: flex; justify-content: flex-end;">
|
||||||
<a href="/devices/index.html">Devices</a>
|
<a href="/devices/index.html">Devices</a>
|
||||||
<div style="display: flex; justify-content: flex-end;">
|
<a href="/profile/index.html">Profile</a>
|
||||||
<a href="/profile/index.html">Profile</a>
|
<span class="logoutContainer">
|
||||||
<span class="logoutContainer">
|
<img class="logout" src="/img/logout.png">
|
||||||
<img class="logout" src="/img/logout.png">
|
</span>
|
||||||
</span>
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="container">
|
||||||
|
<div class="chart-container">
|
||||||
|
<canvas id="myChart" style="width: 49%; height: 49%;"></canvas>
|
||||||
|
</div>
|
||||||
|
<div id="table-wrapper">
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<th>Temperature</th>
|
||||||
|
<th>Date</th>
|
||||||
|
<th>Time</th>
|
||||||
|
<th>Limits</th>
|
||||||
|
</tr>
|
||||||
|
<tbody id="TemperatureTable"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div id="error" class="error"></div>
|
||||||
<div class="chartContainer">
|
</body>
|
||||||
<canvas id="myChart" style="width: 49%; height: 49%;"></canvas>
|
|
||||||
</div>
|
|
||||||
<div class="tableConatiner">
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<th>Name</th>
|
|
||||||
<th>Temperature</th>
|
|
||||||
<th>Date</th>
|
|
||||||
<th>TempHigh</th>
|
|
||||||
<th>TempLow</th>
|
|
||||||
</tr>
|
|
||||||
<tbody id="TemperatureTable"></tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
</html>
|
||||||
|
|
||||||
|
@ -4,6 +4,7 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<title>Login - Temperature alarm</title>
|
<title>Login - Temperature alarm</title>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<link rel="stylesheet" href="/styles/common.css">
|
||||||
<link rel="stylesheet" href="/styles/auth.css">
|
<link rel="stylesheet" href="/styles/auth.css">
|
||||||
<script defer type="module" src="/scripts/login.js"></script>
|
<script defer type="module" src="/scripts/login.js"></script>
|
||||||
</head>
|
</head>
|
||||||
@ -25,7 +26,7 @@
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="form-error"></div>
|
<div id="form-error" class="error"></div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</body>
|
</body>
|
||||||
|
@ -1,28 +0,0 @@
|
|||||||
export const mockTemperatureLogs = [
|
|
||||||
{ id: 1, temperature: 18.9, date: "2025-03-19T17:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 19.1, date: "2025-03-19T17:10:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 19.5, date: "2025-03-19T17:20:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 19.8, date: "2025-03-19T17:30:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.1, date: "2025-03-19T17:40:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.3, date: "2025-03-19T17:50:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.6, date: "2025-03-19T18:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.9, date: "2025-03-19T18:10:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.8, date: "2025-03-19T18:20:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.7, date: "2025-03-19T18:30:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.5, date: "2025-03-19T18:40:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.3, date: "2025-03-19T18:50:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.1, date: "2025-03-19T19:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 18.9, date: "2025-03-19T20:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 19.1, date: "2025-03-19T20:10:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 19.5, date: "2025-03-19T20:20:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 19.8, date: "2025-03-19T20:30:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.1, date: "2025-03-19T20:40:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 20.3, date: "2025-03-19T20:50:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 22.6, date: "2025-03-19T21:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 22.9, date: "2025-03-19T21:10:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 22.8, date: "2025-03-19T21:20:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 22.7, date: "2025-03-19T21:30:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 22.5, date: "2025-03-19T21:40:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 23.3, date: "2025-03-19T21:50:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
{ id: 1, temperature: 24.1, date: "2025-03-19T22:00:00Z", tempHigh: 22.0, tempLow: 18.0 },
|
|
||||||
]
|
|
@ -13,20 +13,23 @@
|
|||||||
<div id="container">
|
<div id="container">
|
||||||
<div class="topnav">
|
<div class="topnav">
|
||||||
<a href="/home/index.html">Home</a>
|
<a href="/home/index.html">Home</a>
|
||||||
<a href="/devices/index.html">Devices</a>
|
|
||||||
<div style="display: flex; justify-content: flex-end;">
|
<div style="display: flex; justify-content: flex-end;">
|
||||||
|
<a href="/devices/index.html">Devices</a>
|
||||||
<a class="active" href="/profile/index.html">Profile</a>
|
<a class="active" href="/profile/index.html">Profile</a>
|
||||||
<span class="logoutContainer">
|
<span class="logoutContainer">
|
||||||
<img class="logout" src="/img/logout.png">
|
<img class="logout" src="/img/logout.png">
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div id="profileCard"></div>
|
<div style="display: flex; justify-content: center;">
|
||||||
<div class="btnContainer">
|
<div class="profileContainer">
|
||||||
<button class="btn" id="openEditModal">Edit</button>
|
<div id="profileCard"></div>
|
||||||
<button class="btn" id="openPasswordModal">Change Password</button>
|
<div class="btnContainer">
|
||||||
|
<button class="btn" id="openEditModal">Edit</button>
|
||||||
</div>
|
<button class="btn" id="openPasswordModal">Change Password</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="editModal" class="modal">
|
<div id="editModal" class="modal">
|
||||||
|
@ -4,6 +4,7 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<title>Register - Temperature Alarm</title>
|
<title>Register - Temperature Alarm</title>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<link rel="stylesheet" href="/styles/common.css">
|
||||||
<link rel="stylesheet" href="/styles/auth.css">
|
<link rel="stylesheet" href="/styles/auth.css">
|
||||||
<script defer type="module" src="/scripts/register.js"></script>
|
<script defer type="module" src="/scripts/register.js"></script>
|
||||||
</head>
|
</head>
|
||||||
@ -33,7 +34,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="form-error"></div>
|
<div id="form-error" class="error"></div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</body>
|
</body>
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import { getDevicesOnUserId, deleteDevice, update, add } from "./services/devices.service.js";
|
import { getDevices, deleteDevice, update, add } from "./services/devices.service.js";
|
||||||
import { devices } from "../mockdata/devices.mockdata.js";
|
import { devices } from "../mockdata/devices.mockdata.js";
|
||||||
|
|
||||||
let id = localStorage.getItem("id");
|
getDevices().then(res => {
|
||||||
// getDevicesOnUserId(id).then(res => {
|
buildTable(res)
|
||||||
// buildTable(res)
|
})
|
||||||
// })
|
|
||||||
buildTable(devices);
|
buildTable(devices);
|
||||||
|
|
||||||
let selectedReferenceId = null; // Store the selected referenceId
|
let selectedReferenceId = null; // Store the selected referenceId
|
||||||
|
@ -1,64 +1,83 @@
|
|||||||
import { mockTemperatureLogs } from "../mockdata/temperature-logs.mockdata.js"; // Import data
|
import { getLogsOnDeviceId } from "./services/devices.service.js";
|
||||||
|
|
||||||
const xValues = mockTemperatureLogs.map((log) =>
|
async function buildChart(data) {
|
||||||
new Date(log.date).toLocaleString()
|
data.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
|
||||||
); // Full Date labels
|
|
||||||
const yValues = mockTemperatureLogs.map((log) => log.temperature); // Temperature values
|
const xValues = data.map((log) =>
|
||||||
buildTable(mockTemperatureLogs);
|
new Date(log.date).toLocaleString()
|
||||||
new Chart("myChart", {
|
); // Full Date labels
|
||||||
type: "line",
|
const yValues = data.map((log) => log.temperature); // Temperature values
|
||||||
data: {
|
buildTable(data);
|
||||||
labels: xValues,
|
new Chart("myChart", {
|
||||||
datasets: [
|
type: "line",
|
||||||
{
|
data: {
|
||||||
fill: false,
|
labels: xValues,
|
||||||
lineTension: 0.4,
|
datasets: [
|
||||||
backgroundColor: "rgba(0,0,255,1.0)",
|
{
|
||||||
borderColor: "rgba(0,0,255,0.1)",
|
label: "Temperature",
|
||||||
data: yValues,
|
fill: false,
|
||||||
},
|
lineTension: 0.4,
|
||||||
],
|
backgroundColor: "rgba(0,0,255,1.0)",
|
||||||
},
|
borderColor: "rgba(0,0,255,0.1)",
|
||||||
options: {
|
data: yValues,
|
||||||
tooltips: {
|
},
|
||||||
callbacks: {
|
],
|
||||||
title: function (tooltipItem) {
|
|
||||||
return `Date: ${tooltipItem[0].label}`;
|
|
||||||
},
|
},
|
||||||
label: function (tooltipItem) {
|
options: {
|
||||||
return `Temperature: ${tooltipItem.value}°C`;
|
tooltips: {
|
||||||
|
callbacks: {
|
||||||
|
title: function (tooltipItem) {
|
||||||
|
return `Date: ${tooltipItem[0].label}`;
|
||||||
|
},
|
||||||
|
label: function (tooltipItem) {
|
||||||
|
return `Temperature: ${tooltipItem.value}°C`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
});
|
||||||
},
|
}
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
function buildTable(data) {
|
function buildTable(data) {
|
||||||
var table = document.getElementById(`TemperatureTable`);
|
var table = document.getElementById(`TemperatureTable`);
|
||||||
data.forEach((log) => {
|
data.forEach((log) => {
|
||||||
var averageTemp = (log.tempHigh + log.tempLow) / 2.0;
|
var averageTemp = (log.tempHigh + log.tempLow) / 2.0;
|
||||||
var color;
|
var color;
|
||||||
if (log.temperature > log.tempHigh) {
|
if (log.temperature >= log.tempHigh) {
|
||||||
color = "tempHigh";
|
color = "tempHigh";
|
||||||
} else if (
|
} else if (
|
||||||
log.temperature < log.tempHigh &&
|
log.temperature < log.tempHigh &&
|
||||||
log.temperature > averageTemp
|
log.temperature > averageTemp
|
||||||
) {
|
) {
|
||||||
color = "tempMidHigh";
|
color = "tempMidHigh";
|
||||||
} else if (log.temperature < log.tempLow) {
|
} else if (log.temperature <= log.tempLow) {
|
||||||
color = "tempLow";
|
color = "tempLow";
|
||||||
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) {
|
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) {
|
||||||
color = "tempMidLow";
|
color = "tempMidLow";
|
||||||
} else {
|
} else {
|
||||||
color = "tempNormal";
|
color = "tempNormal";
|
||||||
}
|
}
|
||||||
var row = ` <tr>
|
|
||||||
<td>Name</td>
|
const date = new Date(log.date).toLocaleDateString();
|
||||||
<td class="${color}">${log.temperature}</td>
|
const time = new Date(log.date).toLocaleTimeString();
|
||||||
<td>${log.date}</td>
|
|
||||||
<td class="tempHigh">${log.tempHigh}</td>
|
table.innerHTML += `
|
||||||
<td class="tempLow">${log.tempLow}</td>
|
<tr>
|
||||||
</tr>`;
|
<td class="temperature ${color}">${log.temperature}°C</td>
|
||||||
table.innerHTML += row;
|
<td>${date}</td>
|
||||||
});
|
<td width="50%">${time}</td>
|
||||||
}
|
<td width="50%">Min: <b class="low-limit">${log.tempLow}°C</b>, Max: <b class="high-limit">${log.tempHigh}°C</b></td>
|
||||||
|
</tr>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO change device id
|
||||||
|
getLogsOnDeviceId(1)
|
||||||
|
.then(buildChart)
|
||||||
|
.catch(err => {
|
||||||
|
document.getElementById("error").innerText = err;
|
||||||
|
document.getElementById("error").style.display = "block";
|
||||||
|
document.getElementById("container").style.display = "none";
|
||||||
|
});
|
||||||
|
|
||||||
|
@ -10,17 +10,18 @@ document.getElementById("loginForm").addEventListener("submit", function(event)
|
|||||||
|
|
||||||
login(emailOrUsername, password)
|
login(emailOrUsername, password)
|
||||||
.then(response => {
|
.then(response => {
|
||||||
if (response.error) {
|
document.cookie = `auth-token=${response.token}; Path=/`;
|
||||||
document.getElementById("form-error").innerText = response.error;
|
|
||||||
document.getElementById("form-error").style.display = "block";
|
localStorage.setItem("user", {
|
||||||
return;
|
id: response.id,
|
||||||
}
|
username: response.userName,
|
||||||
else{
|
});
|
||||||
if (typeof(Storage) !== "undefined") {
|
|
||||||
localStorage.setItem("id", response.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
location.href = "/home";
|
location.href = "/home";
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
document.getElementById("form-error").innerText = error;
|
||||||
|
document.getElementById("form-error").style.display = "block";
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -14,13 +14,10 @@ document.getElementById("registerForm").addEventListener("submit", function(even
|
|||||||
// Call function with form values
|
// Call function with form values
|
||||||
create(email, username, password, repeatPassword)
|
create(email, username, password, repeatPassword)
|
||||||
.then(response => {
|
.then(response => {
|
||||||
if (response?.error) {
|
|
||||||
document.getElementById("form-error").innerText = response.error;
|
|
||||||
document.getElementById("form-error").style.display = "block";
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
location.href = "/login";
|
location.href = "/login";
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
document.getElementById("form-error").innerText = error;
|
||||||
|
document.getElementById("form-error").style.display = "block";
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -1,65 +1,22 @@
|
|||||||
import { address } from "../../shared/constants.js";
|
import { request } from "../../shared/utils.js";
|
||||||
|
|
||||||
export function getDevicesOnUserId(userId) {
|
export function getDevices() {
|
||||||
fetch(`${address}/device/${userId}`, {
|
return request("GET", "/device");
|
||||||
method: "GET",
|
}
|
||||||
|
|
||||||
|
export function update(ids) {
|
||||||
|
fetch(`${address}/get-on-user-id`, {
|
||||||
|
method: "PATCH",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
},
|
},
|
||||||
|
body: JSON.stringify({ ids: ids })
|
||||||
})
|
})
|
||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
.then(data => console.log("Success:", data))
|
.then(data => console.log("Success:", data))
|
||||||
.catch(error => console.error("Error:", error));
|
.catch(error => console.error("Error:", error));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function add(id) {
|
export function getLogsOnDeviceId(id) {
|
||||||
fetch(`${address}/device`, {
|
return request("GET", `/device/logs/${id}`);
|
||||||
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,66 +1,37 @@
|
|||||||
import { address } from "../../shared/constants.js";
|
import { request } from "../../shared/utils.js";
|
||||||
import { handleResponse } from "../../shared/utils.js";
|
|
||||||
|
|
||||||
|
|
||||||
export function get(userId) {
|
export function get() {
|
||||||
return fetch(`${address}/user/${userId}`, {
|
return request("GET",`/user/get`)
|
||||||
method: "GET",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.then(handleResponse)
|
|
||||||
.catch(err => { error: err.message });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function login(usernameOrEmail, password) {
|
export function login(usernameOrEmail, password) {
|
||||||
return fetch(`${address}/user/login`, {
|
return request("POST", "/user/login", {
|
||||||
method: "POST",
|
EmailOrUsrn: usernameOrEmail,
|
||||||
headers: {
|
Password: password,
|
||||||
"Content-Type": "application/json"
|
});
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
EmailOrUsrn: usernameOrEmail,
|
|
||||||
Password: password,
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
.then(handleResponse)
|
|
||||||
.catch(err => { error: err.message });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function create(email, username, password, repeatPassword){
|
export function create(email, username, password, repeatPassword){
|
||||||
return fetch(`${address}/user/create`, {
|
return request("POST", "/user/create", {
|
||||||
method: "POST",
|
email,
|
||||||
headers: {
|
username,
|
||||||
"Content-Type": "application/json"
|
password,
|
||||||
},
|
repeatPassword,
|
||||||
body: JSON.stringify({email: email, username: username, password: password, repeatPassword: repeatPassword})
|
});
|
||||||
})
|
|
||||||
.then(handleResponse)
|
|
||||||
.catch(err => { error: err.message });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function update(email, username, userId){
|
export function update(email, username){
|
||||||
return fetch(`${address}/user/edit/${userId}`, {
|
return request("PATCH", "/user/update", {
|
||||||
method: "PUT",
|
email,
|
||||||
headers: {
|
username,
|
||||||
"Content-Type": "application/json"
|
});
|
||||||
},
|
|
||||||
body: JSON.stringify({email: email, username: username})
|
|
||||||
})
|
|
||||||
.then(handleResponse)
|
|
||||||
.catch(err => { error: err.message });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updatePassword(oldPassword, newPassword, userId){
|
export function updatePassword(oldPassword, newPassword){
|
||||||
return fetch(`${address}/user/change-password/${userId}`, {
|
return request("PATCH", "/user/update-password", {
|
||||||
method: "PUT",
|
oldPassword,
|
||||||
headers: {
|
newPassword,
|
||||||
"Content-Type": "application/json"
|
});
|
||||||
},
|
|
||||||
body: JSON.stringify({oldPassword: oldPassword, newPassword: newPassword})
|
|
||||||
})
|
|
||||||
.then(handleResponse)
|
|
||||||
.catch(err => { error: err.message });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
3
frontend/shared/constants.example.js
Normal file
3
frontend/shared/constants.example.js
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
//export const address = "https://temperature.mercantec.tech/api"
|
||||||
|
export const address = "http://localhost:5000/api";
|
||||||
|
|
@ -1 +0,0 @@
|
|||||||
export const address = "http://127.0.0.1:5000/api"
|
|
@ -1,13 +1,37 @@
|
|||||||
export async function handleResponse(response) {
|
import { address } from "./constants.js";
|
||||||
const json = await response.json();
|
|
||||||
|
|
||||||
if (response.ok || json.error) return json;
|
export async function request(method, path, body = null) {
|
||||||
|
const token = document.cookie.match(/\bauth-token=([^;\s]+)/);
|
||||||
|
|
||||||
if (json.errors) {
|
const headers = {};
|
||||||
return { error: Object.values(response.errors)[0][0] };
|
if (body)
|
||||||
}
|
headers["Content-Type"] = "application/json";
|
||||||
|
if (token?.length > 1)
|
||||||
|
headers["Authorization"] = `Bearer ${token[1]}`;
|
||||||
|
|
||||||
return { error: "Request failed with HTTP code " + response.status };
|
return new Promise((resolve, reject) => {
|
||||||
|
fetch(address + path, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
body: body ? JSON.stringify(body) : undefined,
|
||||||
|
})
|
||||||
|
.then(async response => {
|
||||||
|
try {
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
if (response.ok) return resolve(json);
|
||||||
|
|
||||||
|
if (json.error) return reject(json.error);
|
||||||
|
|
||||||
|
if (json.message) return reject(json.message);
|
||||||
|
|
||||||
|
if (json.errors) return reject(Object.values(json.errors)[0][0]);
|
||||||
|
} finally {
|
||||||
|
reject("Request failed with HTTP code " + response.status);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => reject(err.message));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
document.querySelectorAll(".logoutContainer").forEach(closeBtn => {
|
document.querySelectorAll(".logoutContainer").forEach(closeBtn => {
|
||||||
|
@ -66,16 +66,6 @@ button:hover {
|
|||||||
margin-top: 0.5rem;
|
margin-top: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
#form-error {
|
|
||||||
display: none;
|
|
||||||
background-color: #FFCDD2;
|
|
||||||
color: #C62828;
|
|
||||||
border: 1px solid #C62828;
|
|
||||||
border-radius: 4px;
|
|
||||||
padding: 1rem 2rem;
|
|
||||||
margin-top: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.logoutContainer{
|
.logoutContainer{
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
@ -1,3 +1,16 @@
|
|||||||
.error {
|
.error {
|
||||||
background-color: #EF9A9A;
|
display: none;
|
||||||
|
background-color: #FFCDD2;
|
||||||
|
color: #C62828;
|
||||||
|
border: 1px solid #C62828;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 1rem 2rem;
|
||||||
|
margin-top: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.logout{
|
||||||
|
width: 20px;
|
||||||
|
height: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,13 +1,51 @@
|
|||||||
body {
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: Arial, Helvetica, sans-serif;
|
||||||
|
background-color: #F9F9F9;
|
||||||
font-family: Arial, Helvetica, sans-serif;
|
font-family: Arial, Helvetica, sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
#container {
|
#container {
|
||||||
background-color: white;
|
margin: 0 2rem;
|
||||||
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-wrapper {
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid #DDD;
|
||||||
}
|
}
|
||||||
|
|
||||||
table {
|
table {
|
||||||
|
font-family: arial, sans-serif;
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
background-color: white;
|
||||||
|
color: #616161;
|
||||||
margin: 20px;
|
margin: 20px;
|
||||||
font-family: arial, sans-serif;
|
font-family: arial, sans-serif;
|
||||||
border-collapse: collapse;
|
border-collapse: collapse;
|
||||||
@ -16,38 +54,63 @@ table {
|
|||||||
|
|
||||||
td,
|
td,
|
||||||
th {
|
th {
|
||||||
border: 1px solid #dddddd;
|
border-right: 1px solid #DDD;
|
||||||
text-align: left;
|
border-bottom: 1px solid #DDD;
|
||||||
padding: 8px;
|
text-align: left;
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
border-bottom: 2px solid #DDD;
|
||||||
}
|
}
|
||||||
|
|
||||||
tr:nth-child(even) {
|
tr:nth-child(even) {
|
||||||
background-color: #dddddd;
|
background-color: #F5F5F5;
|
||||||
|
}
|
||||||
|
|
||||||
|
table .temperature {
|
||||||
|
text-align: center;
|
||||||
|
color: white;
|
||||||
|
font-weight: bold;
|
||||||
|
width: 20px;
|
||||||
|
}
|
||||||
|
table tr:not(:last-child) .temperature {
|
||||||
|
border-bottom-color: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
.tempHigh {
|
.tempHigh {
|
||||||
color: #ff0000;
|
background-color: #ff0000;
|
||||||
width: 20px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.tempMidHigh {
|
.tempMidHigh {
|
||||||
color: #fffb00;
|
background-color: #FFA000;
|
||||||
width: 20px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.tempNormal {
|
.tempNormal {
|
||||||
color: #02ed26;
|
background-color: #AAA;
|
||||||
width: 20px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.tempMidLow {
|
.tempMidLow {
|
||||||
color: #16fae7;
|
background-color: #64B5F6;
|
||||||
width: 20px;
|
}
|
||||||
|
.tempLow {
|
||||||
|
background-color: #3F51B5;
|
||||||
}
|
}
|
||||||
|
|
||||||
.tempLow {
|
.low-limit {
|
||||||
color: #0004ff;
|
color: #3F51B5;
|
||||||
width: 20px;
|
}
|
||||||
|
.high-limit {
|
||||||
|
color: #F00;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart-container {
|
||||||
|
margin: 2rem 0;
|
||||||
|
background-color: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid #DDD;
|
||||||
|
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#error {
|
||||||
|
margin: 2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.chartContainer{
|
.chartContainer{
|
||||||
|
@ -85,3 +85,12 @@ h2{
|
|||||||
width: 90%;
|
width: 90%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.profileContainer {
|
||||||
|
margin: 2rem 0;
|
||||||
|
background-color: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid #DDD;
|
||||||
|
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
|
||||||
|
width: 400px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
all: main.c mqtt.c temperature.c device_id.c
|
FILES=main.c brokers/mqtt.c brokers/amqp.c devices/temperature.c devices/display.c device_id.c
|
||||||
$(CC) -lmosquitto -lpthread -li2c main.c mqtt.c temperature.c device_id.c
|
|
||||||
|
all: $(FILES)
|
||||||
|
$(CC) -lmosquitto -lrabbitmq -lpthread -li2c $(FILES)
|
||||||
|
|
||||||
|
35
iot/brokers/amqp.c
Normal file
35
iot/brokers/amqp.c
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
#include <rabbitmq-c/amqp.h>
|
||||||
|
#include <rabbitmq-c/tcp_socket.h>
|
||||||
|
|
||||||
|
#include "../config.h"
|
||||||
|
|
||||||
|
amqp_connection_state_t conn;
|
||||||
|
amqp_socket_t *socket;
|
||||||
|
|
||||||
|
void broker_on_connect(void);
|
||||||
|
|
||||||
|
void amqp_send_message(char *queue, char *message)
|
||||||
|
{
|
||||||
|
amqp_basic_properties_t props;
|
||||||
|
props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
|
||||||
|
props.content_type = amqp_literal_bytes("text/plain");
|
||||||
|
props.delivery_mode = 2;
|
||||||
|
|
||||||
|
amqp_basic_publish(conn, 1, amqp_cstring_bytes(queue), amqp_cstring_bytes(queue), 0, 0, &props, amqp_cstring_bytes(message));
|
||||||
|
}
|
||||||
|
|
||||||
|
void init_amqp(void)
|
||||||
|
{
|
||||||
|
conn = amqp_new_connection();
|
||||||
|
|
||||||
|
socket = amqp_tcp_socket_new(conn);
|
||||||
|
amqp_socket_open(socket, AMQP_IP, AMQP_PORT);
|
||||||
|
|
||||||
|
amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, AMQP_USER, AMQP_PASSWORD);
|
||||||
|
|
||||||
|
amqp_channel_open(conn, 1);
|
||||||
|
|
||||||
|
broker_on_connect();
|
||||||
|
|
||||||
|
for (;;);
|
||||||
|
}
|
4
iot/brokers/amqp.h
Normal file
4
iot/brokers/amqp.h
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
void init_amqp(void);
|
||||||
|
|
||||||
|
void amqp_send_message(char *topic, char *message);
|
||||||
|
|
@ -3,11 +3,11 @@
|
|||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
|
|
||||||
#include "config.h"
|
#include "../config.h"
|
||||||
|
|
||||||
struct mosquitto *mosq;
|
struct mosquitto *mosq;
|
||||||
|
|
||||||
void mqtt_on_connect(void);
|
void broker_on_connect(void);
|
||||||
|
|
||||||
void on_connect(struct mosquitto *client, void *obj, int rc)
|
void on_connect(struct mosquitto *client, void *obj, int rc)
|
||||||
{
|
{
|
||||||
@ -18,7 +18,7 @@ void on_connect(struct mosquitto *client, void *obj, int rc)
|
|||||||
|
|
||||||
puts("Connected to " MQTT_IP);
|
puts("Connected to " MQTT_IP);
|
||||||
|
|
||||||
mqtt_on_connect();
|
broker_on_connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
|
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
|
@ -3,3 +3,7 @@
|
|||||||
#define MQTT_USER "user"
|
#define MQTT_USER "user"
|
||||||
#define MQTT_PASSWORD "password"
|
#define MQTT_PASSWORD "password"
|
||||||
|
|
||||||
|
#define AMQP_IP "127.0.0.1"
|
||||||
|
#define AMQP_PORT 5672
|
||||||
|
#define AMQP_USER "user"
|
||||||
|
#define AMQP_PASSWORD "password"
|
||||||
|
60
iot/devices/display.c
Normal file
60
iot/devices/display.c
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
#include <linux/i2c-dev.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <sys/ioctl.h>
|
||||||
|
#include <i2c/smbus.h>
|
||||||
|
|
||||||
|
#include "display.h"
|
||||||
|
|
||||||
|
#define JHD1313_BUS "/dev/i2c-2"
|
||||||
|
#define JHD1313_ADR 0x3e
|
||||||
|
|
||||||
|
void display_set_cursor_pos(display_handle_t display, int x, int y)
|
||||||
|
{
|
||||||
|
i2c_smbus_write_byte_data(display, 0x00, (y ? 0xC0 : 0x80) + x);
|
||||||
|
}
|
||||||
|
|
||||||
|
void display_write_str(display_handle_t display, char *str)
|
||||||
|
{
|
||||||
|
while (*str) {
|
||||||
|
display_write_char(display, *str);
|
||||||
|
str++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void display_write_char(display_handle_t display, char ch)
|
||||||
|
{
|
||||||
|
i2c_smbus_write_byte_data(display, 0x40, ch);
|
||||||
|
}
|
||||||
|
|
||||||
|
display_handle_t init_display()
|
||||||
|
{
|
||||||
|
int file = open(JHD1313_BUS, O_RDWR);
|
||||||
|
|
||||||
|
if (file < 0) {
|
||||||
|
perror("Error opening display device");
|
||||||
|
exit(EXIT_FAILURE);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ioctl(file, I2C_SLAVE, JHD1313_ADR) == -1) {
|
||||||
|
fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", JHD1313_ADR, JHD1313_BUS, strerror(errno));
|
||||||
|
exit(EXIT_FAILURE);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2 line mode, 5x8
|
||||||
|
i2c_smbus_write_byte_data(file, 0x00, 0x28);
|
||||||
|
// Display on, cursor on, blink off
|
||||||
|
i2c_smbus_write_byte_data(file, 0x00, 0x0C);
|
||||||
|
// Display clear
|
||||||
|
i2c_smbus_write_byte_data(file, 0x00, 0x01);
|
||||||
|
// Entry mode set
|
||||||
|
i2c_smbus_write_byte_data(file, 0x00, 0x06);
|
||||||
|
|
||||||
|
i2c_smbus_write_byte_data(file, 0x00, 0x02);
|
||||||
|
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
10
iot/devices/display.h
Normal file
10
iot/devices/display.h
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
typedef int display_handle_t;
|
||||||
|
|
||||||
|
display_handle_t init_display();
|
||||||
|
|
||||||
|
void display_set_cursor_pos(display_handle_t display, int x, int y);
|
||||||
|
|
||||||
|
void display_write_str(display_handle_t display, char *str);
|
||||||
|
|
||||||
|
void display_write_char(display_handle_t display, char ch);
|
||||||
|
|
@ -11,8 +11,10 @@
|
|||||||
|
|
||||||
#include "temperature.h"
|
#include "temperature.h"
|
||||||
|
|
||||||
#define MPC9808_BUS "/dev/i2c-2"
|
#define MCP9808_BUS "/dev/i2c-2"
|
||||||
#define MPC9808_ADR 0x18
|
#define MCP9808_ADR 0x18
|
||||||
|
#define MCP9808_MANID 0x0054
|
||||||
|
#define MCP9808_DEVID 0x04
|
||||||
|
|
||||||
#define CONFIG_REG 0x01
|
#define CONFIG_REG 0x01
|
||||||
#define TUPPER_REG 0x02
|
#define TUPPER_REG 0x02
|
||||||
@ -53,16 +55,16 @@ double get_temperature(temperature_handle_t file)
|
|||||||
|
|
||||||
temperature_handle_t init_temperature(void)
|
temperature_handle_t init_temperature(void)
|
||||||
{
|
{
|
||||||
int file = open(MPC9808_BUS, O_RDWR);
|
int file = open(MCP9808_BUS, O_RDWR);
|
||||||
|
|
||||||
if (file < 0) {
|
if (file < 0) {
|
||||||
fprintf(stderr, "Error opening temperature sensor device (%s): %s\n", MPC9808_BUS, strerror(errno));
|
perror("Error opening temperature sensor device");
|
||||||
exit(1);
|
exit(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ioctl(file, I2C_SLAVE, MPC9808_ADR) == -1) {
|
if (ioctl(file, I2C_SLAVE, MCP9808_ADR) == -1) {
|
||||||
fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", MPC9808_ADR, MPC9808_BUS, strerror(errno));
|
fprintf(stderr, "ERROR: setting address %d on i2c bus %s with ioctl() - %s", MCP9808_ADR, MCP9808_BUS, strerror(errno));
|
||||||
exit(1);
|
exit(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
|
|
||||||
int32_t reg32;
|
int32_t reg32;
|
||||||
@ -73,23 +75,23 @@ temperature_handle_t init_temperature(void)
|
|||||||
reg32 = i2c_smbus_read_word_data(file, MANID_REG);
|
reg32 = i2c_smbus_read_word_data(file, MANID_REG);
|
||||||
|
|
||||||
if (reg32 < 0) {
|
if (reg32 < 0) {
|
||||||
fprintf(stderr, "ERROR: Read failed on i2c bus register %d - %s\n", MANID_REG,strerror(errno));
|
fprintf(stderr, "Read failed on i2c bus register %d: %s\n", MANID_REG, strerror(errno));
|
||||||
exit(1);
|
exit(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
if (bswap_16(reg16poi[0]) != 0x0054) {
|
if (bswap_16(reg16poi[0]) != MCP9808_MANID) {
|
||||||
fprintf(stderr, "Manufactorer ID wrong is 0x%x should be 0x54\n",__bswap_16(reg16poi[0]));
|
fprintf(stderr, "Invalid manufacturer ID: Expected 0x%x, got 0x%x\n", MCP9808_MANID, __bswap_16(reg16poi[0]));
|
||||||
exit(1);
|
exit(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read device ID and revision
|
// Read device ID and revision
|
||||||
reg32 = i2c_smbus_read_word_data(file, DEVID_REG);
|
reg32 = i2c_smbus_read_word_data(file, DEVID_REG);
|
||||||
if (reg32 < 0) {
|
if (reg32 < 0) {
|
||||||
fprintf(stderr, "ERROR: Read failed on i2c bus register %d - %s\n", DEVID_REG,strerror(errno) );
|
fprintf(stderr, "Read failed on i2c bus register %d - %s\n", DEVID_REG, strerror(errno));
|
||||||
exit(1);
|
exit(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
if (reg8poi[0] != 0x04) {
|
if (reg8poi[0] != MCP9808_DEVID) {
|
||||||
fprintf(stderr, "Manufactorer ID OK but device ID wrong is 0x%x should be 0x4\n",reg8poi[0]);
|
fprintf(stderr, "Invalid device ID - expected 0x%x, got 0x%x\n", MCP9808_DEVID, reg8poi[0]);
|
||||||
exit(1);
|
exit(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
|
|
||||||
return file;
|
return file;
|
29
iot/main.c
29
iot/main.c
@ -6,8 +6,9 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
|
|
||||||
#include "mqtt.h"
|
#include "brokers/amqp.h"
|
||||||
#include "temperature.h"
|
#include "devices/temperature.h"
|
||||||
|
#include "devices/display.h"
|
||||||
#include "device_id.h"
|
#include "device_id.h"
|
||||||
|
|
||||||
void *watch_temperature(void *arg)
|
void *watch_temperature(void *arg)
|
||||||
@ -16,14 +17,21 @@ void *watch_temperature(void *arg)
|
|||||||
|
|
||||||
printf("Device ID: %s\n", device_id);
|
printf("Device ID: %s\n", device_id);
|
||||||
|
|
||||||
temperature_handle_t temp_handle = init_temperature();
|
display_handle_t display = init_display();
|
||||||
|
display_write_str(display, " ");
|
||||||
|
display_set_cursor_pos(display, 0, 1);
|
||||||
|
display_write_str(display, "Device.....");
|
||||||
|
display_write_str(display, device_id);
|
||||||
|
|
||||||
|
temperature_handle_t temp_handle = init_temperature();
|
||||||
get_temperature(temp_handle);
|
get_temperature(temp_handle);
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
|
// Retrieve data
|
||||||
double temperature = get_temperature(temp_handle);
|
double temperature = get_temperature(temp_handle);
|
||||||
size_t timestamp = time(NULL);
|
size_t timestamp = time(NULL);
|
||||||
|
|
||||||
|
// Send JSON
|
||||||
char *format = "{"
|
char *format = "{"
|
||||||
"\"temperature\": %lf,"
|
"\"temperature\": %lf,"
|
||||||
"\"device_id\": \"%s\","
|
"\"device_id\": \"%s\","
|
||||||
@ -33,7 +41,16 @@ void *watch_temperature(void *arg)
|
|||||||
char *str = malloc(snprintf(NULL, 0, format, temperature, device_id, timestamp) + 1);
|
char *str = malloc(snprintf(NULL, 0, format, temperature, device_id, timestamp) + 1);
|
||||||
sprintf(str, format, temperature, device_id, timestamp);
|
sprintf(str, format, temperature, device_id, timestamp);
|
||||||
|
|
||||||
mqtt_send_message("temperature", str);
|
amqp_send_message("temperature-logs", str);
|
||||||
|
|
||||||
|
free(str);
|
||||||
|
|
||||||
|
// Print on display
|
||||||
|
str = malloc(17);
|
||||||
|
sprintf(str, "===[ %.1lf\xDF" "C ]===", temperature);
|
||||||
|
|
||||||
|
display_set_cursor_pos(display, 0, 0);
|
||||||
|
display_write_str(display, str);
|
||||||
|
|
||||||
free(str);
|
free(str);
|
||||||
|
|
||||||
@ -47,7 +64,7 @@ void *watch_temperature(void *arg)
|
|||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
void mqtt_on_connect(void)
|
void broker_on_connect(void)
|
||||||
{
|
{
|
||||||
pthread_t temperature_thread;
|
pthread_t temperature_thread;
|
||||||
pthread_create(&temperature_thread, NULL, watch_temperature, NULL);
|
pthread_create(&temperature_thread, NULL, watch_temperature, NULL);
|
||||||
@ -57,7 +74,7 @@ int main(void)
|
|||||||
{
|
{
|
||||||
srand(time(NULL));
|
srand(time(NULL));
|
||||||
|
|
||||||
init_mqtt();
|
init_amqp();
|
||||||
|
|
||||||
return EXIT_SUCCESS;
|
return EXIT_SUCCESS;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user