Compare commits

...

16 Commits

Author SHA1 Message Date
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
38 changed files with 955 additions and 381 deletions

View File

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

View File

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

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

@ -16,6 +16,12 @@ namespace Api.BusinessLogic
_configuration = configuration;
}
/// <summary>
/// Gets the user from dbaccess using the userId and checks if the user exists
/// Gets all devices that match the userId and checks if there are any devices connected to the user
/// </summary>
/// <param name="userId">UserId that matches a user that owns the devices</param>
/// <returns>returns the devices in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> GetDevices(int userId)
{
var profile = await _dbAccess.ReadUser(userId);
@ -29,6 +35,13 @@ namespace Api.BusinessLogic
return new OkObjectResult(devices);
}
/// <summary>
/// Checks if the user that the device is trying to be added to exists
/// Then it is send to dbaccess
/// </summary>
/// <param name="device">The new device</param>
/// <param name="userId">The user that owns the device</param>
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> AddDevice(Device device, int userId)
{
var profile = await _dbAccess.ReadUser(userId);
@ -38,6 +51,12 @@ namespace Api.BusinessLogic
return await _dbAccess.CreateDevice(device, userId);
}
/// <summary>
/// Checks if the device exist that is trying to be read from
/// Gets the logs and checks if there are any in the list
/// </summary>
/// <param name="deviceId">The deviceId that you want from the logs</param>
/// <returns>returns the logs in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> GetLogs(int deviceId)
{
var device = await _dbAccess.ReadDevice(deviceId);
@ -51,6 +70,12 @@ namespace Api.BusinessLogic
return new OkObjectResult(logs);
}
/// <summary>
/// Checks if the deviceId matches a device
/// </summary>
/// <param name="device">The updated info</param>
/// <param name="deviceId">The device to be edited</param>
/// <returns>returns the updated device in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> EditDevice(Device device, int deviceId)
{
var device1 = _dbAccess.ReadDevice(deviceId);

View File

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

View File

@ -19,15 +19,15 @@ namespace Api.Controllers
_deviceLogic = deviceLogic;
}
// Sends the userId to deviceLogic
[Authorize]
[HttpGet("{userId}")]
public async Task<IActionResult> GetDevices(int userId)
{
List<Device> devices = await _dbAccess.ReadDevices(userId);
if (devices.Count == 0) { return BadRequest(new { error = "There is no devices that belong to this userID" }); }
return await _deviceLogic.GetDevices(userId);
}
// Sends the device and userId to deviceLogic
[Authorize]
[HttpPost("adddevice/{userId}")]
public async Task<IActionResult> AddDevice([FromBody] Device device, int userId)
@ -35,6 +35,7 @@ namespace Api.Controllers
return await _deviceLogic.AddDevice(device, userId);
}
// Sends the deviceId to deviceLogic
[Authorize]
[HttpGet("logs/{deviceId}")]
public async Task<IActionResult> GetLogs(int deviceId)
@ -42,6 +43,7 @@ namespace Api.Controllers
return await _deviceLogic.GetLogs(deviceId);
}
// Sends the deviceId to deviceLogic
[Authorize]
[HttpPut("Edit/{deviceId}")]
public async Task<IActionResult> EditDevice([FromBody] Device device, int deviceId)

View File

@ -21,18 +21,21 @@ namespace Api.Controllers
_userLogic = userLogic;
}
// Sends the login to userLogic
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] Login login)
{
return await _userLogic.Login(login);
}
// Sends the user to userLogic
[HttpPost("Create")]
public async Task<IActionResult> CreateUser([FromBody] User user)
{
return await _userLogic.RegisterUser(user);
}
// Sends the user and userId to userLogic
[Authorize]
[HttpPut("Edit/{userId}")]
public async Task<IActionResult> EditUser([FromBody] User user, int userId)
@ -40,6 +43,7 @@ namespace Api.Controllers
return await _userLogic.EditProfile(user, userId);
}
// Sends the userId to userLogic
[Authorize]
[HttpDelete("Delete/{userId}")]
public async Task<IActionResult> DeleteUser(int userId)
@ -47,5 +51,11 @@ namespace Api.Controllers
return await _userLogic.DeleteUser(userId);
}
[HttpGet("RefreshToken")]
public async Task<IActionResult> RefreshToken(string refreshToken)
{
return await _userLogic.RefreshToken(refreshToken);
}
}
}

View File

@ -18,6 +18,11 @@ namespace Api.DBAccess
_context = context;
}
/// <summary>
/// Creates a user using entityframework core
/// </summary>
/// <param name="user">Need the entire user obj</param>
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> CreateUser(User user)
{
var users = await _context.Users.ToListAsync();
@ -43,6 +48,11 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to databse" });
}
/// <summary>
/// Returns a user that matches either the email or username
/// </summary>
/// <param name="login">Has a username or email and a password here the password is not used</param>
/// <returns>(user) that matches the login</returns>
public async Task<User> Login(Login login)
{
User user = new User();
@ -59,11 +69,32 @@ namespace Api.DBAccess
return user;
}
// Returns a user according to userID
public async Task<User> ReadUser(int userId)
{
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
}
// Returns a user according to refreshToken
public async Task<User> ReadUser(string refreshToken)
{
return await _context.Users.FirstOrDefaultAsync(u => u.RefreshToken == refreshToken);
}
public async void UpdatesRefreshToken(string refreshToken, int userId)
{
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
user.RefreshToken = refreshToken;
user.RefreshTokenExpiresAt = DateTime.Now.AddDays(7);
}
/// <summary>
/// Updates the user in the database
/// </summary>
/// <param name="user">Contains the updated user info</param>
/// <param name="userId">Has the id for the user that is to be updated</param>
/// <returns>returns the updated user in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> UpdateUser(User user, int userId)
{
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
@ -97,6 +128,11 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to database" });
}
/// <summary>
/// Deletes a user from the database
/// </summary>
/// <param name="userId">The Id of the user that is to be deleted</param>
/// <returns>returns true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> DeleteUser(int userId)
{
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
@ -120,6 +156,7 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Invalid user" });
}
// Returns devices according to userID
public async Task<List<Device>> ReadDevices(int userId)
{
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
@ -131,6 +168,12 @@ namespace Api.DBAccess
return devices;
}
/// <summary>
/// Creates a user using entityframework core
/// </summary>
/// <param name="device">The device that is going to be created</param>
/// <param name="userId">The user that owns the device</param>
/// <returns>returns the true in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> CreateDevice(Device device, int userId)
{
var user = await _context.Users.Include(u => u.Devices).FirstOrDefaultAsync(u => u.Id == userId);
@ -147,17 +190,31 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to database" });
}
// Returns a device according to userID
public async Task<Device> ReadDevice(int deviceId)
{
return await _context.Devices.FirstOrDefaultAsync(d => d.Id == deviceId);
}
// Returns a device according to userID
public Device ReadDevice(string refenreId)
{
return _context.Devices.FirstOrDefault(d => d.ReferenceId == refenreId);
}
// Returns all devices
public List<Device> ReadDevices()
{
return _context.Devices.ToList();
}
/// <summary>
/// Updates a device in the database
/// </summary>
/// <param name="device">Contains the updated device info</param>
/// <param name="deviceId">Has the id for the device that is to be updated</param>
/// <returns>returns the updated device in a OkObjectResult and if there is some error it returns a ConflictObjectResult and a message that explain the reason</returns>
public async Task<IActionResult> UpdateDevice(Device device, int deviceId)
{
var device1 = await _context.Devices.FirstOrDefaultAsync(u => u.Id == deviceId);
@ -179,6 +236,11 @@ namespace Api.DBAccess
return new ConflictObjectResult(new { message = "Could not save to database" });
}
/// <summary>
/// Returns the logs from the device
/// </summary>
/// <param name="deviceId">Has the id for the device that the los belong too</param>
/// <returns></returns>
public async Task<List<TemperatureLogs>> ReadLogs(int deviceId)
{
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.Id == deviceId);
@ -190,6 +252,11 @@ namespace Api.DBAccess
return logs;
}
/// <summary>
/// Creates a new log
/// </summary>
/// <param name="temperatureLogs">the new log</param>
/// <param name="referenceId">the referenceId that belongs too the device that recoded the log</param>
public async void CreateLog(TemperatureLogs temperatureLogs, string referenceId)
{
var device = await _context.Devices.Include(d => d.Logs).FirstOrDefaultAsync(d => d.ReferenceId == referenceId);
@ -202,6 +269,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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -12,6 +12,10 @@
public string? Salt { get; set; }
public string? RefreshToken { get; set; }
public DateTime RefreshTokenExpiresAt { get; set; }
public List<Device>? Devices { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using Api;
using Api.AMQP;
using Api.AMQPReciever;
using Api.DBAccess;
using Api.MQTTReciever;
@ -12,7 +13,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 +25,19 @@ class Program
var configuration = services.GetRequiredService<IConfiguration>();
var dbAccess = services.GetRequiredService<DbAccess>();
//AMQPReciever amqp = new AMQPReciever(configuration, dbAccess);
//amqp.Handle_Received_Application_Message().Wait();
MQTTReciever mqtt = new MQTTReciever(configuration, dbAccess);
mqtt.Handle_Received_Application_Message().Wait();
// Choose to either connect AMQP or MQTT
if (rabbitMQ == "AMQP")
{
AMQPReciever amqpReciever = new AMQPReciever(configuration, dbAccess);
amqpReciever.Handle_Received_Application_Message().Wait();
AMQPPublisher aMQPPush = new AMQPPublisher(configuration, dbAccess);
aMQPPush.Handle_Push_Device_Limits().Wait();
}
else if (rabbitMQ == "MQTT")
{
MQTTReciever mqtt = new MQTTReciever(configuration, dbAccess);
mqtt.Handle_Received_Application_Message().Wait();
}
}
});

View File

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

View File

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

View File

@ -1,25 +0,0 @@

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

View File

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

View File

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

View File

@ -1,84 +1,71 @@
import { mockTemperatureLogs } from "../mockdata/temperature-logs.mockdata.js"; // Import data
import { getLogsOnDeviceId } from "./services/devices.service.js";
const xValues = mockTemperatureLogs.map((log) =>
new Date(log.date).toLocaleString()
); // Full Date labels
const yValues = mockTemperatureLogs.map((log) => log.temperature); // Temperature values
buildTable(mockTemperatureLogs);
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [
{
fill: false,
lineTension: 0.4,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues,
},
],
},
options: {
tooltips: {
callbacks: {
title: function (tooltipItem) {
return `Date: ${tooltipItem[0].label}`;
async function buildChart() {
const data = await getLogsOnDeviceId(1);
const xValues = mockTemperatureLogs.map((log) =>
new Date(log.date).toLocaleString()
); // Full Date labels
const yValues = mockTemperatureLogs.map((log) => log.temperature); // Temperature values
buildTable(mockTemperatureLogs);
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [
{
fill: false,
lineTension: 0.4,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues,
},
],
},
label: function (tooltipItem) {
return `Temperature: ${tooltipItem.value}°C`;
options: {
tooltips: {
callbacks: {
title: function (tooltipItem) {
return `Date: ${tooltipItem[0].label}`;
},
label: function (tooltipItem) {
return `Temperature: ${tooltipItem.value}°C`;
},
},
},
},
},
},
},
});
});
}
function buildTable(data) {
var table = document.getElementById(`TemperatureTable`);
data.forEach((log) => {
var averageTemp = (log.tempHigh + log.tempLow) / 2.0;
var color;
if (log.temperature > log.tempHigh) {
color = "tempHigh";
} else if (
log.temperature < log.tempHigh &&
log.temperature > averageTemp
) {
color = "tempMidHigh";
} else if (log.temperature < log.tempLow) {
color = "tempLow";
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) {
color = "tempMidLow";
} else {
color = "tempNormal";
}
var row = ` <tr>
var table = document.getElementById(`TemperatureTable`);
data.forEach((log) => {
var averageTemp = (log.tempHigh + log.tempLow) / 2.0;
var color;
if (log.temperature > log.tempHigh) {
color = "tempHigh";
} else if (
log.temperature < log.tempHigh &&
log.temperature > averageTemp
) {
color = "tempMidHigh";
} else if (log.temperature < log.tempLow) {
color = "tempLow";
} else if (log.temperature > log.tempLow && log.temperature < averageTemp) {
color = "tempMidLow";
} else {
color = "tempNormal";
}
var row = ` <tr>
<td>Name</td>
<td class="${color}">${log.temperature}</td>
<td>${log.date}</td>
<td class="tempHigh">${log.tempHigh}</td>
<td class="tempLow">${log.tempLow}</td>
</tr>`;
table.innerHTML += row;
});
table.innerHTML += row;
});
}
// Get the modal
var modal = document.getElementById("chartModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function () {
modal.style.display = "block";
};
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
};
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
buildChart();

View File

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

View File

@ -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,4 +1,4 @@
import { address } from "../../shared/constants";
import { address } from "../../shared/constants.js";
export function getDevicesOnUserId(id) {
fetch(`${address}/get-on-user-id`, {
@ -26,15 +26,14 @@ export function update(ids) {
.catch(error => console.error("Error:", error));
}
export function getLogsOnDeviceIds(id) {
fetch(`${address}/get-on-device-ids`, {
export function getLogsOnDeviceId(id) {
fetch(`${address}/device/logs/${id}`, {
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));
}
}

View File

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

View File

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

View File

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

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

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

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

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

View File

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

View File

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

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

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

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

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

View File

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

View File

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