Measurements and comments added

This commit is contained in:
Christos Houtouridis
2019-10-06 13:37:16 +03:00
parent 463971982c
commit d478f9a20a
14 changed files with 1270 additions and 905 deletions
+62 -14
View File
@@ -1,5 +1,6 @@
/*!
* \file client.c
* This file contains all the client and device search functionalities.
*
* \author Christos Choutouridis AEM:8997 <cchoutou@ece.auth.gr>
*/
@@ -14,9 +15,19 @@
#include <errno.h>
#include "client.h"
/*!
* Transmit buffer
*/
static char_t tx_buffer [MSG_TEXT_SIZE];
char_t tx_buffer [MSG_TEXT_SIZE];
/*!
* Ping functionality. We use system and pass a test command in order to
* find out if a particular device is on range.
* @param dev The device to ping
* @return The status of the operation
* @arg true The device was on range and replyed to our ping
* @arg false The device wasn't on range
*/
static bool_t ping (devAEM_t dev) {
char_t cmd[72];
devIP_t ip = AEM2ip (dev);
@@ -29,6 +40,10 @@ static bool_t ping (devAEM_t dev) {
return (system(cmd) == 0) ? true:false;
}
/*!
* Search for devices on range and mark the time of first and last sight
* @return The number of devices on range
*/
static size_t seeker (void) {
size_t cnt =0; // count devices on range
log_debug ("Debug: Pinging devices...\n");
@@ -40,9 +55,10 @@ static size_t seeker (void) {
if (ping (devList[i].dev)) { // Noc noc....
devList[i].onRange = true; // Who's there?
++cnt; // No one, bye bye!
// Mark the time for first and last time we saw this device
if (!devList[i].begin)
devList[i].begin = time(NULL);
devList[i].end = time(NULL);
devList[i].begin = time(NULL); // first time only
devList[i].end = time(NULL); // every time
log_debug ("Debug: Device %u found\n", devList[i].dev);
}
else
@@ -52,6 +68,19 @@ static size_t seeker (void) {
return cnt;
}
/*!
* @brief
* Send message functionality
* TCP socket communication for sending a message to device. We use non-blocking
* connect/select in order to be able to timeout from select. We also use send with
* timeout.
*
* @param dev The device to send the message
* @param msg Pointer to message to send
* @return The status of the operation
* @note
* We treat all error of this function as "non-fatal".
*/
static bool_t sendMsg (devAEM_t dev, cMsg_t* msg) {
int sock;
sockaddr_in_t srvAddr;
@@ -140,7 +169,7 @@ static bool_t sendMsg (devAEM_t dev, cMsg_t* msg) {
break;
}
log_debug ("Debug: Setting send timeout succeed\n");
size_t len = cMsg_cat (msg, tx_buffer);
size_t len = cMsg_serialize (msg, tx_buffer);
if (send (sock, tx_buffer, len, MSG_CONFIRM) == -1) {
ret = false;
log_debug ("Debug: Sending failed\n");
@@ -154,10 +183,20 @@ static bool_t sendMsg (devAEM_t dev, cMsg_t* msg) {
return ret;
}
static status_t client (void) {
/*!
* @brief
* Client functionality
*
* Creates a message in a random interval, seeks for devices on range
* and loop in entire msgList in order to send all messages
* @note
* This function never returns
*/
static void client (void) {
msg_t msg; // new message buffer
while (true) {
sleep (settings.msgInterval); // Idle until the time comes
// Idle until the time comes
sleep (settings.msgInterval + (rand()%settings.msgRand));
memset ((void*)&msg, 0, sizeof (msg)); // create a new message
cMsg_make (&msg.cMsg);
msg.sender = settings.me;
@@ -167,16 +206,16 @@ static status_t client (void) {
msgList_acquire (); // try to lock resources
mIter_t at = msgList_add (&msgList, &msg); // Add message to msgList
msgList_release ();
log_debug ("Debug: Message added to msgList at %d\n", at);
if (!seeker ()) { // If we are alone skip the rest
msgList_release (); // but unlock resources first
if (!seeker ()) // If we are alone skip the rest
continue;
}
log_debug ("Debug: Devices found on range\n");
msgList_acquire ();
mIter_t it = msgList_begin (&msgList); // get a message iterator
// begin with old messages first
// for each message -> for each recipient
for (size_t i=0 ; i<msgList_size(&msgList) ; ++i, msgList_preInc (&it)) {
for (size_t j=0 ; j<AEMLIST_SIZE ; ++j) {
@@ -187,11 +226,16 @@ static status_t client (void) {
) {
if (sendMsg (devList[j].dev, &msgList.m[it].cMsg)) {
msgList.m[it].recipients[j] = true;
msgList_release ();
statsUpdateOut (&msg, devList[j].dev);
log_msg_out (&msg, devList[j].dev);
log_debug ("Debug: Send message to device %u succeed\n", devList[j].dev);
msgList_acquire ();
}
else {
msgList_release ();
log_debug ("Debug: Send message to device %u failed\n", devList[j].dev);
msgList_acquire ();
}
//^ we try to send the message and mark the transmission on success
// if send fail, don't worry it may succeed the next time.
@@ -202,14 +246,18 @@ static status_t client (void) {
if (statsPrint (&stats) == MSG_ERROR)
log_error ("Error: Writing to statistics file failed\n");
}
return MSG_ERROR;
return;
}
/*!
* pthread wrapper for \sa client()
* @param ptr
*/
void* pthClient (void* ptr) {
(void)&ptr; // use parameter
if (client () == MSG_ERROR)
exit(1); // we should not be here, client never returns
client ();
exit(1); // we should not be here, client never returns
return NULL;
}
+231 -61
View File
@@ -1,6 +1,6 @@
/*!
* \file core.c
*
* Core messenger functionality
* \author Christos Choutouridis AEM:8997 <cchoutou@ece.auth.gr>
*/
@@ -14,20 +14,48 @@
#include "core.h"
pthread_mutex_t lock_msgList;
pthread_mutex_t lock_stderr;
pthread_mutex_t lock_stdout;
pthread_mutex_t lock_stats;
//! Global data
//! @{
msgList_t msgList; //!< The message list for our application.
//! @}
/*
* Local data types
*/
static pthread_mutex_t lock_msgList; //!< mutex for msgList locking
static pthread_mutex_t lock_stderr; //!< mutex for stderr locking
static pthread_mutex_t lock_stdout; //!< mutex for stderr locking
static pthread_mutex_t lock_stats; //!< mutex for stats locking
//! Helper API
//! @{
//! Macro to create a in_addr_t
#define _ADHOC_SUBNET(A, B, C, D) (((A)<<24) | ((B)<<16) | ((C)<<8) | (D))
devAEM_t addr2devAEM (uint32_t in_addr) {
/*!
* in_addr_t to devAEM_t conversion utility function
* @param in_addr Internet address (host byte order)
* @return devAEM_t representation of the address
* @example
* @code{.c}
* devAEM_t dev = addr2devAEM (ntohl(clntAddr.sin_addr.s_addr));
* @endcode
*/
devAEM_t addr2devAEM (in_addr_t in_addr) {
return (in_addr & 0x000000FF) + ((in_addr >> 8) & 0x000000FF) * 100;
}
/*!
* devAEM_t to in_addr_t conversion utility function
* @param dev devAEM_t address
* @return Internet address (host byte order)
* @example
* @code{.c}
* sockaddr_in_t srvAddr;
* srvAddr.sin_addr.s_addr = htonl (devAEM2addr (dev));
* @endcode
*/
in_addr_t devAEM2addr (devAEM_t dev) {
uint32_t add = _ADHOC_SUBNET (ADHOC_NET_A, ADHOC_NET_B, ADHOC_NET_C, ADHOC_NET_D);
add |= (dev % 100) & 0x000000FF;
@@ -35,36 +63,48 @@ in_addr_t devAEM2addr (devAEM_t dev) {
return add;
}
/*!
* DevIP_t to devAEM_t conversion utility function
* @param ip pointer to devIP_t type address
* @return devAEM_t representation of the address
* @note
* We discard the first 2 fields
*/
devAEM_t ip2AEM (devIP_t* ip) {
return ip->C*100 + ip->D;
}
/*!
* devAEM_t to DevIP_t conversion utility function
* @param dev devAEM_t representation of the address
* @return devIP_t type address
*/
devIP_t AEM2ip (devAEM_t dev) {
devIP_t ip = {
.A =ADHOC_NET_A, .B=ADHOC_NET_B, .C=dev/100, .D=dev%100
};
return ip;
}
devIP_t addr2ip (in_addr_t in_addr) {
devIP_t ip = {
.A = ADHOC_NET_A,
.B = ADHOC_NET_B,
.C = (in_addr >> 8) & 0x000000FF,
.D = in_addr & 0x000000FF
};
return ip;
}
//! @}
/*
* Log related local data
*/
static char_t* _frm_msg_in = "In from dev=%d, message: from=%d, to=%d, timestamp=%lld, text=%s\n";
static char_t* _frm_msg_out = "Out to dev=%d, message: from=%d, to=%d, timestamp=%lld, text=%s\n";
static char_t* _frm_msg_new = "New message: from=%d, to=%d, timestamp=%lld, text=%s\n";
//! log API
//! @{
static char_t* _frm_msg_io = "dev=%d, message: from=%d, to=%d, timestamp=%lld, text=%s\n";
static char_t* _frm_msg_new = "new message: from=%d, to=%d, timestamp=%lld, text=%s\n";
#define _HEAD_SIZE 25
/*!
* Initialize log functionality
* @return The status of the operation
*/
status_t log_init (void) {
// Try to initialize pthreads for logging
if (pthread_mutex_init(&lock_stderr, NULL) != 0) {
fprintf (stderr, "Error %s: mutex init has failed\n", __FUNCTION__ );
return MSG_ERROR;
@@ -76,41 +116,74 @@ status_t log_init (void) {
return MSG_OK;
}
void log_msg_io (msg_t* msg) {
/*!
* Logs incoming messages
* @param msg Pointer to msg to log
* @note
* This function depends on \sa settings.outLevel
*/
void log_msg_in (msg_t* msg) {
if (settings.outLevel >= OUTLEVEL_1) {
char_t head[_HEAD_SIZE];
memcpy (head, msg->cMsg.text, (_HEAD_SIZE-1));
head[_HEAD_SIZE-1] = 0;
pthread_mutex_lock(&lock_stdout);
fprintf (stdout, _frm_msg_io,
pthread_mutex_lock(&lock_stdout); // lock stdout
fprintf (stdout, _frm_msg_in, // print and flush
msg->sender,
cMsg_getFrom (&msg->cMsg),
cMsg_getTo (&msg->cMsg),
cMsg_getTs (&msg->cMsg),
head
msg->cMsg.from,
msg->cMsg.to,
msg->cMsg.ts,
msg->cMsg.text
);
fflush(stdout);
pthread_mutex_unlock(&lock_stdout);
pthread_mutex_unlock(&lock_stdout); // unlock stdout
}
}
/*!
* Logs outgoing messages
* @param msg Pointer to msg to log
* @param dev device that accepts the message
* @note
* This function depends on \sa settings.outLevel
*/
void log_msg_out (msg_t* msg, devAEM_t dev) {
if (settings.outLevel >= OUTLEVEL_1) {
pthread_mutex_lock(&lock_stdout); // lock stdout
fprintf (stdout, _frm_msg_out, // print and flush
dev,
msg->cMsg.from,
msg->cMsg.to,
msg->cMsg.ts,
msg->cMsg.text
);
fflush(stdout);
pthread_mutex_unlock(&lock_stdout); // unlock stdout
}
}
/*!
* Logs new messages
* @param msg Pointer to msg to log
* @note
* This function depends on \sa settings.outLevel
*/
void log_msg_new (msg_t* msg) {
if (settings.outLevel >= OUTLEVEL_1) {
char_t head[_HEAD_SIZE];
memcpy (head, msg->cMsg.text, (_HEAD_SIZE-1));
head[_HEAD_SIZE-1] = 0;
pthread_mutex_lock(&lock_stdout);
fprintf (stdout, _frm_msg_new,
cMsg_getFrom (&msg->cMsg),
cMsg_getTo (&msg->cMsg),
cMsg_getTs (&msg->cMsg),
head
pthread_mutex_lock(&lock_stdout); // lock stdout
fprintf (stdout, _frm_msg_new, // print and flush
msg->cMsg.from,
msg->cMsg.to,
msg->cMsg.ts,
msg->cMsg.text
);
fflush(stdout);
pthread_mutex_unlock(&lock_stdout);
pthread_mutex_unlock(&lock_stdout); // unlock stdout
}
}
/*!
* Debug message log to stdout
* Variadic formating print
* @param fmt Pointer to printf like format string
*/
void log_debug (const char *fmt, ...) {
if (settings.outLevel >= OUTLEVEL_2) {
va_list ap;
@@ -123,6 +196,11 @@ void log_debug (const char *fmt, ...) {
}
}
/*!
* Debug error message log to stderr
* Variadic formating print
* @param fmt Pointer to printf like format string
*/
void log_error (const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
@@ -133,7 +211,6 @@ void log_error (const char *fmt, ...) {
va_end(ap);
}
//! @}
//! cMsg_t API
@@ -157,7 +234,14 @@ void cMsg_make (cMsg_t* msg) {
sprintf (msg->text, "%s #%d", MESSAGE_BODY, msgID++);
}
size_t cMsg_cat (cMsg_t* msg, char_t* buffer) {
/*!
* Message concatenation
* This function synthesize the ascii message for transmission
* @param msg Pointer to message to serialize
* @param buffer Pointer to output buffer
* @return The size of the resulting message
*/
size_t cMsg_serialize (cMsg_t* msg, char_t* buffer) {
return sprintf (buffer, "%d_%d_%lld_%s",
msg->from,
msg->to,
@@ -166,7 +250,17 @@ size_t cMsg_cat (cMsg_t* msg, char_t* buffer) {
);
}
char_t* _strtok (char_t* str, char_t c, size_t max) {
/*!
* Custom strtok functionality
* @param str Pointer to string to parse
* @param max The size of string
* @param c Single delimiter character (non compatible with strtok())
* @return Pointer to token (non compatible with strtok())
* @note
* This function alters the given string by adding null termination in the places
* of delimiters
*/
char_t* _strtok (char_t* str, size_t max, char_t c) {
static char_t* last = NULL;
char_t* ret = str;
@@ -206,7 +300,7 @@ status_t cMsg_parse (cMsg_t* cMsg, char_t* rawMsg, size_t size) {
bool_t done = true;
for (size_t i =0; i < 3; ++i) {
tok[i] = _strtok (rest, MSG_DELIMITER, size);
tok[i] = _strtok (rest, size, MSG_DELIMITER);
if (tok[i] == NULL) {
done = false;
@@ -260,20 +354,18 @@ bool_t cMsg_equal (cMsg_t* m1, cMsg_t* m2) {
* mgs_t API
*/
//! @{
/*!
* message initialization
* @param msg
*/
void msg_init (msg_t* msg) {
memset ((void*)msg, 0, sizeof(msg));
memset ((void*)msg, 0, sizeof(msg_t)); // init to 0
}
//! @}
/*!
* Create a message list for our application.
*/
msgList_t msgList;
//! msgList API
//! @{
@@ -287,6 +379,11 @@ msgList_t msgList;
if (test < value) apply = value; \
while (0)
/*!
* Returns an iterator for \sa devList AND \sa msg_t.recipients
* @param dev The device to search
* @return The iterator, namely the index to devList array in which is the \p dev
*/
dIter_t devList_getIter (devAEM_t dev) {
for (dIter_t i =0 ; i<AEMLIST_SIZE ; ++i) {
if (devList[i].dev == dev)
@@ -295,7 +392,11 @@ dIter_t devList_getIter (devAEM_t dev) {
return -1; // return end()
}
/*!
* Initialize the msgList
* @param msgList Pointer to mesList t initialize
* @return The status of the operation
*/
status_t msgList_init (msgList_t* msgList) {
if (pthread_mutex_init(&lock_msgList, NULL) != 0) {
log_error ("Error: mutex init has failed\n");
@@ -338,14 +439,54 @@ mIter_t msgList_preDec (mIter_t* it) {
return *it;
}
/*!
* @param this Pointer to msgList to use
* @return An iterator to the first message of \sa MSG_LIST_SIZE
* of msgList.m[]
* @note
* As the msgList is a ring buffer we can not have a sensible end() iterator.
* end() will eventually merge with begin() when the size reaches \sa MSG_LIST_SIZE
* For that reason in all of our loops through msgList we shall take a begin()
* iterator and loop using size as sentinel
* @example
* @code{.c}
* mIter_t it = msgList_begin (&msgList); // get a message iterator
* size_t size= msgList_size(&msgList); // get current msgList size
* for (size_t i=0 ; i<size ; ++i, msgList_preInc (&it)) { // don't forget to increase iterator
* // use msgList[it]
* }
* @endcode
*/
mIter_t msgList_begin (msgList_t* this) {
return this->first;
}
/*!
* @param this Pointer to msgList to use
* @return An iterator to the last inserted message of \sa MSG_LIST_SIZE
* of msgList.m[]
*/
mIter_t msgList_last (msgList_t* this) {
return this->last;
}
/*!
* @param this Pointer to msgList to use
* @return The current used slots of msgList
* @note
* As the msgList is a ring buffer we can not have a sensible end() iterator.
* end() will eventually merge with begin() when the size reaches \sa MSG_LIST_SIZE
* For that reason in all of our loops through msgList we shall take a begin()
* iterator and loop using size as sentinel
* @example
* @code{.c}
* mIter_t it = msgList_begin (&msgList); // get a message iterator
* size_t size= msgList_size(&msgList); // get current msgList size
* for (size_t i=0 ; i<size ; ++i, msgList_preInc (&it)) { // don't forget to increase iterator
* // use msgList[it]
* }
* @endcode
*/
size_t msgList_size (msgList_t* this) {
return this->size;
}
@@ -392,7 +533,9 @@ mIter_t msgList_add (msgList_t* this, msg_t* msg) {
}
//! Acquires msgList resources
void msgList_acquire () { pthread_mutex_lock (&lock_msgList); }
//! releases msgList resources
void msgList_release () { pthread_mutex_unlock (&lock_msgList); }
//! @}
@@ -400,6 +543,11 @@ void msgList_release () { pthread_mutex_unlock (&lock_msgList); }
//! Statistics API
//! @{
/*!
* Initialize statistics
* @param s Pointer to \sa stat_t struct to initialize
* @return The status of the operation
*/
status_t stats_init (stats_t* s) {
memset ((void*)s, 0, sizeof (stats_t));
if (pthread_mutex_init(&lock_stats, NULL) != 0) {
@@ -409,6 +557,10 @@ status_t stats_init (stats_t* s) {
return MSG_OK;
}
/*!
* Update statistics for newly created messages
* @param msg Pointer to msg
*/
void statsUpdateCreate (msg_t* msg) {
pthread_mutex_lock (&lock_stats);
@@ -418,6 +570,7 @@ void statsUpdateCreate (msg_t* msg) {
// average message size
int32_t saved = stats.totalMsg - stats.duplicateMsg;
if ((saved-1) > 0) {
// Append to average
int32_t l = strlen(msg->cMsg.text);
stats.avMsgSize += l / (fpdata_t)(saved -1);
stats.avMsgSize *= (fpdata_t)(saved-1)/saved;
@@ -425,6 +578,11 @@ void statsUpdateCreate (msg_t* msg) {
pthread_mutex_unlock (&lock_stats);
}
/*!
* Update statistics for incoming message
* @param msg Pointer to incoming message
* @param dup Flag to indicate if the message was duplicate
*/
void statsUpdateIn (msg_t* msg, bool_t dup) {
pthread_mutex_lock (&lock_stats);
@@ -437,11 +595,13 @@ void statsUpdateIn (msg_t* msg, bool_t dup) {
// averages
int32_t saved = stats.totalMsg - stats.duplicateMsg;
if ((saved-1) > 0) {
// Append to message size average
int32_t l = strlen(msg->cMsg.text);
stats.avMsgSize += l / (fpdata_t)(saved -1);
stats.avMsgSize *= (fpdata_t)(saved-1)/saved;
if (settings.trackTime) {
// append to time to me average
tstamp_t dt = (tstamp_t)time(NULL) - msg->cMsg.ts;
if (dt < 0)
dt = 0;
@@ -452,27 +612,37 @@ void statsUpdateIn (msg_t* msg, bool_t dup) {
pthread_mutex_unlock (&lock_stats);
}
/*!
* Update statistics for outgoing message
* @param msg Pointer to message
* @param dev The recipient device
*/
void statsUpdateOut (msg_t* msg, devAEM_t dev) {
pthread_mutex_lock (&lock_stats);
stats.outDirectMsg += (msg->cMsg.to == dev) ? 1:0;
pthread_mutex_unlock (&lock_stats);
}
/*!
* Statistics print functionality
* @param stats Pointer to stats to print
* @return The status of the operation
*/
status_t statsPrint (stats_t* stats) {
FILE* fp = fopen ("statistics.txt", "w");
if (fp == NULL) {
fclose (fp);
return MSG_ERROR;
}
fprintf (fp, "\nStatistics\n");
fprintf (fp, " total messages: %d\n", stats->totalMsg);
fprintf (fp, " duplicate messages: %d\n", stats->duplicateMsg);
fprintf (fp, " messages for me: %d\n", stats->forMeMsg);
fprintf (fp, " messages by me: %d\n",stats->myMsg);
fprintf (fp, " In messages direct for me: %d\n", stats->inDirectMsg);
fprintf (fp, " Out direct messages: %d\n", stats->outDirectMsg);
fprintf (fp, " Average message size: %g\n", stats->avMsgSize);
fprintf (fp, " Average time to me: %g\n", stats->avTimeToMe);
fprintf (fp, "\n Statistics\n============\n");
fprintf (fp, "Total messages: %d\n", stats->totalMsg);
fprintf (fp, "Duplicate messages: %d\n", stats->duplicateMsg);
fprintf (fp, "Messages for me: %d\n", stats->forMeMsg);
fprintf (fp, "Messages by me: %d\n",stats->myMsg);
fprintf (fp, "In messages direct for me: %d\n", stats->inDirectMsg);
fprintf (fp, "Out direct messages: %d\n", stats->outDirectMsg);
fprintf (fp, "Average message size: %g\n", stats->avMsgSize);
fprintf (fp, "Average time to me: %g\n", stats->avTimeToMe);
for (size_t i =0 ; i<AEMLIST_SIZE ; ++i) {
fprintf (fp, " Device %u found on %lld, last: %lld\n",
+10 -13
View File
@@ -4,8 +4,8 @@
* \author Christos Choutouridis AEM:8997 <cchoutou@ece.auth.gr>
*/
#ifndef __core__
#define __core__
#ifndef __core_h__
#define __core_h__
#include <netinet/in.h>
@@ -13,14 +13,13 @@
extern msgList_t msgList;
devAEM_t addr2devAEM (uint32_t in_addr);
devAEM_t addr2devAEM (in_addr_t in_addr);
in_addr_t devAEM2addr (devAEM_t dev);
devAEM_t ip2AEM (devIP_t* ip);
devIP_t AEM2ip (devAEM_t dev);
devIP_t addr2ip (in_addr_t in_addr);
void cMsg_make (cMsg_t* msg);
size_t cMsg_cat (cMsg_t* msg, char_t* buffer);
size_t cMsg_serialize (cMsg_t* msg, char_t* buffer);
status_t cMsg_parse (cMsg_t* cMsg, char_t* rawMsg, size_t size);
uint32_t cMsg_getFrom (cMsg_t* cMsg);
uint32_t cMsg_getTo (cMsg_t* cMsg);
@@ -38,25 +37,23 @@ status_t msgList_init (msgList_t* msgList);
mIter_t msgList_begin (msgList_t* this);
mIter_t msgList_last (msgList_t* this);
size_t msgList_size (msgList_t* this);
mIter_t msgList_find (msgList_t* this, msg_t* msg);
mIter_t msgList_add (msgList_t* this, msg_t* msg);
void msgList_acquire ();
void msgList_release ();
status_t stats_init (stats_t* s);
void statsUpdateCreate (msg_t* msg);
void statsUpdateIn (msg_t* msg, bool_t dup);
void statsUpdateOut (msg_t* msg, devAEM_t dev);
void statsUpdateCreate (msg_t* msg);
void statsUpdateIn (msg_t* msg, bool_t dup);
void statsUpdateOut (msg_t* msg, devAEM_t dev);
status_t statsPrint (stats_t* stats);
status_t log_init(void);
void log_msg_io (msg_t* msg);
void log_msg_in (msg_t* msg);
void log_msg_out (msg_t* msg, devAEM_t dev);
void log_msg_new (msg_t* msg);
void log_debug (const char *fmt, ...);
void log_error (const char *fmt, ...);
#endif /* __core__ */
#endif /* __core_h__ */
+4 -1
View File
@@ -35,15 +35,18 @@ static void listen_handler (devAEM_t dev, char_t* buffer, size_t size) {
if (myCopy == -1) {
// We don't have a copy, accept and store it
msgList_add (&msgList, &msg);
msgList_release ();
statsUpdateIn (&msg, false); // message process
log_msg_io (&msg); // log
log_msg_in (&msg); // log
}
else {
// We have a copy
msgList_release ();
statsUpdateIn (&msg, true); // message process
log_debug("Debug: Duplicate message from: %d\n", msg.sender);
}
// Processing...
msgList_acquire ();
// Do not echo message to sender, he already has it
msgList.m[myCopy].recipients[devList_getIter (dev)] = true;
// don't push back message to creator, he already has it
+9 -9
View File
@@ -1,3 +1,10 @@
/*!
* \file main.c
* This is the main file of the RTES final task
*
* \author Christos Choutouridis AEM:8997 <cchoutou@ece.auth.gr>
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
@@ -40,13 +47,6 @@ const struct option long_opt[] = {
{NULL, 0, NULL, 0}
};
//// Interrupt handler
//void intHandler(int dummy) {
// (void)dummy;
// statsPrint (&stats);
// exit (0);
//}
/*!
* \brief
* Parse input argument and fill the kcli_input_t struct
@@ -92,12 +92,12 @@ int parse_args (settings_t *s, int argc, char const *argv[]) {
int main(int argc, char const *argv[]) {
parse_args (&settings, argc, argv);
// Initialize all subsystems
log_init ();
stats_init (&stats);
msgList_init (&msgList);
// if (signal(SIGTERM, intHandler) == SIG_ERR) //catching interrupt
// log_error("Error: Can not catch SIGINT\n");
// Create threads
pthread_t ptL, ptC;
pthread_create (&ptL, NULL, pthListener, NULL);
-806
View File
@@ -1,806 +0,0 @@
#define DEBUG
#define FU08 "%hhu"
#define FU16 "%hu"
#define FU32 "%lu"
#define FU64 "%llu"
#define FSTR "%s"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
//--Tools Module
#include <time.h>
uint64_t TIME_u64Current(void) {
return time(NULL);
}
uint16_t RAND_u16GetNumber(uint16_t u16Min, uint16_t u16Max) {
static uint8_t i = 0;
if (i == 0) {
srand(time(NULL));
i++;
}
return rand() % (u16Max + 1 - u16Min) + u16Min;
}
//--Log Module
#include <stdarg.h>
sem_t semLog;
void LOG_vSetup(void) {
sem_init(&semLog, 0, 1);
}
void LOG_vPrintf(const char* format, ...) {
sem_wait(&semLog);
va_list args;
va_start(args, format);
#ifdef DEBUG
printf(FU64":", TIME_u64Current());
vprintf(format, args);
#endif
FILE* fp;
fp = fopen("/tmp/log.txt", "a");
if (fp != NULL) {
fprintf(fp, FU64":", TIME_u64Current());
vfprintf(fp, format, args);
fclose(fp);
}
va_end(args);
sem_post(&semLog);
}
//--File Module
#define FILE_EOF 0xFF
int8_t FILE_i08Compare(char* pchPath1, char* pchPath2) {
FILE* file1 = fopen(pchPath1, "r");
FILE* file2 = fopen(pchPath2, "r");
if (file1 == NULL) {
if (file2 != NULL)
fclose(file2);
return 1;
}
if (file2 == NULL) {
fclose(file1);
return 2;
}
char ch1, ch2;
do {
ch1 = fgetc(file1);
ch2 = fgetc(file2);
if (ch1 != ch2) {
fclose(file1);
fclose(file2);
return 0;
}
} while (ch1 != FILE_EOF && ch2 != FILE_EOF);
if (ch1 == FILE_EOF && ch2 == FILE_EOF) {
fclose(file1);
fclose(file2);
return 3;
}
else {
fclose(file1);
fclose(file2);
return 0;
}
}
//--WiFi Module
#define NETWORK_TYPE "wlan0"
#include <arpa/inet.h>
#include <sys/socket.h>
#define WIFI_BUFFER 2000
#include <pthread.h>
struct ParserArgs {
int sock;
struct sockaddr_in client_address;
socklen_t client_address_len;
bool (*bParse)(uint8_t* pu08Address, char* pchBuffer);
};
void WiFi_vParser(void* ptr) {
struct ParserArgs temp;
memcpy(&temp, ptr, sizeof(struct ParserArgs));
char pchRemoteAddress[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(temp.client_address.sin_addr), pchRemoteAddress, INET_ADDRSTRLEN);
//uint16_t pu16RemotePort = temp.client_address.sin_port;
char pchBuffer[WIFI_BUFFER];
char* pchTemp = (char*)pchBuffer;
int16_t i16New = 0;
uint16_t u16Length = 0;
uint16_t u16Remaining = WIFI_BUFFER;
while ((i16New = recv(temp.sock, pchTemp, u16Remaining, 0)) > 0) {
pchTemp += i16New;
u16Remaining -= i16New;
u16Length += i16New;
pchTemp[0] = '\0';
}
uint8_t pu08Levels[4];
sscanf(pchRemoteAddress, FU08"."FU08"."FU08"."FU08, &pu08Levels[0], &pu08Levels[1], &pu08Levels[2], &pu08Levels[3]);
temp.bParse(pu08Levels, pchBuffer);
close(temp.sock);
}
bool WiFi_bListener(int32_t i32ServerPort, bool (*bParse)(uint8_t* pu08Address, char* pchBuffer)) {
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(i32ServerPort);
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
int listen_sock;
if ((listen_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
return false;
if ((bind(listen_sock, (struct sockaddr *)&server_address, sizeof(server_address))) == -1) {
close(listen_sock);
return false;
}
if (listen(listen_sock, WIFI_BUFFER) == -1) {
close(listen_sock);
return false;
}
while (true) {
LOG_vPrintf("WiFiListener-New\n");
struct ParserArgs client;
client.client_address_len = sizeof(client.client_address);
client.bParse = bParse;
LOG_vPrintf("WiFiListener-Start\n");
if ((client.sock = accept(listen_sock, (struct sockaddr *)&client.client_address, &client.client_address_len)) == -1) {
return false;
}
WiFi_vParser(&client);
LOG_vPrintf("WiFiListener-Stop\n");
}
close(listen_sock);
return true;
}
bool WiFi_bSend(char* pchServerAddress, int32_t i32ServerPort, char* pchServerText) {
LOG_vPrintf("WiFi-Send-Sock\n");
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
LOG_vPrintf("WiFi-Send-Fail\n");
return false;
}
LOG_vPrintf("WiFi-Send-Init\n");
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(pchServerAddress);
server_address.sin_port = htons(i32ServerPort);
LOG_vPrintf("WiFi-Send-Connect\n");
if (connect(sock, (struct sockaddr*)&server_address, sizeof(server_address)) == -1) {
LOG_vPrintf("WiFi-Send-Fail\n");
close(sock);
return false;
}
LOG_vPrintf("WiFi-Send-Send\n");
if (send(sock, pchServerText, strlen(pchServerText), MSG_CONFIRM) == -1) {
LOG_vPrintf("WiFi-Send-NoConfirmation\n");
close(sock);
return false;
}
LOG_vPrintf("WiFi-Send-Close\n");
close(sock);
return true;
}
//--Messages Module
#define PAYLOAD_SIZE 256
#define PAYLOAD_DELIMITER '_'
#define MESSAGES_SIZE 2000
typedef struct tMessage {
uint32_t u32Sender;
uint32_t u32Receiver;
uint64_t u64Timestamp;
char pchMessage[PAYLOAD_SIZE];
bool bDone;
uint32_t* pu32Sent;
uint32_t u32Sent;
} sMessage;
typedef struct tMessages {
uint32_t u32Owner;
sMessage psArray[MESSAGES_SIZE];
uint16_t u16ArrayIndex;
bool bFull;
uint32_t u32CheckedMessages;
uint32_t u32LoggedMessages;
sem_t semAccess;
} sMessages;
void MSG_vSetup(sMessages* psMessages, uint32_t u32Owner) {
sem_init(&psMessages->semAccess, 0, 1);
psMessages->u32Owner = u32Owner;
psMessages->u16ArrayIndex = 0;
psMessages->bFull = false;
psMessages->u32CheckedMessages = 0;
psMessages->u32LoggedMessages = 0;
}
static inline sMessage* MSG_mGet(sMessages* psMessages, uint16_t u16Index) {
//sem_wait(&semMessages);
sMessage* temp;
if (psMessages->bFull) {
temp = &psMessages->psArray[(psMessages->u16ArrayIndex + u16Index) % MESSAGES_SIZE];
} else
temp = &psMessages->psArray[u16Index];
//sem_post(&semMessages);
return temp;
}
static inline uint16_t MSG_u16Length(sMessages* psMessages) {
//sem_wait(&semMessages);
uint16_t temp;
if (psMessages->bFull)
temp = MESSAGES_SIZE;
else
temp = psMessages->u16ArrayIndex;
//sem_post(&semMessages);
return temp;
}
void MSG_vInsert(sMessages* psMessages, sMessage* psMessage, bool bSent, uint32_t u32Device) {
sem_wait(&psMessages->semAccess);
psMessages->psArray[psMessages->u16ArrayIndex].u32Sender = psMessage->u32Sender;
psMessages->psArray[psMessages->u16ArrayIndex].u32Receiver = psMessage->u32Receiver;
psMessages->psArray[psMessages->u16ArrayIndex].u64Timestamp = psMessage->u64Timestamp;
psMessages->psArray[psMessages->u16ArrayIndex].bDone = (psMessage->u32Receiver == psMessages->u32Owner);
memcpy(psMessages->psArray[psMessages->u16ArrayIndex].pchMessage, psMessage->pchMessage, strlen(psMessage->pchMessage));
if (bSent) {
psMessages->psArray[psMessages->u16ArrayIndex].u32Sent = 1;
psMessages->psArray[psMessages->u16ArrayIndex].pu32Sent = (uint32_t*)malloc(1 * sizeof(uint32_t));
psMessages->psArray[psMessages->u16ArrayIndex].pu32Sent[0] = u32Device;
}
else
psMessages->psArray[psMessages->u16ArrayIndex].u32Sent = 0;
psMessages->u16ArrayIndex = (psMessages->u16ArrayIndex + 1) % MESSAGES_SIZE;
if (psMessages->u16ArrayIndex == 0)
psMessages->bFull = true;
psMessages->u32LoggedMessages++;
sem_post(&psMessages->semAccess);
}
bool MSG_bCheck(sMessages* psMessages, sMessage* psMessage) {
sem_wait(&psMessages->semAccess);
uint16_t u16ArrayLength = MSG_u16Length(psMessages);
bool flag = false;
for (uint16_t i = 0; i < u16ArrayLength; i++) {
sMessage* temp = MSG_mGet(psMessages, i);
if (temp->u32Sender != psMessage->u32Sender)
continue;
if (temp->u32Receiver != psMessage->u32Receiver)
continue;
if (temp->u64Timestamp != psMessage->u64Timestamp)
continue;
if (strcmp(temp->pchMessage, psMessage->pchMessage) != 0)
continue;
flag = true;
break;
}
psMessages->u32CheckedMessages++;
sem_post(&psMessages->semAccess);
return flag;
}
bool MSG_bParse(sMessage* psMessage, char* pchBuffer) {
char* pchArrays[4];
bool bFlag = false;
uint16_t i;
char* s = pchBuffer;
for (i = 0; s[i]; s[i] == PAYLOAD_DELIMITER ? i++ : *s++);
if (i != 3)
return false;
char* pchRest = pchBuffer;
for (uint8_t i = 0; i < 3; i++) {
const char s[2] = { PAYLOAD_DELIMITER, '\0'};
pchArrays[i] = strtok(pchRest, s);
if (pchArrays[i] == NULL) {
bFlag = true;
break;
} else {
pchRest += strlen(pchRest) + 1;
}
}
pchArrays[3] = pchRest;
if (!bFlag) {
psMessage->u32Sender = atoi(pchArrays[0]);
psMessage->u32Receiver = atoi(pchArrays[1]);
psMessage->u64Timestamp = atoi(pchArrays[2]);
strcpy(psMessage->pchMessage, pchArrays[3]);
}
return (!bFlag);
}
void MSG_vExport(sMessages* psMessages) {
sem_wait(&psMessages->semAccess);
uint16_t u16ArrayLength = MSG_u16Length(psMessages);
FILE* file = fopen("/tmp/messages.txt", "w");
if (file == NULL) {
sem_post(&psMessages->semAccess);
return;
}
fprintf(file, "Checked:"FU32"\n", psMessages->u32CheckedMessages);
fprintf(file, "Logged:"FU32"\n", psMessages->u32LoggedMessages);
fprintf(file, "Index:"FU32"\n", psMessages->u16ArrayIndex);
fprintf(file, "index:sender_receiver_timestamp_message:sent:done\n");
for (uint16_t i = 0; i < u16ArrayLength; i++) {
sMessage* temp = MSG_mGet(psMessages, i);
fprintf(file, FU16":"FU32"_"FU32"_"FU64"_"FSTR":"FU32":"FU08"\n", i, temp->u32Sender, temp->u32Receiver, temp->u64Timestamp, temp->pchMessage, temp->u32Sent, (temp->bDone ? 1 : 0));
}
fclose(file);
sem_post(&psMessages->semAccess);
}
void MSG_vSend(sMessages* psMessages, uint32_t u32Receiver, bool (*bSend)(char* pchBuffer)) {
sem_wait(&psMessages->semAccess);
uint16_t u16Length;
if (psMessages->bFull)
u16Length = MESSAGES_SIZE;
else
u16Length = psMessages->u16ArrayIndex;
for (uint16_t i = 0; i < u16Length; i++) {
sMessage* temp = MSG_mGet(psMessages, i);
bool bFlag = false;
if (temp->bDone)
bFlag = true;
else {
for (uint32_t j = 0 ; j < temp->u32Sent; j++) {
if (temp->pu32Sent[j] == u32Receiver) {
bFlag = true;
break;
}
}
}
if (bFlag)
continue;
else {
LOG_vPrintf("Message-Send-"FU32"-Start\n", i);
char pchBuffer[5 + 5 + 3 + 10 + 256];
sprintf(pchBuffer, FU32"_"FU32"_"FU64"_"FSTR, temp->u32Sender, temp->u32Receiver, temp->u64Timestamp, temp->pchMessage);
LOG_vPrintf("Message-Send-"FU32"-Send\n", i);
if (bSend(pchBuffer)) {
if (temp->u32Sent == 0)
temp->pu32Sent = (uint32_t*)malloc(1 * sizeof(uint32_t));
else
temp->pu32Sent = (uint32_t*)realloc(temp->pu32Sent, (temp->u32Sent + 1) * sizeof(uint32_t));
temp->pu32Sent[temp->u32Sent] = u32Receiver;
temp->u32Sent++;
temp->bDone = (temp->u32Receiver == u32Receiver);
} else {
LOG_vPrintf("Message-Send-"FU32"-Error\n", i);
}
LOG_vPrintf("Message-Send-"FU32"-Stop\n", i);
}
}
sem_post(&psMessages->semAccess);
}
sMessages sMessagesList;
//--Devices Module
#define DEVICES_SIZE 100
typedef struct tDevice {
uint32_t u32Id;
bool bActive;
uint64_t u64Start;
uint64_t u64Last;
} sDevice;
typedef struct tDevices {
sDevice psArray[DEVICES_SIZE];
uint16_t u16ArrayIndex;
bool bFull;
sem_t semAccess;
} sDevices;
void DVC_vSetup(sDevices* psDevices) {
sem_init(&psDevices->semAccess, 0, 1);
psDevices->u16ArrayIndex = 0;
psDevices->bFull = false;
}
void DVC_vInsert(sDevices* psDevices, uint16_t u32Id) {
//sem_wait(&semDevices);
psDevices->psArray[psDevices->u16ArrayIndex].u32Id = u32Id;
psDevices->psArray[psDevices->u16ArrayIndex].bActive = true;
psDevices->psArray[psDevices->u16ArrayIndex].u64Start = TIME_u64Current();
psDevices->psArray[psDevices->u16ArrayIndex].u64Last = 0;
psDevices->u16ArrayIndex = (psDevices->u16ArrayIndex + 1) % DEVICES_SIZE;
if (psDevices->u16ArrayIndex == 0)
psDevices->bFull = true;
//sem_post(&semDevices);
}
uint16_t DVC_u16Update(sDevices* psDevices, uint32_t* pu32Id, uint16_t u16IdSize, uint32_t* pu32New) {
sem_wait(&psDevices->semAccess);
uint16_t u16ArrayLength;
if (psDevices->bFull)
u16ArrayLength = DEVICES_SIZE;
else
u16ArrayLength = psDevices->u16ArrayIndex;
bool pbFlag[u16IdSize];
for (uint16_t j = 0; j < u16IdSize; j++) {
pbFlag[j] = false;
}
for (uint16_t i = 0; i < u16ArrayLength; i++) {
bool bFlag = false;
for (uint16_t j = 0; j < u16IdSize; j++) {
if (psDevices->psArray[i].u32Id == pu32Id[j]) {
bFlag = true;
pbFlag[j] = true;
break;
}
}
if (bFlag) {
if (psDevices->psArray[i].bActive)
psDevices->psArray[i].u64Last = TIME_u64Current();
else {
psDevices->psArray[i].bActive = true;
psDevices->psArray[i].u64Start = TIME_u64Current();
psDevices->psArray[i].u64Last = 0;
}
} else {
psDevices->psArray[i].bActive = false;
}
}
uint16_t u16Cnt = 0;
for (uint16_t j = 0; j < u16IdSize; j++) {
if (!pbFlag[j]) {
DVC_vInsert(psDevices, pu32Id[j]);
pu32New[u16Cnt] = pu32Id[j];
u16Cnt++;
}
}
sem_post(&psDevices->semAccess);
return u16Cnt;
}
void DVC_vExport(sDevices* psDevices) {
sem_wait(&psDevices->semAccess);
uint16_t u16ArrayLength;
if (psDevices->bFull)
u16ArrayLength = DEVICES_SIZE;
else
u16ArrayLength = psDevices->u16ArrayIndex;
FILE* file = fopen("/tmp/devices.txt", "w");
if (file == NULL) {
sem_post(&psDevices->semAccess);
return;
}
fprintf(file, FU32"\n", psDevices->u16ArrayIndex);
fprintf(file, "index:active,id,start,stop\n");
for (uint16_t i = 0; i < u16ArrayLength; i++)
fprintf(file, FU32":"FSTR","FU32","FU64","FU64"\n", i, psDevices->psArray[i].bActive ? "true" : "false", psDevices->psArray[i].u32Id, psDevices->psArray[i].u64Start, psDevices->psArray[i].u64Last);
fclose(file);
sem_post(&psDevices->semAccess);
}
sDevices sDevicesList;
//--Timer Module
#include <signal.h>
#include <sys/time.h>
typedef struct tInterrupt {
bool bRunning;
uint32_t u32Ticks;
void (*vCallback)(uint32_t);
} sInterrupt;
sInterrupt sTimer;
void TMR_vHandler(int sig) {
static uint32_t i = 0;
sTimer.vCallback(i - 1);
i++;
if (sTimer.u32Ticks > 0 && i >= sTimer.u32Ticks) {
struct itimerval sInterval = {0};
setitimer(ITIMER_REAL, &sInterval, NULL);
sTimer.bRunning = false;
}
}
bool TMR_bSetup(suseconds_t susInterval, void (*vCallback)(uint32_t)) {
sTimer.vCallback = vCallback;
sTimer.u32Ticks = 0;
sTimer.bRunning = true;
signal(SIGALRM, TMR_vHandler);
struct itimerval sInterval;
sInterval.it_interval.tv_usec = susInterval % 1000000;
sInterval.it_interval.tv_sec = susInterval / 1000000;
sInterval.it_value = sInterval.it_interval;
if (setitimer(ITIMER_REAL, &sInterval, NULL) != 0)
return false;
return true;
}
//--High Level Application
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define AEM 8844
#define SERVER_PORT 2288
#define INTERRUPTS
#ifdef INTERRUPTS
sem_t semSearcher;
#endif
const uint32_t pu32FriendsList[] = {7000, 7001, 7002, 7003, 8845};
const uint8_t u08FriendsSize = 5;
#define CREATE_PERIOD_MIN 1 //secs
#define CREATE_PERIOD_MAX 1 //secs
//#define CREATE_PERIOD_MIN 1*60 //secs
//#define CREATE_PERIOD_MAX 5*60 //secs
uint32_t u32Selector(void) {
static uint32_t count = 0;
count++;
uint8_t index = RAND_u16GetNumber(0, u08FriendsSize - 1);
sMessage temp;
temp.u32Sender = AEM;
temp.u32Receiver = pu32FriendsList[index];
temp.u64Timestamp = TIME_u64Current();
sprintf(temp.pchMessage, "I am message #%d of GKyri", count);
temp.u32Sent = 0;
LOG_vPrintf("Selector-Insert\n");
MSG_vInsert(&sMessagesList, &temp, false, 0);
/*
LOG_vPrintf("Selector-Export\n");
MSG_vExport(&sMessagesList);
*/
return pu32FriendsList[index];
}
void APP_vCallback(uint32_t u32Tick) {
static bool bRunning = false;
if (!bRunning) {
bRunning = true;
LOG_vPrintf("Callback-Start\n");
u32Selector();
LOG_vPrintf("Callback-Stop\n");
#ifdef INTERRUPTS
sem_post(&semSearcher);
#endif
bRunning = false;
}
}
void APP_vCreator(void) {
uint16_t u16Interval = RAND_u16GetNumber(CREATE_PERIOD_MIN, CREATE_PERIOD_MAX);
if (TMR_bSetup(500000, APP_vCallback)) {
//if (TMR_bSetup(u16Interval * 1000000, APP_vCallback)) {
while (true)
pause();
}
}
bool APP_bReceiveBuffer(uint8_t* pu08Address, char* pchBuffer) {
LOG_vPrintf("Receiver-Start\n");
uint32_t u32Id = (uint32_t)pu08Address[2] * 100 + pu08Address[3];
sMessage temp;
if (!MSG_bParse(&temp, pchBuffer))
return false;
temp.u32Sent = 0;
if (!MSG_bCheck(&sMessagesList, &temp)) {
LOG_vPrintf("Receiver-Insert\n");
MSG_vInsert(&sMessagesList, &temp, true, u32Id);
/*
LOG_vPrintf("Receiver-Export\n");
MSG_vExport(&sMessagesList);
*/
}
LOG_vPrintf("Receiver-Stop\n");
#ifdef INTERRUPTS
sem_post(&semSearcher);
#endif
return true;
}
void APP_vListener(void) {
WiFi_bListener(SERVER_PORT, APP_bReceiveBuffer);
}
char pchMessageReceiver[15 + 1];
bool APP_bSendBuffer(char* pchBuffer) {
return WiFi_bSend(pchMessageReceiver, SERVER_PORT, pchBuffer);
}
bool APP_bSender(uint32_t u32Receiver) {
sprintf(pchMessageReceiver, "10.0."FU08"."FU08, u32Receiver / 100, u32Receiver % 100);
char pchTest[13 + 15 + 12 + 1];
sprintf(pchTest, "ping -c1 -w1 "FSTR" > /dev/null", pchMessageReceiver);
if (system(pchTest) == 0) {
MSG_vSend(&sMessagesList, u32Receiver, APP_bSendBuffer);
return true;
} else {
return false;
}
}
#define SEARCHER_SLEEP_PERIOD 60 //secs
#define SEARCHER_SLEEP_DELAY 30 //secs
void APP_vSearcher(void) {
#ifdef INTERRUPTS
sem_init(&semSearcher, 0, 0);
#endif
sleep(SEARCHER_SLEEP_PERIOD);
while (true) {
LOG_vPrintf("Searcher-Start\n");
uint16_t u16Cnt = 0;
uint32_t* pu32Id = (uint32_t*)malloc(1 * sizeof(uint32_t));
for (uint8_t i = 0; i < u08FriendsSize; i++) {
uint32_t u32Receiver = pu32FriendsList[i];
sprintf(pchMessageReceiver, "10.0."FU08"."FU08, u32Receiver / 100, u32Receiver % 100);
char pchTest[13 + 15 + 12 + 1];
sprintf(pchTest, "ping -c1 -w1 "FSTR" > /dev/null", pchMessageReceiver);
if (system(pchTest) == 0) {
pu32Id[u16Cnt] = u32Receiver;
u16Cnt++;
pu32Id = (uint32_t*)realloc(pu32Id, (u16Cnt + 1) * sizeof(uint32_t));
}
}
LOG_vPrintf("Searcher-Send-Start\n");
uint32_t pu32New[u16Cnt];
//uint16_t u16NewLength = DVC_u16Update(&sDevicesList, pu32Id, u16Cnt, pu32New);
DVC_u16Update(&sDevicesList, pu32Id, u16Cnt, pu32New);
for (uint16_t i = 0; i < u16Cnt; i++) {
LOG_vPrintf("Searcher-Send-"FU32"-Start\n", i);
APP_bSender(pu32Id[i]);
LOG_vPrintf("Searcher-Send-"FU32"-Stop\n", i);
}
free(pu32Id);
LOG_vPrintf("Searcher-Send-Stop\n");
LOG_vPrintf("Searcher-Export\n");
DVC_vExport(&sDevicesList);
MSG_vExport(&sMessagesList);
LOG_vPrintf("Searcher-Stop\n");
#ifdef INTERRUPTS
for (uint16_t i = 0; i < SEARCHER_SLEEP_PERIOD; i++) {
int value;
sem_getvalue(&semSearcher, &value);
if (value > 0) {
if (i > SEARCHER_SLEEP_DELAY) {
LOG_vPrintf("Searcher-Interrupt\n");
sem_wait(&semSearcher);
break;
}
}
sleep(1);
}
#else
sleep(SLEEP_PERIOD);
#endif
}
}
void APP_vSetup(void){
int8_t i08Result;
bool bFlag = false;
i08Result = FILE_i08Compare("/root/wpa_supplicant.conf", "/etc/wpa_supplicant/wpa_supplicant.conf");
if (i08Result == 0 || i08Result == 2) {
bFlag = true;
LOG_vPrintf("Replacing 'wpa_supplicant'\n");
system("sudo cp /root/wpa_supplicant.conf /etc/wpa_supplicant/wpa_supplicant.conf");
}
i08Result = FILE_i08Compare("/root/interfaces", "/etc/network/interfaces");
if (i08Result == 0 || i08Result == 2) {
bFlag = true;
LOG_vPrintf("Replacing 'interfaces'\n");
system("sudo cp /root/interfaces /etc/network/interfaces");
}
i08Result = FILE_i08Compare("/root/messenger.service", "/etc/systemd/system/messenger.service");
if (i08Result == 0 || i08Result == 2) {
bFlag = true;
LOG_vPrintf("Replacing 'messenger.service'\n");
system("sudo cp /root/messenger.service /etc/systemd/system");
system("systemctl enable messenger");
}
if (bFlag) {
LOG_vPrintf("Restarting\n");
system("shutdown -r 0");
exit(EXIT_SUCCESS);
}
}
void* Th1Func(void* ptr) {
APP_vListener();
return NULL;
}
void* Th2Func(void* ptr) {
APP_vCreator();
return NULL;
}
void* Th3Func(void* ptr) {
APP_vSearcher();
return NULL;
}
int main( int argc, char* const* argv) {
APP_vSetup();
LOG_vSetup();
MSG_vSetup(&sMessagesList, AEM);
DVC_vSetup(&sDevicesList);
pthread_t thread1, thread2, thread3;
pthread_create( &thread1, NULL, Th1Func, NULL);
pthread_create( &thread2, NULL, Th2Func, NULL);
pthread_create( &thread3, NULL, Th3Func, NULL);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
pthread_join( thread3, NULL);
return EXIT_SUCCESS;
}
+3 -1
View File
@@ -23,7 +23,7 @@
#define devList_init(l) l = { \
{ 7700, 0, 0, 0}, \
{ 8000, 0, 0, 0}, \
{ 8261, 0, 0, 0}, \
{ 8765, 0, 0, 0}, \
{ 8844, 0, 0, 0}, \
{ 8880, 0, 0, 0}, \
@@ -218,6 +218,7 @@ typedef struct {
devAEM_t me;
uint16_t port;
time_t msgInterval;
time_t msgRand;
outLevel_en outLevel;
time_t pingTimeout;
timeval_t sendTimeout;
@@ -230,6 +231,7 @@ extern settings_t settings;
.me = 8997, \
.port = 2288, \
.msgInterval = 60, \
.msgRand = 240, \
.outLevel = OUTLEVEL_1, \
.pingTimeout = 1, \
.sendTimeout = {4, 0}, \