File size: 7,967 Bytes
fe84fce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
#include <filesystem>
#include <map>
#include <time.h>
#include <C:\Users\sriff\Downloads\Practicum_Stuff\SoftwareEngineeringTeam2Proj\ArduinoServerTest\include\asio-1.28.0\include\asio.hpp>
// #include <pqxx/pqxx> // <-- TODO: The library header isnt exactly a header and I'm stuck on how to approach getting it to include correctly

using namespace std;
using namespace asio;
using namespace asio::ip;
namespace fs = std::filesystem;

// Config file just for the port used? Too little I will pass for now
int portVal = 999;

// Global map to store open file streams for each MAC address
map<string, ofstream> macFiles;

/*
void setupDatabase() {
    try {
        // Establish a connection to the PostgreSQL database
        pqxx::connection conn("dbname=database user=postgres password=password hostaddr=127.0.0.1 port=5432");
        if (conn.is_open()) {
            cout << "Opened database successfully: " << conn.dbname() << endl;
        }
        else {
            cerr << "Failed to open database" << endl;
            return;
        }

        // Start a transaction
        pqxx::dbtransaction txn(conn);

        // Create a new table
        txn.exec("CREATE TABLE IF NOT EXISTS sensorTable ("
            "time VARCHAR(14),"
            "mac VARCHAR(17),"
            "sensorvalue VARCHAR(255)"
            ");");

        // Commit the transaction
        txn.commit();

        cout << "Database setup completed successfully" << endl;

        // Close the connection
        conn.close();
    }
    catch (const exception& e) {
        cerr << e.what() << endl;
    }
}
*/

/*
 // Function to send sensor data to postgresql database
void saveToDatabase(const string& pkg) {
    try {
        // Establish a connection to the PostgreSQL database
        pqxx::connection conn("dbname=database user=postgres password=password hostaddr=127.0.0.1 port=5432");

        if (conn.is_open()) {
            cout << "Opened database successfully: " << conn.dbname() << endl;
        }
        else {
            cerr << "Failed to open database" << endl;
            return;
        }

        // Create a transaction
        pqxx::work txn(conn);

        // Prepare the query string
        std::stringstream query;
        query << "INSERT INTO sensorTable (time, mac, sensorvalue) VALUES ("
            << pkg.substr(0, 14) << ", '"  // Assuming time is the first 14 characters
            << pkg.substr(15, 17) << "', " // Assuming mac address is from character 15 to 31
            << pkg.substr(33) << ")";      // Assuming sensor value is after the mac address

        // Execute the query
        txn.exec(query.str());

        // Commit the transaction
        txn.commit();

        cout << "Records inserted successfully" << endl;

        // Close the connection
        conn.close();
    }
    catch (const exception& e) {
        cerr << e.what() << endl;
    }
}
*/

// Function to write sensor data to log files
void writeToLog(const string& macAddress, const string& data) {
    // Check if a /log directory exists
    fs::path logDir = fs::path(fs::current_path()) / "log";
    if (!fs::exists(logDir) || !fs::is_directory(logDir)) {
        fs::create_directory(logDir);
    }

    // Filesystem cannot create a new file with ':' in the filename
    string macAddressStripped = macAddress;
    macAddressStripped.erase(remove(macAddressStripped.begin(), macAddressStripped.end(), ':'), macAddressStripped.end());

    // Check if a file for the MAC address exists
    fs::path filePath = logDir / (macAddressStripped + ".csv");
    if (!fs::exists(filePath)) {
        // Create a new file for the MAC address
        ofstream newFile(filePath);
        if (newFile.is_open()) {
            newFile << data << endl;
            newFile.close();
        }
    }
    // Existing MAC address, append to the existing file
    else {
        ofstream existingFile(filePath, ios_base::app);
        if (existingFile.is_open()) {
            existingFile << data << endl;
            existingFile.close();
        }
    }
}

// Function to parse sensor data and write to appropriate log files
void parseAndWriteMAC(const string& csvData) {
    istringstream iss(csvData);

    string line;
    while (getline(iss, line)) {
        istringstream lineStream(line);
        vector<string> tokens;
        string token;
        while (getline(lineStream, token, ',')) {
            tokens.push_back(token);
        }

        if (tokens.size() >= 2) {
            string macAddress = tokens[1];
            auto it = macFiles.find(macAddress);
            if (it == macFiles.end()) {
                // New MAC address, create a new file stream and call writeToLog
                ofstream newFile;
                macFiles[macAddress] = move(newFile);
                writeToLog(macAddress, line);
            }
            else {
                // Existing MAC address, write to the existing file stream and call writeToLog
                writeToLog(macAddress, line);
            }
        }
    }
}

int main() {
    // Initialize the postgresql database
    //setupDatabase();

    // Show me the ip address (maybe save it in a variable for later)
    try {
        io_context io_context;
        tcp::resolver resolver(io_context);
        tcp::resolver::query query(host_name(), "");
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
        tcp::resolver::iterator end;

        while (endpoint_iterator != end) {
            tcp::endpoint endpoint = *endpoint_iterator++;
            if (endpoint.address().is_v4()) {
                cout << "Please ensure port forwarding from external IP to local IP " << endpoint.address().to_string() << " is enabled." << endl;
                cout << "Please ensure your board WiFi and external IP are configured." << endl;
                cout << "Example: Board(s) configured to report to external IP 111.222.333.444\n    Local machine IP address is " << endpoint.address().to_string() << ", and for that local IP:\n    External IP start port: 8080, external IP end port: 277\n    Local IP start port: 277, local IP end port to land on this server:" << portVal << endl;
                break;
            }
        }
    }
    catch (exception& e) {
        cerr << "Exception: " << e.what() << endl;
    }

    // Set up the server to accept the sensor transmissions from
    try {
        io_context io_context;

        // Create an acceptor to listen for new connections
        tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), portVal));

        cout << "Server listening on 0.0.0.0 local end port " << portVal << "\n" << endl;

        while (true) {
            // Wait for a new connection
            tcp::socket socket(io_context);
            acceptor.accept(socket);

            cout << "Connection from: " << socket.remote_endpoint().address().to_string() << endl;

            // Receive data from the client
            asio::streambuf buffer;
            asio::read_until(socket, buffer, "\n");
            string data = buffer_cast<const char*>(buffer.data());

            // Setup the time report to add to the sensor data
            time_t now;
            time(&now);
            struct tm tm_info;
            localtime_s(&tm_info, &now);
            char timeBuffer[15];
            strftime(timeBuffer, sizeof(timeBuffer), "%d%m%Y%H%M%S", &tm_info);
            stringstream ss;
            ss << timeBuffer << "," << data;

            // pkg holds time,mac,sensorvalue
            string pkg = ss.str();
            cout << pkg << endl;

            // Send data to csv file (Per unique mac)
            parseAndWriteMAC(pkg);

            // TODO: Send data to the database
            //saveToDatabase(pkg);
        }
    }
    catch (std::exception& e) {
        cerr << "Exception: " << e.what() << endl;
    }

    return 0;
}