Skip to content

Commit e117cb6

Browse files
committed
Update packet to comply with CAN BUS protocol
1 parent ac8a881 commit e117cb6

File tree

10 files changed

+290
-130
lines changed

10 files changed

+290
-130
lines changed

communication/include/bus_manager.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ class BusManager
2727
// Sends to the server to listen for requests
2828
ErrorCode startConnection();
2929

30+
// Stops server connection
31+
static void stopConnection();
32+
3033
// Receives the packet that arrived and checks it before sending it out
3134
void receiveData(Packet &p);
3235

@@ -36,8 +39,5 @@ class BusManager
3639
// Implement a priority check according to the CAN bus
3740
Packet packetPriority(Packet &a, Packet &b);
3841

39-
// Static method to handle SIGINT signal
40-
static void signalHandler(int signum);
41-
4242
~BusManager();
4343
};

communication/include/communication.h

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,15 @@ class Communication
5151
ErrorCode startConnection();
5252

5353
// Sends a message to manager
54-
ErrorCode sendMessage(void *data, size_t dataSize, uint32_t destID, uint32_t srcID, bool isBroadcast);
54+
ErrorCode sendMessage(void *data, size_t dataSize, uint32_t destID,
55+
uint32_t srcID,
56+
MessageType messageType = MessageType::DATA_MESSAGE);
5557

5658
// Sends a message to manager - Async
57-
void sendMessageAsync(void *data, size_t dataSize, uint32_t destID, uint32_t srcID, std::function<void(ErrorCode)> passSend, bool isBroadcast);
59+
void sendMessageAsync(void *data, size_t dataSize, uint32_t destID,
60+
uint32_t srcID,
61+
std::function<void(ErrorCode)> sendCallback,
62+
MessageType messageType = MessageType::DATA_MESSAGE);
5863

5964
//Destructor
6065
~Communication();

communication/include/message.h

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,35 @@
66
#include <cstdlib>
77
#include <unordered_map>
88
#include <iostream>
9+
#include <chrono>
910
#include "packet.h"
1011

11-
class Message
12-
{
12+
enum MessageType {
13+
INITIAL_CONNECTION, // Represents initial connection of a component to the server
14+
ERROR_MESSAGE, // Error message (highest priority)
15+
ACK, // Acknowledgment message
16+
OVERLOAD_MESSAGE, // Indicates network overload
17+
REMOTE_TRANSMISSION_REQUEST, // Request for remote data (RTR)
18+
DATA_MESSAGE // Regular data message (lowest priority)
19+
};
20+
21+
22+
23+
class Message {
1324
private:
14-
std::vector<Packet> packets;
15-
uint32_t tps;
16-
25+
std::vector<Packet> packets;
26+
uint32_t tps;
27+
uint32_t messageID;
28+
29+
uint32_t generateMessageID(MessageType messageType, uint16_t srcID);
30+
1731
public:
18-
// Default
32+
// Default constructor
1933
Message() = default;
2034

2135
// Constructor for sending message
22-
Message(uint32_t srcID, void *data, int dlc, bool isBroadcast, uint32_t destID = 0xFFFF);
23-
36+
Message(uint32_t srcID, uint32_t destID, void* data, size_t size, MessageType messageType);
37+
2438
// Constructor for receiving message
2539
Message(uint32_t tps);
2640

@@ -31,8 +45,14 @@ class Message
3145
bool isComplete() const;
3246

3347
// Get the complete data of the message
34-
void *completeData() const;
48+
void* completeData() const;
3549

3650
// Get the packets of the message
37-
std::vector<Packet> &getPackets();
51+
std::vector<Packet>& getPackets();
52+
53+
// Extract the MessageType from the message ID
54+
static MessageType getMessageTypeFromID(uint32_t messageID);
55+
56+
// Returns a string representation of the MessageType enum value
57+
static std::string getMessageTypeString(MessageType type);
3858
};

communication/include/packet.h

Lines changed: 70 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,75 @@
1-
#pragma once
2-
#include <vector>
1+
#ifndef __PACKET_H__
2+
#define __PACKET_H__
3+
34
#include <cstring>
4-
#include <cstdint>
5-
#include <ctime>
6-
#include <cstdlib>
7-
#include <unordered_map>
8-
#include <iostream>
9-
#include <bitset>
10-
#include <cstdint>
11-
#include <iomanip>
5+
#include <string>
126
#include <sstream>
7+
#include <iomanip>
8+
139
#define SIZE_PACKET 8
14-
class Packet
15-
{
10+
11+
class Packet {
1612
public:
17-
// Packet header containing various metadata fields
18-
struct Header
19-
{
20-
uint32_t ID; // Message ID
21-
uint32_t PSN; // Packet Sequence Number
22-
uint32_t TPS; // Total Packet Sum
23-
uint32_t SrcID; // Source ID
24-
uint32_t DestID; // Destination ID
25-
uint8_t DLC; // Data Length Code (0-8 bits)
26-
uint16_t CRC; // Cyclic Redundancy Check for error detection
27-
int timestamp; // Timestamp field
28-
bool isBroadcast; // True for broadcast, false for unicas
29-
bool passive;
30-
bool RTR;
31-
} header;
32-
33-
void *data[SIZE_PACKET];
34-
35-
// Default constructor for Packet.
36-
Packet() = default;
37-
38-
// Constructor for sending message
39-
Packet(uint32_t id, uint32_t psn, uint32_t tps, uint32_t srcID, uint32_t destID, void *data, uint8_t dlc, bool isBroadcast, bool RTR = false, bool passive = false);
40-
41-
// Constructor for receiving message
42-
Packet(uint32_t id);
43-
44-
// Calculate CRC for the given data and length
45-
uint16_t calculateCRC(const void *data, size_t length);
46-
47-
// A function to convert the data to hexa (logger)
48-
std::string pointerToHex(const void *ptr, size_t size) const;
13+
// Default constructor for Packet.
14+
Packet() = default;
15+
16+
// Constructor for sending message
17+
Packet(uint32_t id, uint32_t PSN, uint32_t TPS, uint32_t srcId,
18+
uint32_t destId, int DLC, bool RTR, bool isBroadcast,
19+
const uint8_t *payload);
20+
21+
// Constructor for receiving message
22+
Packet(uint32_t id);
23+
24+
// Destructor
25+
~Packet() = default;
26+
27+
// Overloaded operator>
28+
bool operator>(const Packet &other) const;
29+
30+
// Getters for accessing Header fields
31+
uint32_t getId() const { return header.id; }
32+
uint32_t getPSN() const { return header.PSN; }
33+
uint32_t getTPS() const { return header.TPS; }
34+
uint32_t getSrcId() const { return header.srcId; }
35+
uint32_t getDestId() const { return header.destId; }
36+
int getTimestamp() const { return header.timestamp; }
37+
int getDLC() const { return header.DLC; }
38+
uint16_t getCRC() const { return header.CRC; }
39+
bool isRTR() const { return header.RTR; }
40+
bool getIsPassive() const { return header.passive; }
41+
bool getIsBroadcast() const { return header.isBroadcast; }
42+
43+
const uint8_t *getPayload() const { return payload; }
44+
45+
// Setters for modifying Header fields
46+
void setIsPassive(bool p) { header.passive = p; }
47+
void setTimestamp(int t) { header.timestamp = t; }
48+
49+
// CRC calculation
50+
uint16_t calculateCRC() const;
51+
bool validateCRC() const;
52+
53+
// A function to convert the data to hexa (logger)
54+
std::string pointerToHex() const;
55+
56+
private:
57+
// Header structure within Packet
58+
struct Header {
59+
uint32_t id; // Unique identifier for the message (4 bytes)
60+
uint32_t PSN; // Packet Sequence Number (4 bytes)
61+
uint32_t TPS; // Total Packet Sum (4 bytes)
62+
uint32_t srcId; // Source node ID (4 bytes)
63+
uint32_t destId; // Destination node ID (4 bytes)
64+
int timestamp; // Timestamp marking the packet's send time (4 bytes)
65+
int DLC; // Data Length Code (0-8 bytes) (4 bytes)
66+
uint16_t CRC; // Cyclic Redundancy Check (2 bytes)
67+
bool RTR; // Remote Transmission Request flag (1 byte)
68+
bool passive; // Passive state flag (1 byte)
69+
bool isBroadcast; // Broadcast flag (1 byte)
70+
} header;
71+
72+
uint8_t payload[SIZE_PACKET]; // Data payload (fixed size, up to SIZE_PACKET bytes)
4973
};
74+
75+
#endif // __PACKET_H__

communication/sockets/real_socket.cpp

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -83,14 +83,14 @@ ssize_t RealSocket::recv(int sockfd, void *buf, size_t len, int flags)
8383
const Packet *p = static_cast<const Packet *>(buf);
8484

8585
if (valread < 0)
86-
RealSocket::log.logMessage(logger::LogLevel::ERROR, std::to_string(p->header.SrcID), std::to_string(p->header.DestID), std::string(" Error occurred: in socket ") + std::to_string(sockfd) + std::string(" ") + std::string(strerror(errno)));
86+
RealSocket::log.logMessage(logger::LogLevel::ERROR, std::to_string(p->getSrcId()), std::to_string(p->getDestId()), std::string(" Error occurred: in socket ") + std::to_string(sockfd) + std::string(" ") + std::string(strerror(errno)));
8787
else if (valread == 0)
88-
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->header.SrcID), std::to_string(p->header.DestID), std::string(" connection closed: in socket ") + std::to_string(sockfd) + std::string(" ") + std::string(strerror(errno)));
88+
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->getSrcId()), std::to_string(p->getDestId()), std::string(" connection closed: in socket ") + std::to_string(sockfd) + std::string(" ") + std::string(strerror(errno)));
8989
else {
90-
if (!p->header.DLC)
91-
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->header.SrcID), std::to_string(p->header.DestID), std::string("received packet number: ") + std::to_string(p->header.PSN) + std::string(", of messageId: ") + std::to_string(p->header.ID) + std::string(" ") + std::string(strerror(errno)) + " ID for connection: " + std::to_string(p->header.SrcID));
90+
if (!p->getDLC())
91+
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->getSrcId()), std::to_string(p->getDestId()), std::string("received packet number: ") + std::to_string(p->getPSN()) + std::string(", of messageId: ") + std::to_string(p->getId()) + std::string(" ") + std::string(strerror(errno)) + " ID for connection: " + std::to_string(p->getSrcId()));
9292
else
93-
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->header.SrcID), std::to_string(p->header.DestID), std::string("received packet number: ") + std::to_string(p->header.PSN) + std::string(", of messageId: ") + std::to_string(p->header.ID) + std::string(" ") + std::string(strerror(errno)) + " Data: " + p->pointerToHex(p->data,p->header.DLC));
93+
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->getSrcId()), std::to_string(p->getDestId()), std::string("received packet number: ") + std::to_string(p->getPSN()) + std::string(", of messageId: ") + std::to_string(p->getId()) + std::string(" ") + std::string(strerror(errno)) + " Data: " + p->pointerToHex());
9494
}
9595

9696

@@ -103,12 +103,12 @@ ssize_t RealSocket::send(int sockfd, const void *buf, size_t len, int flags)
103103
const Packet *p = static_cast<const Packet *>(buf);
104104
if (sendAns <= 0)
105105
{
106-
RealSocket::log.logMessage(logger::LogLevel::ERROR, std::to_string(p->header.SrcID), std::to_string(p->header.DestID), "sending packet number: " + std::to_string(p->header.PSN) + ", of messageId: " + std::to_string(p->header.ID) + std::string(" ") + std::string(strerror(errno)));
106+
RealSocket::log.logMessage(logger::LogLevel::ERROR, std::to_string(p->getSrcId()), std::to_string(p->getDestId()), "sending packet number: " + std::to_string(p->getPSN()) + ", of messageId: " + std::to_string(p->getId()) + std::string(" ") + std::string(strerror(errno)));
107107
}
108-
if (!p->header.DLC)
109-
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->header.SrcID), std::to_string(p->header.DestID), "sending packet number: " + std::to_string(p->header.PSN) + ", of messageId: " + std::to_string(p->header.ID) + std::string(" ") + std::string(strerror(errno)) + " ID for connection: " + std::to_string(p->header.SrcID));
108+
if (!p->getDLC())
109+
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->getSrcId()), std::to_string(p->getDestId()), "sending packet number: " + std::to_string(p->getPSN()) + ", of messageId: " + std::to_string(p->getId()) + std::string(" ") + std::string(strerror(errno)) + " ID for connection: " + std::to_string(p->getSrcId()));
110110
else
111-
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->header.SrcID), std::to_string(p->header.DestID), "sending packet number: " + std::to_string(p->header.PSN) + ", of messageId: " + std::to_string(p->header.ID) + std::string(" ") + std::string(strerror(errno)) + " Data: " + p->pointerToHex(p->data,p->header.DLC));
111+
RealSocket::log.logMessage(logger::LogLevel::INFO, std::to_string(p->getSrcId()), std::to_string(p->getDestId()), "sending packet number: " + std::to_string(p->getPSN()) + ", of messageId: " + std::to_string(p->getId()) + std::string(" ") + std::string(strerror(errno)) + " Data: " + p->pointerToHex());
112112
return sendAns;
113113
}
114114

communication/src/bus_manager.cpp

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ std::mutex BusManager::managerMutex;
77
BusManager::BusManager(std::vector<uint32_t> idShouldConnect, uint32_t limit) :server(8080, std::bind(&BusManager::receiveData, this, std::placeholders::_1))//,syncCommunication(idShouldConnect, limit)
88
{
99
// Setup the signal handler for SIGINT
10-
signal(SIGINT, BusManager::signalHandler);
1110
}
1211

1312
// Static function to return a singleton instance
@@ -45,7 +44,7 @@ void BusManager::receiveData(Packet &p)
4544
// Sending according to broadcast variable
4645
ErrorCode BusManager::sendToClients(const Packet &packet)
4746
{
48-
if(packet.header.isBroadcast)
47+
if(packet.getIsBroadcast())
4948
return server.sendBroadcast(packet);
5049
return server.sendDestination(packet);
5150
}
@@ -59,16 +58,15 @@ Packet BusManager::checkCollision(Packet &currentPacket)
5958
// Implement a priority check according to the CAN bus
6059
Packet BusManager::packetPriority(Packet &a, Packet &b)
6160
{
62-
return (a.header.SrcID < b.header.SrcID) ? a : b;
61+
return (a.getSrcId() < b.getSrcId()) ? a : b;
6362
}
6463

65-
// Static method to handle SIGINT signal
66-
void BusManager::signalHandler(int signum)
64+
//shut down the server
65+
void BusManager::stopConnection()
6766
{
6867
if (instance) {
69-
instance->server.stopServer(); // Call the stopServer method
68+
instance->server.stopServer(); // Stop server on interrupt
7069
}
71-
exit(signum);
7270
}
7371

7472
BusManager::~BusManager() {

communication/src/communication.cpp

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ ErrorCode Communication::startConnection()
2929
}
3030

3131
// Sends a message sync
32-
ErrorCode Communication::sendMessage(void *data, size_t dataSize, uint32_t destID, uint32_t srcID, bool isBroadcast)
32+
ErrorCode Communication::sendMessage(void *data, size_t dataSize, uint32_t destID,
33+
uint32_t srcID,
34+
MessageType messageType)
3335
{
3436
if (dataSize == 0)
3537
return ErrorCode::INVALID_DATA_SIZE;
@@ -40,10 +42,9 @@ ErrorCode Communication::sendMessage(void *data, size_t dataSize, uint32_t destI
4042
if (!client.isConnected())
4143
return ErrorCode::CONNECTION_FAILED;
4244

43-
Message msg(srcID, data, dataSize, isBroadcast, destID);
44-
45+
Message msg(srcID, destID, data, dataSize,messageType); // Create a new message
4546
//Sending the message to logger
46-
RealSocket::log.logMessage(logger::LogLevel::INFO,std::to_string(srcID),std::to_string(destID),"Complete message:" + msg.getPackets().at(0).pointerToHex(data, dataSize));
47+
RealSocket::log.logMessage(logger::LogLevel::INFO,std::to_string(srcID),std::to_string(destID),"Complete message:" + msg.getPackets().at(0).pointerToHex());
4748

4849
for (auto &packet : msg.getPackets()) {
4950
ErrorCode res = client.sendPacket(packet);
@@ -55,14 +56,16 @@ ErrorCode Communication::sendMessage(void *data, size_t dataSize, uint32_t destI
5556
}
5657

5758
// Sends a message Async
58-
void Communication::sendMessageAsync(void *data, size_t dataSize, uint32_t destID, uint32_t srcID, std::function<void(ErrorCode)> sendCallback, bool isBroadcast)
59+
void Communication::sendMessageAsync(void *data, size_t dataSize, uint32_t destID,
60+
uint32_t srcID,
61+
std::function<void(ErrorCode)> sendCallback,
62+
MessageType messageType)
5963
{
6064
std::promise<ErrorCode> resultPromise;
6165
std::future<ErrorCode> resultFuture = resultPromise.get_future();
6266

63-
std::thread([this, data, dataSize, destID, srcID, isBroadcast, &resultPromise]() {
64-
ErrorCode res = this->sendMessage(data, dataSize, destID, srcID, isBroadcast);
65-
resultPromise.set_value(res);
67+
std::thread([this, data, dataSize, destID, srcID, messageType, sendCallback,&resultPromise]() {
68+
ErrorCode result = this->sendMessage(data, dataSize, destID, srcID, messageType); // Send the message resultPromise.set_value(res);
6669
}).detach();
6770

6871
ErrorCode res = resultFuture.get();
@@ -83,13 +86,13 @@ void Communication::receivePacket(Packet &p)
8386
// Checks if the packet is intended for him
8487
bool Communication::checkDestId(Packet &p)
8588
{
86-
return p.header.isBroadcast || p.header.DestID == this->id;
89+
return p.getIsBroadcast() || p.getDestId() == this->id;
8790
}
8891

8992
// Checks if the data is currect
9093
bool Communication::validCRC(Packet &p)
9194
{
92-
return p.header.CRC == p.calculateCRC(p.data, p.header.DLC);
95+
return p.validateCRC();
9396
}
9497

9598
// Receives the packet and adds it to the message
@@ -117,21 +120,21 @@ Packet Communication::hadArrived()
117120
// Adding the packet to the complete message
118121
void Communication::addPacketToMessage(Packet &p)
119122
{
120-
std::string messageId = std::to_string(p.header.ID);
123+
std::string messageId = std::to_string(p.getId());
121124
// If the message already exists, we will add the packet
122125
if (receivedMessages.find(messageId) != receivedMessages.end()) {
123126
receivedMessages[messageId].addPacket(p);
124127
} else {
125128
// If the message does not exist, we will create a new message
126-
Message msg(p.header.TPS);
129+
Message msg(p.getTPS());
127130
msg.addPacket(p);
128131
receivedMessages[messageId] = msg;
129132
}
130133

131134
// If the message is complete, we pass the data to the passData function
132135
if (receivedMessages[messageId].isComplete()) {
133136
void *completeData = receivedMessages[messageId].completeData();
134-
passData(p.header.SrcID, completeData);
137+
passData(p.getSrcId(), completeData);
135138
receivedMessages.erase(messageId); // Removing the message once completed
136139
}
137140
}

0 commit comments

Comments
 (0)