Compare commits

...

87 Commits

Author SHA1 Message Date
Jeas0001
58ee243422 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-04-14 10:06:51 +02:00
Jeas0001
4c2dba1040 Uploaded forkert domainmodel men den rigtige var i rapporten 2025-04-14 10:06:25 +02:00
LilleBRG
a4ebdbc96c error mesasge on login pops up 2025-04-11 11:37:31 +02:00
LilleBRG
22c397aebb all entries on devicelist is now white background 2025-04-11 09:10:45 +02:00
LilleBRG
f76ca8f670 errormessages shown to user + updates to refreshtoken 2025-04-10 16:07:45 +02:00
Jeas0001
6b4445aa2f Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-04-10 12:22:26 +02:00
Jeas0001
d891cf86d5 Easier to see when a message is recieved 2025-04-10 12:22:14 +02:00
LilleBRG
9aae80cb73 fixed add device endpoint 2025-04-10 12:13:31 +02:00
LilleBRG
6f6f53f3cd login dosent send you to home when login failed 2025-04-10 11:27:18 +02:00
c6dad9b3f1
Ignore if temperature is above 200 2025-04-09 13:25:45 +02:00
98928c552e
Add note to readme 2025-04-09 12:19:55 +02:00
597602ad2c
Add appsettings example file 2025-04-09 10:24:48 +02:00
6add0412c3
Add documentation to readme 2025-04-09 10:22:05 +02:00
d25b72c3db
Fix changing password in frontend 2025-04-09 09:43:52 +02:00
2e5334001f
Remove test folder 2025-04-08 14:14:58 +02:00
Jeas0001
72a809f7ae Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-04-08 14:08:30 +02:00
Jeas0001
e60425e3c4 Chart resizes with window size now 2025-04-08 14:08:19 +02:00
9a04cf14ac
Use fanout exchange for receiving temperature updates 2025-04-08 13:55:14 +02:00
Jeas0001
0d77807d56 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-04-08 11:22:11 +02:00
Jeas0001
08623ef65d Devices no longer show object object for temperature and date but actual values that match our chart 2025-04-08 11:21:26 +02:00
50a83145a6
Fix publishing of AMQP message to the correct exchange 2025-04-08 11:06:46 +02:00
LilleBRG
4cd3a60f20 fixed nameErrors 2025-04-08 11:05:48 +02:00
e002d07187
Fix error when selecting all time 2025-04-08 10:32:51 +02:00
Jeas0001
07230e1ef3 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-04-08 10:32:11 +02:00
Jeas0001
f35aeb592b Fix for chrome browser showing time 2025-04-08 10:32:03 +02:00
2a7ccc7e5f
Make device selector work, fix x-axis 2025-04-08 10:15:41 +02:00
1fad48b7d8
Receive min/max temperature on iot device 2025-04-07 13:30:39 +02:00
LilleBRG
4be7977c11 refreshtoken implemented, i think? 2025-04-07 13:16:48 +02:00
Jeas0001
1f372355d4 Publish automatisk ved edit af temphigh og low 2025-04-07 10:00:57 +02:00
LilleBRG
fd1b4ace5d cannot submit device edits without changing input values 2025-04-04 12:16:53 +02:00
4bf539963a
Small fixes to iot code 2025-04-04 11:22:45 +02:00
48c621f1de
Implement buzzer alarm 2025-04-04 10:14:24 +02:00
LilleBRG
c91aa4b278 device and profile works with changed structure 2025-04-03 17:29:51 +02:00
LilleBRG
c1fbebe0da Merge branches 'master', 'master' and 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-04-03 14:37:07 +02:00
LilleBRG
0c9cd6349c device crud works 2025-04-03 14:35:45 +02:00
9eaba2e77a
Use local timezone on dashboard 2025-04-03 14:09:54 +02:00
Jeas0001
a4f205290d Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-04-03 09:29:31 +02:00
Jeas0001
5dd2a5ec1d Removed temperaturelogs from being a dbset and made it so you can the correct logs from the datetimerange 2025-04-03 09:29:11 +02:00
ea485813fe
Fix device dropdown and chart units 2025-04-03 09:25:33 +02:00
eb66edb902
Fix Chrome issues 2025-04-02 13:48:59 +02:00
b390d4a108
Optimize query to fetch logs within date period 2025-04-02 13:36:51 +02:00
9686e27ba3
Fix not being able to fetch logs in a specific period 2025-04-02 13:16:17 +02:00
59c78e5eac
Fix device list and table duplication 2025-04-02 13:09:46 +02:00
4f9ecfb43d
Add period selector 2025-04-02 12:24:27 +02:00
3d014eab96
Add device dropdown 2025-04-02 09:33:53 +02:00
2516b2b086
Implement pagination in table 2025-04-02 08:58:30 +02:00
LilleBRG
f1b3c39c02 almost done with devices 2025-04-01 14:49:51 +02:00
28cffcfb42
Fix data decimation 2025-04-01 13:50:55 +02:00
96fe8a4cdf
Redirect to dashboard when accessing frontpage while logged in 2025-04-01 13:50:55 +02:00
0c532fb979
Redirect to login when not authenticated 2025-04-01 13:50:55 +02:00
LilleBRG
9529d2cdc8 renamed model folder 2025-04-01 13:15:25 +02:00
82efeff40b
Limit table to 50 rows 2025-04-01 12:50:19 +02:00
9c35f257c5
Enable data decimation 2025-04-01 12:39:53 +02:00
a12784934b
Get device list for dashboard and upgrade chart.js 2025-04-01 12:27:57 +02:00
LilleBRG
49c9a5a792 profile update and password update fixed 2025-04-01 10:30:59 +02:00
c42d2e3c16
Fix logout 2025-04-01 09:05:05 +02:00
LilleBRG
c9155d582b no errors after merge. update database please 2025-03-31 15:49:35 +02:00
LilleBRG
db023ac84e Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-31 14:49:34 +02:00
Jeas0001
1ca64702d7 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-31 11:16:29 +02:00
Jeas0001
6cb36947cb Made the datetime optional 2025-03-31 11:16:16 +02:00
fb3705690d
Don't send undefined content type in frontend 2025-03-31 11:03:38 +02:00
e2dd9d9e6e
Fix cookie path 2025-03-31 11:00:20 +02:00
Jeas0001
668b29c068 Undid last commit from me 2025-03-31 10:50:21 +02:00
Jeas0001
d9205d425c Datetime ranged have any logs 2025-03-31 10:48:20 +02:00
fe85e1ff23
Add JS constants to gitignore 2025-03-31 10:42:23 +02:00
Jeas0001
7a3d5b4f71 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-31 10:39:35 +02:00
Jeas0001
9dc19efd83 Removed unnessesary usings and added a datetimerange for getting logs 2025-03-31 10:39:07 +02:00
6fe0841cbc
Add error handling on dashboard 2025-03-31 10:31:57 +02:00
df130b312c
Style dashboard 2025-03-31 10:20:26 +02:00
dd2a3cf150
Show real temperature data in frontend 2025-03-31 09:30:08 +02:00
Jeas0001
f6e2c8f450 Gets userId from the jwttoken 2025-03-31 09:19:50 +02:00
b8bb86edca
Fix JWT bearer authentication 2025-03-27 10:47:31 +01:00
Jeas0001
595ade2d79 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-27 10:37:25 +01:00
02bfbabcfc
Set auth token when logging in 2025-03-27 10:33:40 +01:00
0f1b10d2d7
Change how requests are sent in order to send auth token 2025-03-27 10:33:40 +01:00
Jeas0001
8ad863b781 Added securityDefinition and requirements 2025-03-27 10:22:46 +01:00
Jeas0001
46de83dc42 RefreshToken is made 2025-03-27 10:17:25 +01:00
Jeas0001
edc195b234 Fixed AMQPPublish and split the code into more functions and added Refresh token to Usermodel 2025-03-27 09:48:08 +01:00
Jeas0001
bce48fe8d1 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-26 14:28:30 +01:00
Jeas0001
998cb90acc Changed the name of the publisher 2025-03-26 14:28:20 +01:00
Jeas0001
47797d18a0 Made AMQPPush for pushing the device limits to RabbitMQ and consume after 1 hour 2025-03-26 13:14:12 +01:00
Jeas0001
6f311fabd4 Comments 2025-03-26 12:14:42 +01:00
2f5f753ab6
Implement printing temperature on display 2025-03-26 09:59:25 +01:00
Jeas0001
60c0fc9475 Merge branch 'master' of git.reim.ar:ReiMerc/temperature-alarm 2025-03-25 13:15:52 +01:00
Jeas0001
507e156f17 Some comment in AMQPReciever, AMQPReciever and DBAccess 2025-03-25 13:15:42 +01:00
90cbf7ae81
Fix listening for AMQP messages, remove test console app 2025-03-25 12:54:52 +01:00
8c6037b010
Implement AMQP in IoT 2025-03-25 12:30:53 +01:00
87 changed files with 2884 additions and 1037 deletions

View File

@ -1,2 +1,43 @@
# Temperature Alarm
![Picture of the BeagleBone](docs/img/beaglebone_small.jpg)
![Screenshot of the dashboard](docs/img/dashboard_small.png)
## Setup
In the `backend/Api` folder, copy `appsettings.example.json` into `appsettings.json` and fill out the values.
In the `frontend` folder, copy `shared/constants.example.js` into `shared/constants.js` and fill out the values.
In the `iot` folder, copy `config.example.h` into `config.h` and fill out the values.
## Running
To run the backend, type `dotnet run` within the `backend/Api` folder. Make sure you have the .NET 8 SDK installed.
The frontend should just be hosted with a static web server. To run locally, you may e.g. use PHP: `php -S 0.0.0.0:80`
The IoT code should be run on a BeagleBone Black with:
- A Grove Base Cape, set to 5V
- A JHD1313 Grove-LCD RGB Backlight display in one of the I2C\_2 ports
- An MCP9808 Grove High Accuracy Temperature Sensor in one of the I2C\_2 ports
- A Grove Buzzer in the GPIO\_51 port
The following library packages are required by the IoT code and should be installed on the BeagleBone:
`apt install libmosquitto-dev librabbitmq-dev libi2c-dev libgpiod-dev libcjson-dev`
> [!NOTE]
> The gpiod library must be below version 2.0. Debian Bookworm still distributes the old version of the library.
> [!NOTE]
> The RabbitMQ apt package is missing the header files - They can be copied from [here](https://github.com/alanxz/rabbitmq-c/tree/master/include/rabbitmq-c) into the `/usr/include/rabbitmq-c` folder
Copy the source files onto the BeagleBone and run the following command to compile and run the code:
`make && ./a.out`
To run in the background, a program such as GNU Screen can be used.

View File

@ -0,0 +1,78 @@
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 IConnection _conn;
private IChannel _channel;
private ConnectionFactory _factory;
private string _queue;
public AMQPPublisher(IConfiguration configuration)
{
_configuration = configuration;
_factory = new ConnectionFactory();
_queue = "temperature-limits";
InitFactory();
}
public async void Handle_Push_Device_Limits(DeviceLimit deviceLimit)
{
// Connecting to rabbitMQ
await Connect();
string message = JsonSerializer.Serialize(deviceLimit);
var body = Encoding.UTF8.GetBytes(message);
await _channel.BasicPublishAsync(exchange: _queue, routingKey: _queue, body: body);
// Short delay before disconnecting from rabbitMQ
await Task.Delay(1000);
// Disconnecting from rabbitMQ to save resources
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: true, exclusive: false, autoDelete: false);
Console.WriteLine($"{_queue} connected");
return true;
}
// The info for the factory
private void InitFactory()
{
_factory.UserName = _configuration["AMQP:username"];
_factory.Password = _configuration["AMQP:password"];
_factory.HostName = _configuration["AMQP:host"];
_factory.Port = Convert.ToInt32(_configuration["AMQP:port"]);
}
}
}

View File

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

View File

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

View File

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

View File

@ -1,7 +1,8 @@
using Api.DBAccess;
using Api.Models;
using Api.Models.Devices;
using Microsoft.AspNetCore.Mvc;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Api.AMQP;
namespace Api.BusinessLogic
{
@ -16,57 +17,135 @@ namespace Api.BusinessLogic
_configuration = configuration;
}
/// <summary>
/// Gets the user from dbaccess using the userId and checks if the user exists
/// Gets all devices that match the userId and checks if there are any devices connected to the user
/// </summary>
/// <param name="userId">UserId that matches a user that owns the devices</param>
/// <returns>returns the devices in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> GetDevices(int userId)
{
var profile = await _dbAccess.ReadUser(userId);
var userDetails = await _dbAccess.ReadUserDetails(userId);
if (profile == null) { return new ConflictObjectResult(new { message = "Could not find user" }); }
if (userDetails.Devices.Count == 0) { return new ConflictObjectResult(new { message = "Could not find any devices connected to the user" }); }
var devices = await _dbAccess.ReadDevices(userId);
if (devices.Count == 0) { return new ConflictObjectResult(new { message = "Could not find any devices connected to the user" }); }
List<GetDeviceDTO> devices = new List<GetDeviceDTO>();
foreach (var item in userDetails.Devices)
{
var latestLog = item.Logs?.OrderByDescending(log => log.Date).FirstOrDefault(); // Get the latest log
GetDeviceDTO device = new GetDeviceDTO
{
Id = item.Id,
Name = item.Name,
TempHigh = item.TempHigh,
TempLow = item.TempLow,
ReferenceId = item.ReferenceId,
LatestLog = latestLog
};
devices.Add(device);
}
return new OkObjectResult(devices);
}
/// <summary>
/// Checks if the user that the device is trying to be added to exists
/// Then it is send to dbaccess
/// </summary>
/// <param name="device">The new device</param>
/// <param name="userId">The user that owns the device</param>
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> AddDevice(string referenceId, int userId)
{
var profile = await _dbAccess.ReadUser(userId);
if (profile == null) { return new ConflictObjectResult(new { message = "Could not find user" }); }
var user = await _dbAccess.ReadUserDetails(userId);
var possibleDevice = _dbAccess.ReadDevice(referenceId);
if (possibleDevice != null) { return new ConflictObjectResult(new { message = "Device with given referenceId already exists" }); }
if (user == null) { return new ConflictObjectResult(new { message = "Could not find user" }); }
Device device = new Device
{
Name = "Undefined",
TempHigh = 0,
TempLow = 0,
TempHigh = 100,
TempLow = -40,
ReferenceId = referenceId,
Logs = new List<TemperatureLogs>(),
};
DeviceLimit deviceLimit = new DeviceLimit();
deviceLimit.TempHigh = device.TempHigh;
deviceLimit.TempLow = device.TempLow;
deviceLimit.ReferenceId = device.ReferenceId;
AMQPPublisher publisher = new AMQPPublisher(_configuration);
publisher.Handle_Push_Device_Limits(deviceLimit);
return await _dbAccess.CreateDevice(device, userId);
user.Devices.Add(device);
return await _dbAccess.CreateDevice(user);
}
public async Task<IActionResult> GetLogs(int deviceId)
/// <summary>
/// Checks if the deviceId matches a device
/// </summary>
/// <param name="device">The updated info</param>
/// <param name="deviceId">The device to be edited</param>
/// <returns>returns the updated device in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> EditDevice(UpdateDeviceRequest request, int deviceId)
{
var device = await _dbAccess.ReadDevice(deviceId);
if (device != null)
{
if (device.Name == "" || device.Name == null)
return new ConflictObjectResult(new { message = "Please enter a name" });
device.Name = request.Name;
device.TempLow = request.TempLow;
device.TempHigh = request.TempHigh;
DeviceLimit deviceLimit = new DeviceLimit();
deviceLimit.TempHigh = device.TempHigh;
deviceLimit.TempLow = device.TempLow;
deviceLimit.ReferenceId = device.ReferenceId;
AMQPPublisher publisher = new AMQPPublisher(_configuration);
publisher.Handle_Push_Device_Limits(deviceLimit);
}
return await _dbAccess.UpdateDevice(device);
}
/// <summary>
/// deletes a device
/// </summary>
/// <param name="referenceId">the id used to delete</param>
/// <param name="userId">Used for deleting device from devices list in user</param>
/// <returns>returns OK</returns>
public async Task<IActionResult> DeleteDevice(int deviceId)
{
var device = await _dbAccess.ReadDevice(deviceId);
if (device != null)
{
return await _dbAccess.DeleteDevice(device);
}
return new ConflictObjectResult(new { message = "Invalid user" });
}
/// <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);
if (device == null) { return new ConflictObjectResult(new { message = "Could not find device" }); }
var logs = await _dbAccess.ReadLogs(deviceId);
if (logs.Count == 0) { return new ConflictObjectResult(new { message = "Could not find any logs connected to the device" }); }
var logs = await _dbAccess.ReadLogs(deviceId, dateTimeRange);
return new OkObjectResult(logs);
}
public async Task<IActionResult> EditDevice(Device device, int deviceId)
{
var device1 = _dbAccess.ReadDevice(deviceId);
if (device1 == null) { return new ConflictObjectResult(new { message = "Could not find device" }); }
return await _dbAccess.UpdateDevice(device, deviceId);
}
}
}

View File

@ -1,14 +1,17 @@
using Api.DBAccess;
using Api.Models;
using Api.Models.User;
using Api.Models.Devices;
using Api.Models.Users;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Api.BusinessLogic
{
@ -25,40 +28,71 @@ namespace Api.BusinessLogic
public async Task<IActionResult> getUser(int userId)
{
User user = await _dbAccess.getUser(userId);
User user = await _dbAccess.ReadUser(userId);
if (user == null || user.Id == 0) { return new ConflictObjectResult(new { message = "Could not find user" }); }
return new OkObjectResult(new { user.Id, user.UserName, user.Email });
}
public async Task<IActionResult> RegisterUser(User user)
/// <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(CreateUserRequest request)
{
if (!new Regex(@".+@.+\..+").IsMatch(user.Email))
if (!new Regex(@".+@.+\..+").IsMatch(request.Email))
{
return new ConflictObjectResult(new { message = "Invalid email address" });
}
if (!PasswordSecurity(user.Password))
if (!PasswordSecurity(request.Password))
{
return new ConflictObjectResult(new { message = "Password is not up to the security standard" });
}
if (user.Devices == null)
var users = await _dbAccess.ReadAllUsers();
foreach (var item in users)
{
user.Devices = new List<Device>();
if (item.UserName == request.UserName)
{
return new ConflictObjectResult(new { message = "Username is already in use." });
}
if (item.Email == request.Email)
{
return new ConflictObjectResult(new { message = "Email is being used already" });
}
}
string salt = Guid.NewGuid().ToString();
string hashedPassword = ComputeHash(user.Password, SHA256.Create(), salt);
user.Salt = salt;
user.Password = hashedPassword;
string hashedPassword = ComputeHash(request.Password, SHA256.Create(), salt);
User user = new User
{
UserName = request.UserName,
Email = request.Email,
Password = hashedPassword,
Salt = salt,
Devices = new List<Device>()
};
return await _dbAccess.CreateUser(user);
}
/// <summary>
/// Gets the user that matches the login
/// Hashes the login password with the users salt
/// checks if the hashed password that the login has is the same as the one saved in the database
/// </summary>
/// <param name="login">Has a username or email and a password</param>
/// <returns>Returns a jwt token, username and userid</returns>
public async Task<IActionResult> Login(Login login)
{
User user = await _dbAccess.Login(login);
User user = await _dbAccess.ReadUserForLogin(login.EmailOrUsrn);
if (user == null || user.Id == 0) { return new ConflictObjectResult(new { message = "Could not find user" }); }
@ -67,20 +101,61 @@ namespace Api.BusinessLogic
if (user.Password == hashedPassword)
{
var token = GenerateJwtToken(user);
return new OkObjectResult(new { token, user.Id});
user = await UpdateRefreshToken(user);
return new OkObjectResult(new { token, user.UserName, user.Id, refreshToken = user.RefreshToken });
}
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(UpdateUserRequest userRequest, int userId)
{
return await _dbAccess.UpdateUser(userRequest, userId);
var profile = await _dbAccess.ReadUser(userId);
var users = await _dbAccess.ReadAllUsers();
if (profile == null) { return new ConflictObjectResult(new { message = "User does not exist" }); }
foreach (var item in users)
{
if (item.UserName == userRequest.UserName && userId != item.Id)
{
return new ConflictObjectResult(new { message = "Username is already in use." });
}
if (item.Email == userRequest.Email && userId != item.Id)
{
return new ConflictObjectResult(new { message = "Email is being used already" });
}
}
if (userRequest.Email == "" || userRequest.Email == null)
return new ConflictObjectResult(new { message = "Please enter an email" });
if (userRequest.UserName == "" || userRequest.UserName == null)
return new ConflictObjectResult(new { message = "Please enter a username" });
profile.Email = userRequest.Email;
profile.UserName = userRequest.UserName;
return await _dbAccess.UpdateUser(profile);
}
public async Task<IActionResult> changePassword(ChangePasswordRequest passwordRequest, int userId)
{
var user = await _dbAccess.ReadUser(userId);
if (user == null) { return new ConflictObjectResult(new { message = "User does not exist" }); }
string hashedPassword = ComputeHash(passwordRequest.OldPassword, SHA256.Create(), user.Salt);
@ -96,15 +171,44 @@ namespace Api.BusinessLogic
}
string hashedNewPassword = ComputeHash(passwordRequest.NewPassword, SHA256.Create(), user.Salt);
user.Password = hashedNewPassword;
return await _dbAccess.updatePassword(hashedNewPassword, userId);
return await _dbAccess.UpdatePassword(user);
}
/// <summary>
/// Just sends the userid of the user that is to be deleted
/// </summary>
/// <param name="userId">The Id of the user that is to be deleted</param>
/// <returns>returns the true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> DeleteUser(int userId)
{
return await _dbAccess.DeleteUser(userId);
var user = await _dbAccess.ReadUserDetails(userId);
if (user != null)
{
return await _dbAccess.DeleteUser(user);
}
return new ConflictObjectResult(new { message = "Invalid user" });
}
public async Task<IActionResult> RefreshToken(string refreshToken)
{
User user = await _dbAccess.ReadUserByRefreshToken(refreshToken);
if (user == null) { return new ConflictObjectResult(new { message = "Could not match refreshtoken" }); }
user = await UpdateRefreshToken(user);
string jwtToken = GenerateJwtToken(user);
return new OkObjectResult(new { token = jwtToken, refreshToken = user.RefreshToken });
}
/// <summary>
/// Generates a hash from a salt and input using the algorithm that is provided
/// </summary>
/// <param name="input">This is the input that is supposed to be hashed</param>
/// <param name="algorithm">This is the alogorithm that is used to encrypt the input</param>
/// <param name="salt">This is something extra added to make the hashed input more unpredictable</param>
/// <returns>The hashed input</returns>
private static string ComputeHash(string input, HashAlgorithm algorithm, string salt)
{
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
@ -120,6 +224,11 @@ namespace Api.BusinessLogic
return BitConverter.ToString(hashedBytes);
}
/// <summary>
/// Checks if password is up to our security standard
/// </summary>
/// <param name="password">The password that is to be checked</param>
/// <returns>true or false dependeing on if the password is up to standard</returns>
public bool PasswordSecurity(string password)
{
var hasMinimum8Chars = new Regex(@".{8,}");
@ -127,6 +236,11 @@ namespace Api.BusinessLogic
return hasMinimum8Chars.IsMatch(password);
}
/// <summary>
/// Generates a JWT token that last 2 hours
/// </summary>
/// <param name="user">Used for sending the userid and username with the token</param>
/// <returns>Returns a valid JWTToken</returns>
private string GenerateJwtToken(User user)
{
var claims = new[]
@ -144,10 +258,18 @@ namespace Api.BusinessLogic
_configuration["JwtSettings:Issuer"],
_configuration["JwtSettings:Audience"],
claims,
expires: DateTime.Now.AddMinutes(30),
expires: DateTime.Now.AddHours(1),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
private async Task<User> UpdateRefreshToken(User user)
{
user.RefreshToken = Guid.NewGuid().ToString();
user.RefreshTokenExpiresAt = DateTime.Now.AddDays(30);
await _dbAccess.UpdateUser(user);
return user;
}
}
}

View File

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

View File

@ -14,10 +14,10 @@ namespace Api.Controllers
_dbAccess = dbAccess;
}
[HttpGet("API")]
[HttpGet("api")]
public async Task<IActionResult> HealthAPI() { return Ok(true); }
[HttpGet("DB")]
[HttpGet("db")]
public async Task<IActionResult> HealthDB() { return Ok(_dbAccess.Test()); }
}
}

View File

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

View File

@ -1,13 +1,13 @@
using Microsoft.EntityFrameworkCore;
using Api.Models;
using System.Text;
using System.Runtime.Intrinsics.Arm;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Api.Models.User;
using Api.Models.Devices;
using Api.Models.Users;
using Microsoft.AspNetCore.Http.HttpResults;
using System.Collections.Generic;
//All EF Core database calls
namespace Api.DBAccess
{
public class DbAccess
@ -18,202 +18,195 @@ namespace Api.DBAccess
{
_context = context;
}
public async Task<User> getUser(int userId)
{
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
}
public async Task<IActionResult> CreateUser(User user)
{
var users = await _context.Users.ToListAsync();
foreach (var item in users)
{
if (item.UserName == user.UserName)
{
return new ConflictObjectResult(new { message = "Username is already in use." });
}
if (item.Email == user.Email)
{
return new ConflictObjectResult(new { message = "Email is being used already" });
}
}
_context.Users.Add(user);
bool saved = await _context.SaveChangesAsync() == 1;
if (saved) { return new OkObjectResult(true); }
return new ConflictObjectResult(new { message = "Could not save to databse" });
}
public async Task<User> Login(Login login)
{
User user = new User();
if (!login.EmailOrUsrn.Contains("@"))
{
user = await _context.Users.FirstOrDefaultAsync(u => u.UserName == login.EmailOrUsrn);
}
else
{
user = await _context.Users.FirstOrDefaultAsync(u => u.Email == login.EmailOrUsrn);
}
if (user == null || user.Id == 0) { return new User(); }
return user;
}
/// <summary>
/// Gets one user on id
/// </summary>
/// <param name="userId">used to get the specific user</param>
/// <returns>returns a user object from the database based on the given id</returns>
public async Task<User> ReadUser(int userId)
{
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
}
public async Task<IActionResult> UpdateUser(EditUserRequest user, int userId)
public async Task<User> ReadUserDetails(int userId)
{
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
var users = await _context.Users.ToListAsync();
return await _context.Users
.Include(u => u.Devices)
.ThenInclude(u => u.Logs)
.FirstOrDefaultAsync(u => u.Id == userId);
}
if (profile == null) { return new ConflictObjectResult(new { message = "User does not exist" }); }
// Returns a user according to refreshToken
public async Task<User> ReadUserByRefreshToken(string refreshToken)
{
return await _context.Users.FirstOrDefaultAsync(u => u.RefreshToken == refreshToken);
}
foreach (var item in users)
/// <summary>
/// Used to check both email and login for the login.
/// </summary>
/// <param name="emailOrUsername">stores the input of username or email</param>
/// <returns>returns a user object from the database based on the given email or username</returns>
public async Task<User> ReadUserForLogin(string emailOrUsername)
{
if (emailOrUsername.Contains("@"))
{
if (item.UserName == user.UserName && userId != item.Id)
{
return new ConflictObjectResult(new { message = "Username is already in use." });
}
if (item.Email == user.Email && userId != item.Id)
{
return new ConflictObjectResult(new { message = "Email is being used already" });
}
return await _context.Users.FirstOrDefaultAsync(u => u.Email == emailOrUsername);
}
else
{
return await _context.Users.FirstOrDefaultAsync(u => u.UserName == emailOrUsername);
}
}
if(user.Email != "" && user.Email != null)
profile.Email = user.Email;
if (user.UserName != "" && user.UserName != null)
profile.UserName = user.UserName;
/// <summary>
/// Gets all users
/// </summary>
/// <returns>Return a list of users</returns>
public async Task<List<User>> ReadAllUsers()
{
return await _context.Users.ToListAsync();
}
/// <summary>
/// Creates a user
/// </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)
{
_context.Users.Add(user);
bool saved = await _context.SaveChangesAsync() == 1;
if (saved) { return new OkObjectResult(profile); }
if (saved) { return new OkObjectResult(true); }
return new ConflictObjectResult(new { message = "Could not save to database" });
}
/// <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)
{
_context.Entry(user).State = EntityState.Modified;
bool saved = await _context.SaveChangesAsync() == 1;
if (saved) { return new OkObjectResult(user);}
return new ConflictObjectResult(new { message = "Could not save to database" });
}
public async Task<IActionResult> UpdatePassword(User user)
{
_context.Entry(user).State = EntityState.Modified;
bool saved = await _context.SaveChangesAsync() == 1;
if (saved) { return new OkObjectResult(user); }
return new ConflictObjectResult(new { message = "Could not save to database" });
}
public async Task<IActionResult> updatePassword(string newPassword, int userId)
/// <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(User user)
{
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
if (profile == null) { return new ConflictObjectResult(new { message = "User does not exist" }); }
profile.Password = newPassword;
bool saved = await _context.SaveChangesAsync() == 1;
if (saved) { return new OkObjectResult(profile); }
return new ConflictObjectResult(new { message = "Could not save to database" });
}
public async Task<IActionResult> DeleteUser(int userId)
{
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
if (user != null)
{
if (user.Devices != null && user.Devices.Count > 0)
{
foreach (var item in user.Devices)
{
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.Id == item.Id);
if (device != null) { _context.Devices.Remove(device); }
}
}
_context.Users.Remove(user);
bool saved = await _context.SaveChangesAsync() >= 0;
if (saved) { return new OkObjectResult(saved); }
return new ConflictObjectResult(new { message = "Could not save to database" });
}
return new ConflictObjectResult(new { message = "Invalid user" });
}
public async Task<List<Device>> ReadDevices(int userId)
{
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
if (user == null || user.Devices == null) { return new List<Device>(); }
var devices = user.Devices;
return devices;
}
public async Task<IActionResult> CreateDevice(Device device, int userId)
{
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
if (user == null || user.Devices == null) { return new ConflictObjectResult(new { message = "User did not have a device list" }); }
if (device.Logs == null) { device.Logs = new List<TemperatureLogs>(); }
user.Devices.Add(device);
bool saved = await _context.SaveChangesAsync() == 1;
_context.Users.Remove(user);
bool saved = await _context.SaveChangesAsync() >= 0;
if (saved) { return new OkObjectResult(saved); }
return new ConflictObjectResult(new { message = "Could not save to database" });
}
// Returns all devices
public List<Device> ReadDevices()
{
return _context.Devices.ToList();
}
// Returns a device according to deviceId
public async Task<Device> ReadDevice(int deviceId)
{
return await _context.Devices.FirstOrDefaultAsync(d => d.Id == deviceId);
}
public Device ReadDevice(string refenreId)
// Returns a device according to referenceId
public Device ReadDevice(string referenceId)
{
return _context.Devices.FirstOrDefault(d => d.ReferenceId == refenreId);
return _context.Devices.FirstOrDefault(d => d.ReferenceId == referenceId);
}
public async Task<IActionResult> UpdateDevice(Device device, int deviceId)
/// <summary>
/// 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(User user)
{
var device1 = await _context.Devices.FirstOrDefaultAsync(u => u.Id == deviceId);
_context.Entry(user).State = EntityState.Modified;
if (device1 == null) { return new ConflictObjectResult(new { message = "Device does not exist" }); }
bool saved = await _context.SaveChangesAsync() == 2;
device1.TempLow = device.TempLow;
device1.TempHigh = device.TempHigh;
device1.ReferenceId = device.ReferenceId;
device1.Name = device.Name;
bool saved = await _context.SaveChangesAsync() == 1;
if (saved) { return new OkObjectResult(device1); }
if (saved) { return new OkObjectResult(user.Id); }
return new ConflictObjectResult(new { message = "Could not save to database" });
}
public async Task<List<TemperatureLogs>> ReadLogs(int deviceId)
/// <summary>
/// Updates a device in the database
/// </summary>
/// <param name="request">Contains the updated device info</param>
/// <param name="referenceId">Has the id for the device that is to be updated</param>
/// <returns>returns the updated device in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> UpdateDevice(Device device)
{
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.Id == deviceId);
_context.Entry(device).State = EntityState.Modified;
bool saved = await _context.SaveChangesAsync() == 1;
if (device == null || device.Logs == null) { return new List<TemperatureLogs>(); }
if (saved) { return new OkObjectResult(device); }
var logs = device.Logs;
return logs;
return new ConflictObjectResult(new { message = "Could not save to database" });
}
public async Task<IActionResult> DeleteDevice(Device device)
{
_context.Devices.Remove(device);
bool saved = await _context.SaveChangesAsync() >= 0;
if (saved) { return new OkObjectResult(saved); }
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>
/// <param name="range">Return only logs within the specified datetime range</param>
/// <returns></returns>
public async Task<List<TemperatureLogs>> ReadLogs(int deviceId, DateTimeRange range)
{
return _context.Devices.Include(d => d.Logs.Where(l => l.Date > range.DateTimeStart && l.Date < range.DateTimeEnd)).Where(d => d.Id == deviceId).FirstOrDefault().Logs;
}
/// <summary>
/// Creates a new log
/// </summary>
/// <param name="temperatureLogs">the new log</param>
/// <param name="referenceId">the referenceId that belongs too the device that recoded the log</param>
public async void CreateLog(TemperatureLogs temperatureLogs, string referenceId)
{
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.ReferenceId == referenceId);
@ -226,6 +219,7 @@ namespace Api.DBAccess
await _context.SaveChangesAsync();
}
// Does a health check on the database access
public async Task<bool> Test()
{
return _context.Database.CanConnect();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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("20250403144251_removeNullableLists")]
partial class removeNullableLists
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
modelBuilder.Entity("Api.Models.Devices.Device", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReferenceId")
.HasColumnType("TEXT");
b.Property<double>("TempHigh")
.HasColumnType("REAL");
b.Property<double>("TempLow")
.HasColumnType("REAL");
b.Property<int?>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Devices");
});
modelBuilder.Entity("Api.Models.TemperatureLogs", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("Date")
.HasColumnType("TEXT");
b.Property<int?>("DeviceId")
.HasColumnType("INTEGER");
b.Property<double>("TempHigh")
.HasColumnType("REAL");
b.Property<double>("TempLow")
.HasColumnType("REAL");
b.Property<double>("Temperature")
.HasColumnType("REAL");
b.HasKey("Id");
b.HasIndex("DeviceId");
b.ToTable("TemperatureLogs");
});
modelBuilder.Entity("Api.Models.Users.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("RefreshToken")
.HasColumnType("TEXT");
b.Property<DateTime>("RefreshTokenExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("Salt")
.HasColumnType("TEXT");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Api.Models.Devices.Device", b =>
{
b.HasOne("Api.Models.Users.User", null)
.WithMany("Devices")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Api.Models.TemperatureLogs", b =>
{
b.HasOne("Api.Models.Devices.Device", null)
.WithMany("Logs")
.HasForeignKey("DeviceId");
});
modelBuilder.Entity("Api.Models.Devices.Device", b =>
{
b.Navigation("Logs");
});
modelBuilder.Entity("Api.Models.Users.User", b =>
{
b.Navigation("Devices");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Api.Migrations
{
/// <inheritdoc />
public partial class removeNullableLists : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
namespace Api.Models
namespace Api.Models.Devices
{
public class Device
{
@ -12,6 +12,6 @@
public string? ReferenceId { get; set; }
public List<TemperatureLogs>? Logs { get; set; }
public List<TemperatureLogs> Logs { get; set; }
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,11 @@
namespace Api.Models.Users
{
public class CreateUserRequest
{
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,20 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Database": "Data Source=database.sqlite3"
},
"JwtSettings": {
"Issuer": "TemperatureAlarmApi",
"Audience": "Customers",
"Key": ""
}
}

View File

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

View File

@ -1,25 +0,0 @@

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

View File

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

View File

@ -1,36 +0,0 @@
using MQTTnet;
var mqttFactory = new MqttClientFactory();
IMqttClient mqttClient;
using (mqttClient = mqttFactory.CreateMqttClient())
{
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithTcpServer($"10.135.51.116", 1883)
.WithCredentials($"h5", $"Merc1234")
.WithCleanSession()
.Build();
// Setup message handling before connecting so that queued messages
// are also handled properly. When there is no event handler attached all
// received messages get lost.
mqttClient.ApplicationMessageReceivedAsync += e =>
{
Console.WriteLine("Received application message.");
return Task.CompletedTask;
};
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
Console.WriteLine("mqttClient");
//var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder().WithTopicTemplate(topic).Build();
await mqttClient.SubscribeAsync("temperature");
Console.WriteLine("MQTT client subscribed to topic.");
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 136 KiB

BIN
docs/img/beaglebone.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 498 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

BIN
docs/img/dashboard.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

2
frontend/.gitignore vendored Normal file
View File

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

View File

@ -5,40 +5,46 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Temperature-Alarm-Web</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/luxon"></script>
<link rel="stylesheet" href="/styles/common.css">
<link rel="stylesheet" href="/styles/auth.css">
<link rel="stylesheet" href="/styles/devices.css" />
<script defer type="module" src="/scripts/devices.js"></script>
<script defer type="module" src="/shared/utils.js"></script>
</head>
<body>
<div id="container">
<div class="topnav">
<a href="/home/index.html">Home</a>
<a class="active" href="/devices/index.html">Devices</a>
<div style="display: flex; justify-content: flex-end;">
<a href="/profile/index.html">Profile</a>
<span class="logoutContainer">
<img class="logout" src="/img/logout.png">
</span>
</div>
</div>
<div class="topnav">
<a href="/home/index.html">Home</a>
<div style="display: flex; justify-content: flex-end;">
<a class="active" href="/devices">Devices</a>
<a href="/profile">Profile</a>
<span class="logout-container">
<img class="logout" src="/img/logout.png">
</span>
</div>
</div>
<div class="addDeviceContainer">
<button id="addDevice">Add Device</button>
</div>
<div class="tableConatiner">
<table>
<tr>
<th>Id</th>
<th>Placement(name)</th>
<th>Set Temp High</th>
<th>Set Temp Low</th>
<th>Latest Meassurement</th>
<th></th>
</tr>
<tbody id="deviceTable"></tbody>
</table>
<div style="display: flex; justify-content: center;">
<div class="tableConatiner">
<table>
<thead>
<tr>
<th>Id</th>
<th>Placement(name)</th>
<th>Set Temp High</th>
<th>Set Temp Low</th>
<th>Latest Meassurement</th>
<th></th>
</tr>
</thead>
<tbody id="deviceTable"></tbody>
</table>
</div>
</div>
<div id="get-error" class="error"></div>
</div>
@ -52,6 +58,7 @@
<button type="button" class="cancelbtn">Cancel</button>
<button type="button" id="deletebtn">Delete</button>
</div>
<div id="delete-error" class="error"></div>
</div>
</form>
</div>
@ -66,18 +73,18 @@
<input type="text" placeholder="Enter a name for the placement" id="name" required>
<label for="tempHigh"><b>High Temperature</b></label>
<input type="text" placeholder="Edit the high temperature" id="tempHigh" required>
<input type="number" placeholder="Edit the high temperature" id="tempHigh" required>
<label for="tempLow"><b>Low Temperature</b></label>
<input type="text" placeholder="Edit the low temperature" id="tempLow" required>
<input type="number" placeholder="Edit the low temperature" id="tempLow" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="button" id="editbtn">Save Changes</button>
</div>
<div id="form-error"></div>
</div>
<div id="edit-error" class="error"></div>
</div>
</form>
</div>
</div>
@ -98,8 +105,8 @@
<button type="button" id="addbtn">Add</button>
</div>
<div id="form-error"></div>
</form>
<div id="add-error" class="error"></div>
</form>
</div>
</div>
</div>

View File

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

View File

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

View File

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

View File

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

View File

@ -4,29 +4,32 @@
<meta charset="UTF-8" />
<title>Register - Temperature Alarm</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles/common.css">
<link rel="stylesheet" href="/styles/auth.css">
<link rel="stylesheet" href="/styles/profile.css">
<script defer type="module" src="/scripts/profile.js"></script>
<script defer type="module" src="/shared/utils.js"></script>
</head>
<body>
<div id="container">
<div class="topnav">
<a href="/home/index.html">Home</a>
<a href="/devices/index.html">Devices</a>
<div style="display: flex; justify-content: flex-end;">
<a class="active" href="/profile/index.html">Profile</a>
<span class="logoutContainer">
<a href="/devices">Devices</a>
<a class="active" href="/profile">Profile</a>
<span class="logout-container">
<img class="logout" src="/img/logout.png">
</span>
</div>
</div>
<div id="profileCard"></div>
<div class="btnContainer">
<button class="btn" id="openEditModal">Edit</button>
<button class="btn" id="openPasswordModal">Change Password</button>
</div>
<div style="display: flex; justify-content: center;">
<div class="profileContainer">
<div id="profileCard"></div>
<div class="btnContainer">
<button class="btn" id="openEditModal">Edit</button>
<button class="btn" id="openPasswordModal">Change Password</button>
</div>
</div>
</div>
</div>
<div id="editModal" class="modal">
@ -36,13 +39,13 @@
<form id="editForm">
<div class="form-container">
<label for="email"><b>Email</b></label>
<input type="email" placeholder="Enter email "id="email">
<input type="email" placeholder="Enter email "id="email" required>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter username" id="uname">
<button type="submit">Save Changes</button>
<input type="text" placeholder="Enter username" id="uname" required>
<button id="submitEditBtn" type="submit">Save Changes</button>
<div id="editprofile-error" class="error"></div>
</div>
</form>
</div>
@ -65,7 +68,7 @@
<button type="submit">Change Password</button>
<div id="form-error"></div>
<div id="password-error" class="error"></div>
</div>
</form>
</div>

View File

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

View File

@ -1,90 +1,149 @@
import { getDevicesOnUserId, deleteDevice, update, add } from "./services/devices.service.js";
import { devices } from "../mockdata/devices.mockdata.js";
import { add, getDevices, update, deleteDevice } from "./services/devices.service.js";
import { logout } from "../shared/utils.js";
let id = localStorage.getItem("id");
// getDevicesOnUserId(id).then(res => {
// buildTable(res)
// })
buildTable(devices);
getDevices().then((res) => buildTable(res))
.catch(error => {
document.getElementById("get-error").innerText = error;
document.getElementById("get-error").style.display = "block";
});
let selectedReferenceId = null; // Store the selected referenceId
let selectedId = null; // Store the selected referenceId
const nameInput = document.getElementById("name");
const tempHighInput = document.getElementById("tempHigh");
const tempLowInput = document.getElementById("tempLow");
const editbtn = document.getElementById("editbtn");
var name;
var tempHigh;
var tempLow;
function buildTable(data) {
var table = document.getElementById("deviceTable");
table.innerHTML = ""; // Clear existing rows before adding new ones
data.forEach((device) => {
var row = document.createElement("tr");
row.innerHTML = `
<td>${device.referenceId}</td>
<td>${device.name}</td>
<td>${device.tempHigh}</td>
<td>${device.tempLow}</td>
<td>Temperature: ${device.latestLog.temperature}°C, Date: ${device.latestLog.date}</td>
<td style="width: 90px;">
<img class="editIconbtn tableIcons" src="/img/Edit.png" data-referenceid="${device.referenceId}">
<img class="trashBtn tableIcons" src="/img/Trash.png" data-referenceid="${device.referenceId}">
</td>
`;
table.appendChild(row);
});
document.getElementById("addDevice").onclick = () => {
document.getElementById("addModal").style.display = "block";
}
const latestLog = device.latestLog;
const temperatureText = latestLog
? `Temperature: ${latestLog.temperature}°C, Date: ${luxon.DateTime.fromISO(latestLog.date, { zone: "UTC" }).setZone("Europe/Copenhagen").toFormat("DD T")}`
: "No logs yet";
const row = document.createElement("tr");
row.innerHTML = `
<td>${device.referenceId}</td>
<td>${device.name}</td>
<td>${device.tempHigh}</td>
<td>${device.tempLow}</td>
<td>${temperatureText}</td>
<td style="width: 90px;">
<img class="editIconbtn tableIcons" src="/img/Edit.png" data-id="${device.id}" data-referenceId="${device.referenceId}" data-name="${device.name}" data-tempHigh="${device.tempHigh}" data-tempLow="${device.tempLow}">
<img class="trashBtn tableIcons" src="/img/Trash.png" data-id="${device.id}" data-referenceId="${device.referenceId}">
</td>
`;
table.appendChild(row);
});
// Attach click event to all trash buttons
document.querySelectorAll(".trashBtn").forEach((btn) => {
btn.onclick = function () {
selectedReferenceId = this.getAttribute("data-referenceid"); // Store referenceId
document.getElementById("deleteDeviceHeader").innerHTML = `Delete Device ${selectedReferenceId}`;
selectedId = this.getAttribute("data-id"); // Store referenceId
document.getElementById("deleteDeviceHeader").innerHTML = `Delete Device ${this.getAttribute("data-referenceId")}`;
document.getElementById("deleteModal").style.display = "block";
};
});
// Attach click event to all trash buttons
document.querySelectorAll(".editIconbtn").forEach((btn) => {
btn.onclick = function () {
selectedReferenceId = this.getAttribute("data-referenceid"); // Store referenceId
document.getElementById("editDeviceHeader").innerHTML = `Edit Device ${selectedReferenceId}`;
selectedId = this.getAttribute("data-id"); // Store referenceId
document.getElementById("editDeviceHeader").innerHTML = `Edit Device ${this.getAttribute("data-referenceId")}`;
nameInput.value = this.getAttribute("data-name");
tempHighInput.value = this.getAttribute("data-tempHigh");
tempLowInput.value = this.getAttribute("data-tempLow");
name = nameInput.value;
tempHigh = tempHighInput.value;
tempLow = tempLowInput.value;
editbtn.disabled = true;
document.getElementById("editModal").style.display = "block";
};
});
}
document.getElementById("addDevice").onclick = () => {
document.getElementById("referenceId").value = "";
document.getElementById("addModal").style.display = "block";
}
document.querySelectorAll(".cancelbtn").forEach(button => {
button.onclick = () => {
document.getElementById("deleteModal").style.display = "none";
document.getElementById("editModal").style.display = "none";
document.getElementById("addModal").style.display = "none";
document.getElementById("add-error").style.display = "none";
document.getElementById("add-error").innerText = "";
document.getElementById("delete-error").style.display = "none";
document.getElementById("delete-error").innerText = "";
document.getElementById("edit-error").style.display = "none";
document.getElementById("edit-error").innerText = "";
};
});
const checkForChanges = () => {
if (nameInput.value !== name || tempHighInput.value !== tempHigh || tempLowInput.value !== tempLow) {
editbtn.disabled = false; // Enable button if changes were made
} else {
editbtn.disabled = true; // Disable button if no changes
}
};
nameInput.addEventListener("input", checkForChanges);
tempHighInput.addEventListener("input", checkForChanges);
tempLowInput.addEventListener("input", checkForChanges);
// Delete button logic
document.getElementById("deletebtn").onclick = () => {
if (selectedReferenceId) {
deleteDevice(selectedReferenceId); // Call delete function with referenceId
document.getElementById("deleteModal").style.display = "none";
window.location.reload();
if (selectedId) {
deleteDevice(selectedId).then(() => location.reload())
.catch(error => {
document.getElementById("delete-error").innerText = error;
document.getElementById("delete-error").style.display = "block";
});
}
};
document.getElementById("addbtn").onclick = () => {
const referenceId = document.getElementById("referenceId").value;
add(referenceId); // Call delete function with referenceId
document.getElementById("deleteModal").style.display = "none";
window.location.reload();
add(referenceId).then(() => location.reload())
.catch(error => {
document.getElementById("add-error").innerText = error;
document.getElementById("add-error").style.display = "block";
});
};
document.getElementById("editbtn").onclick = () => {
if (selectedReferenceId) {
if (selectedId) {
const name = document.getElementById("name").value;
const tempHigh = document.getElementById("tempHigh").value;
const tempLow = document.getElementById("tempLow").value;
update(selectedReferenceId, name, tempHigh, tempLow); // Call delete function with referenceId
document.getElementById("deleteModal").style.display = "none";
window.location.reload();
update(selectedId, name, tempHigh, tempLow).then(() => location.reload())
.catch(error => {
document.getElementById("edit-error").innerText = error;
document.getElementById("edit-error").style.display = "block";
});
}
};
document.querySelector(".logout-container").addEventListener("click", logout);

View File

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

View File

@ -3,24 +3,23 @@ import { login } from "./services/users.service.js";
document.getElementById("loginForm").addEventListener("submit", function(event) {
event.preventDefault();
document.getElementById("form-error").style.display = "none";
const emailOrUsername = document.getElementById("emailorusn").value;
const password = document.getElementById("psw").value;
login(emailOrUsername, password)
.then(response => {
if (response.error) {
document.getElementById("form-error").innerText = response.error;
document.getElementById("form-error").style.display = "block";
return;
}
else{
if (typeof(Storage) !== "undefined") {
localStorage.setItem("id", response.id);
}
}
login(emailOrUsername, password).then((response) => {
if(response.token && response.refreshToken){
document.cookie = `auth-token=${response.token}; Path=/`;
document.cookie = `refresh-token=${response.refreshToken}; Path=/`;
localStorage.setItem("user", JSON.stringify({
id: response.id,
username: response.userName,
}));
location.href = "/home";
});
}
})
.catch(error => {
document.getElementById("login-error").innerText = error;
document.getElementById("login-error").style.display = "block";
});
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1 +0,0 @@
export const address = "http://127.0.0.1:5000/api"

View File

@ -1,18 +1,85 @@
export async function handleResponse(response) {
const json = await response.json();
import { address } from "./constants.js";
if (response.ok || json.error) return json;
if (json.errors) {
return { error: Object.values(response.errors)[0][0] };
export async function request(method, path, body = null) {
var token = document.cookie.match(/\bauth-token=([^;\s]+)/);
if (token != null) {
token = token[1];
}
else{
await getTokenByReferenceId(method, path, body);
}
const headers = {};
headers["Authorization"] = `Bearer ${token}`;
return { error: "Request failed with HTTP code " + response.status };
if (body)
headers["Content-Type"] = "application/json";
return new Promise((resolve, reject) => {
fetch(address + path, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
})
.then(async response => {
if (response.status === 401) {
getTokenByReferenceId(method, path, body);
}
try {
const json = await response.json();
if (response.ok) return resolve(json);
if (json.error) return reject(json.error);
if (json.message) return reject(json.message);
if (json.title) return reject(json.title);
if (json.errors) return reject(Object.values(json.errors)[0][0]);
} finally {
reject("Request failed with HTTP code " + response.status);
}
})
.catch(err => reject(err.message));
});
}
export function getTokenByReferenceId(method, path, body = null) {
var token = document.cookie.match(/\brefresh-token=([^;\s]+)/);
if (token != null) {
return fetch(`${address}/user/refreshtoken/${token[1]}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
})
.then(async response => {
const json = await response.json()
document.cookie = `auth-token=${json.token}; Path=/`;
document.cookie = `refresh-token=${json.refreshToken}; Path=/`;
return request(method, path, body);
})
.catch(error => {
location.href = "/login";
});
}
}
export function logout() {
localStorage.removeItem("user");
document.cookie = "auth-token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT";
document.cookie = "refresh-token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT";
window.location.href = "/";
}
export function getUser() {
return JSON.parse(localStorage.getItem("user"));
}
export function isLoggedIn() {
return (document.cookie.match(/\bauth-token=/) && localStorage.getItem("user"));
}
document.querySelectorAll(".logoutContainer").forEach(closeBtn => {
closeBtn.onclick = () => {
localStorage.clear();
window.location.href = "/index.html";
};
});

View File

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

View File

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

View File

@ -12,9 +12,6 @@ table {
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
.addDeviceContainer{
margin-top: 20px;
@ -30,6 +27,12 @@ table {
.tableConatiner{
display: flex;
justify-content: center;
overflow: hidden;
border-radius: 8px;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
border: 1px solid #DDD;
margin-bottom: 2rem;
background-color: white;
}
.tableIcons{
@ -79,7 +82,7 @@ table {
/* Add padding and center-align text to the container */
.container {
padding: 16px;
margin: 0 2rem;
}
/* The Modal (background) */

View File

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

View File

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

View File

@ -85,3 +85,12 @@ h2{
width: 90%;
}
.profileContainer {
margin: 2rem 0;
background-color: white;
border-radius: 8px;
border: 1px solid #DDD;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
width: 400px;
}

View File

@ -1,3 +1,9 @@
all: main.c mqtt.c temperature.c device_id.c
$(CC) -lmosquitto -lpthread -li2c main.c mqtt.c temperature.c device_id.c
FILES=main.c brokers/mqtt.c brokers/amqp.c devices/temperature.c devices/display.c devices/buzzer.c device_properties.c
# libgpiod version must be < 2.0
# apt install libmosquitto-dev librabbitmq-dev libi2c-dev libgpiod-dev libcjson-dev
all: $(FILES)
$(CC) -lmosquitto -lrabbitmq -pthread -li2c -lgpiod -lcjson $(FILES)

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

@ -0,0 +1,82 @@
#include <rabbitmq-c/amqp.h>
#include <rabbitmq-c/tcp_socket.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "../config.h"
amqp_connection_state_t conn;
amqp_socket_t *socket;
amqp_channel_t channel = 1;
void broker_on_connect(void);
bool broker_on_message(char *exchange, char *message);
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, channel, amqp_cstring_bytes(queue), amqp_cstring_bytes(queue), false, false, &props, amqp_cstring_bytes(message));
}
void amqp_subscribe(char *exchange, char *queue)
{
amqp_exchange_declare(conn, channel, amqp_cstring_bytes(exchange), amqp_cstring_bytes("fanout"), false, false, false, false, amqp_empty_table);
amqp_queue_declare(conn, channel, amqp_cstring_bytes(queue), false, false, false, true, amqp_empty_table);
amqp_queue_bind(conn, channel, amqp_cstring_bytes(queue), amqp_cstring_bytes(exchange), amqp_empty_bytes, amqp_empty_table);
amqp_basic_consume(conn, channel, amqp_cstring_bytes(queue), amqp_cstring_bytes("iot"), true, true, false, amqp_empty_table);
}
char *amqp_bytes_to_cstring(amqp_bytes_t bytes)
{
char *str = malloc(bytes.len + 1);
memcpy(str, bytes.bytes, bytes.len);
str[bytes.len] = '\0';
return str;
}
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, channel);
broker_on_connect();
while (true) {
amqp_envelope_t envelope;
amqp_consume_message(conn, &envelope, NULL, 0);
if (envelope.exchange.len == 0) {
continue;
}
char *exchange_name = amqp_bytes_to_cstring(envelope.exchange);
char *message = amqp_bytes_to_cstring(envelope.message.body);
broker_on_message(exchange_name, message);
amqp_basic_ack(conn, channel, envelope.delivery_tag, false);
free(exchange_name);
free(message);
amqp_destroy_envelope(&envelope);
}
}

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

@ -0,0 +1,6 @@
void init_amqp(void);
void amqp_send_message(char *topic, char *message);
void amqp_subscribe(char *exchange, char *queue);

View File

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

View File

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

View File

@ -1,46 +0,0 @@
#include <stdlib.h>
#include <stdio.h>
#include "device_id.h"
#define DEVICE_ID_SIZE 5
char *get_device_id(void)
{
FILE *file = fopen("device_id.txt", "r");
if (!file) {
char *device_id = generate_device_id();
file = fopen("device_id.txt", "w");
fprintf(file, "%s", device_id);
fclose(file);
return device_id;
}
char *device_id = malloc(DEVICE_ID_SIZE + 1);
fgets(device_id, DEVICE_ID_SIZE + 1, file);
fclose(file);
return device_id;
}
char *generate_device_id(void)
{
char *device_id = malloc(DEVICE_ID_SIZE + 1);
for (int i = 0; i < DEVICE_ID_SIZE; i++) {
device_id[i] = 'A' + (random() % 26);
}
device_id[DEVICE_ID_SIZE] = '\0';
return device_id;
}
void destroy_device_id(char *device_id)
{
free(device_id);
}

View File

@ -1,6 +0,0 @@
char *get_device_id(void);
char *generate_device_id(void);
void destroy_device_id(char *device_id);

78
iot/device_properties.c Normal file
View File

@ -0,0 +1,78 @@
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "device_properties.h"
char *get_device_id(void)
{
FILE *file = fopen("device_id.txt", "r");
if (!file) {
char *device_id = generate_device_id();
file = fopen("device_id.txt", "w");
fprintf(file, "%s", device_id);
fclose(file);
return device_id;
}
char *device_id = malloc(DEVICE_ID_SIZE + 1);
fgets(device_id, DEVICE_ID_SIZE + 1, file);
fclose(file);
return device_id;
}
char *generate_device_id(void)
{
char *device_id = malloc(DEVICE_ID_SIZE + 1);
for (int i = 0; i < DEVICE_ID_SIZE; i++) {
device_id[i] = 'A' + (random() % 26);
}
device_id[DEVICE_ID_SIZE] = '\0';
return device_id;
}
void set_min_temperature(double temperature)
{
FILE *file = fopen("min_temp.txt", "w");
fprintf(file, "%lf", temperature);
fclose(file);
}
double get_min_temperature(void)
{
FILE *file = fopen("min_temp.txt", "r");
if (!file) return NAN;
double temperature = NAN;
fscanf(file, "%lf", &temperature);
fclose(file);
return temperature;
}
void set_max_temperature(double temperature)
{
FILE *file = fopen("max_temp.txt", "w");
fprintf(file, "%lf", temperature);
fclose(file);
}
double get_max_temperature(void)
{
FILE *file = fopen("max_temp.txt", "r");
if (!file) return NAN;
double temperature = NAN;
fscanf(file, "%lf", &temperature);
fclose(file);
return temperature;
}

11
iot/device_properties.h Normal file
View File

@ -0,0 +1,11 @@
#define DEVICE_ID_SIZE 5
char *get_device_id(void);
char *generate_device_id(void);
void set_min_temperature(double temperature);
double get_min_temperature(void);
void set_max_temperature(double temperature);
double get_max_temperature(void);

44
iot/devices/buzzer.c Normal file
View File

@ -0,0 +1,44 @@
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include "buzzer.h"
buzzer_handle_t init_buzzer()
{
struct gpiod_chip *chip = gpiod_chip_open_by_name("gpiochip1");
if (chip == NULL) {
fprintf(stderr, "Unable to find gpiochip1\n");
exit(EXIT_FAILURE);
}
struct gpiod_line *line = gpiod_chip_get_line(chip, 19);
if (line == NULL) {
fprintf(stderr, "Unable to get line 19\n");
exit(EXIT_FAILURE);
}
gpiod_line_request_output(line, "buzzer", 0);
return (buzzer_handle_t) {
chip,
line,
};
}
void sound_buzzer(buzzer_handle_t buzzer, int delay, int length)
{
for (int cycle = 0; cycle < length; cycle++) {
gpiod_line_set_value(buzzer.line, 1);
usleep(delay);
gpiod_line_set_value(buzzer.line, 0);
usleep(delay);
}
}
void destroy_buzzer(buzzer_handle_t buzzer)
{
gpiod_line_release(buzzer.line);
gpiod_chip_close(buzzer.chip);
}

13
iot/devices/buzzer.h Normal file
View File

@ -0,0 +1,13 @@
#include <gpiod.h>
typedef struct {
struct gpiod_chip *chip;
struct gpiod_line *line;
} buzzer_handle_t;
buzzer_handle_t init_buzzer();
void sound_buzzer(buzzer_handle_t buzzer, int delay, int length);
void destroy_buzzer(buzzer_handle_t buzzer);

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

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

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

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

View File

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

View File

@ -5,10 +5,31 @@
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <cjson/cJSON.h>
#include "mqtt.h"
#include "temperature.h"
#include "device_id.h"
#include "brokers/amqp.h"
#include "devices/temperature.h"
#include "devices/display.h"
#include "devices/buzzer.h"
#include "device_properties.h"
void *sound_alarm(void *arg)
{
buzzer_handle_t buzzer = init_buzzer();
int delay = 170, length = 600;
for (int i = 0; i < 5; i++) {
sound_buzzer(buzzer, delay, length);
usleep(delay * 2 * length);
}
destroy_buzzer(buzzer);
return NULL;
}
void *watch_temperature(void *arg)
{
@ -16,14 +37,23 @@ void *watch_temperature(void *arg)
printf("Device ID: %s\n", device_id);
temperature_handle_t temp_handle = init_temperature();
display_handle_t display = init_display();
display_write_str(display, " ");
display_set_cursor_pos(display, 0, 1);
display_write_str(display, "Device.....");
display_write_str(display, device_id);
temperature_handle_t temp_handle = init_temperature();
get_temperature(temp_handle);
while (true) {
// Retrieve data
double min_temperature = get_min_temperature();
double max_temperature = get_max_temperature();
double temperature = get_temperature(temp_handle);
size_t timestamp = time(NULL);
// Send JSON
char *format = "{"
"\"temperature\": %lf,"
"\"device_id\": \"%s\","
@ -33,31 +63,94 @@ void *watch_temperature(void *arg)
char *str = malloc(snprintf(NULL, 0, format, temperature, device_id, timestamp) + 1);
sprintf(str, format, temperature, device_id, timestamp);
mqtt_send_message("temperature", str);
amqp_send_message("temperature-logs", str);
free(str);
// Print on display
str = malloc(17);
sprintf(str, "===[ %.1lf\xDF" "C ]===", temperature);
display_set_cursor_pos(display, 0, 0);
display_write_str(display, str);
free(str);
// Sound alarm if applicable
if (
temperature < 200.0 &&
min_temperature != NAN && max_temperature != NAN &&
(temperature < min_temperature || temperature > max_temperature)
) {
pthread_t alarm_thread;
pthread_create(&alarm_thread, NULL, sound_alarm, NULL);
}
printf("Temperature: %lf\n", temperature);
sleep(60);
}
destroy_device_id(device_id);
free(device_id);
return NULL;
}
void mqtt_on_connect(void)
void broker_on_connect(void)
{
// Subscribe to messages from queue
char *queue = malloc(strlen("device-") + DEVICE_ID_SIZE + 1);
strcpy(queue, "device-");
strcat(queue, get_device_id());
amqp_subscribe("temperature-limits", queue);
free(queue);
// Start thread for watching temperature
pthread_t temperature_thread;
pthread_create(&temperature_thread, NULL, watch_temperature, NULL);
}
bool broker_on_message(char *exchange, char *message)
{
cJSON *json = cJSON_Parse(message);
if (cJSON_IsInvalid(json)) goto cancel;
// Get values
cJSON *reference_id = cJSON_GetObjectItem(json, "ReferenceId");
if (!cJSON_IsString(reference_id)) goto cancel;
cJSON *min_temp = cJSON_GetObjectItem(json, "TempLow");
if (!cJSON_IsNumber(min_temp)) goto cancel;
cJSON *max_temp = cJSON_GetObjectItem(json, "TempHigh");
if (!cJSON_IsNumber(min_temp)) goto cancel;
if (strcmp(reference_id->valuestring, get_device_id()) != 0) {
goto cancel;
}
printf("Min temperature: %lf, Max temperature: %lf\n", min_temp->valuedouble, max_temp->valuedouble);
set_min_temperature(min_temp->valuedouble);
set_max_temperature(max_temp->valuedouble);
cJSON_Delete(json);
return true;
cancel:
cJSON_Delete(json);
return false;
}
int main(void)
{
srand(time(NULL));
init_mqtt();
init_amqp();
return EXIT_SUCCESS;
}