gateway.c 17.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
#include <unistd.h>
#include <stdint.h>
#include <pthread.h>
#include <sys/time.h>
#include <libpq-fe.h>
#include <math.h>
#include <signal.h>
#include <time.h>

#include <errno.h>

#include "gateway_protocol.h"
#include "base64.h"
#include "task_queue.h"

#define NTHREADS_MAX			10
Vladislav Rykov's avatar
Vladislav Rykov committed
22

Vladislav Rykov's avatar
Vladislav Rykov committed
23
24
25
#define TIMEDATE_LENGTH			32
#define PEND_SEND_RETRIES_MAX		5
#define GATEWAY_PROTOCOL_APP_KEY_SIZE	8
Vladislav Rykov's avatar
Vladislav Rykov committed
26
#define DEVICE_DATA_MAX_LENGTH		256
Vladislav Rykov's avatar
Vladislav Rykov committed
27

Vladislav Rykov's avatar
Vladislav Rykov committed
28
29
typedef struct {
	uint32_t utc;
Vladislav Rykov's avatar
Vladislav Rykov committed
30
	char timedate[TIMEDATE_LENGTH];
Vladislav Rykov's avatar
Vladislav Rykov committed
31

Vladislav Rykov's avatar
Vladislav Rykov committed
32
33
	uint8_t data[DEVICE_DATA_MAX_LENGTH];
	uint8_t data_length;
Vladislav Rykov's avatar
Vladislav Rykov committed
34
35
} sensor_data_t;

Vladislav Rykov's avatar
Vladislav Rykov committed
36
typedef struct {
Vladislav Rykov's avatar
Vladislav Rykov committed
37
	uint8_t app_key[GATEWAY_PROTOCOL_APP_KEY_SIZE +1];
Vladislav Rykov's avatar
Vladislav Rykov committed
38
39
40
41
42
43
44
45
	uint8_t dev_id;
	int server_desc;
	int client_desc;
	struct sockaddr_in server;
	struct sockaddr_in client;
	int sock_len;
} gcom_ch_t; // gateway communication channel

46
47
48
49
50
51
52
typedef struct {
	gcom_ch_t gch;	
	gateway_protocol_packet_type_t packet_type;
	uint8_t packet[DEVICE_DATA_MAX_LENGTH];
	uint8_t packet_length;
} gcom_ch_request_t;

Vladislav Rykov's avatar
Vladislav Rykov committed
53
54
/* for multithreading impl */
void * connection_handler (void *args);
55
void process_packet(void *request);
Vladislav Rykov's avatar
Vladislav Rykov committed
56

Vladislav Rykov's avatar
Vladislav Rykov committed
57
58
59
int send_gcom_ch(gcom_ch_t *gch, uint8_t *pck, uint8_t pck_size);
int recv_gcom_ch(gcom_ch_t *gch, uint8_t *pck, uint8_t *pck_length, uint16_t pck_size);

Vladislav Rykov's avatar
Vladislav Rykov committed
60
void packet_encode(
Vladislav Rykov's avatar
Vladislav Rykov committed
61
62
63
64
65
	const uint8_t *app_key,
	const uint8_t dev_id, 
	const gateway_protocol_packet_type_t p_type, 
	const uint8_t payload_length,
	const uint8_t *payload,
Vladislav Rykov's avatar
Vladislav Rykov committed
66
67
68
	uint8_t *packet_length,
	uint8_t *packet);
uint8_t packet_decode(
Vladislav Rykov's avatar
Vladislav Rykov committed
69
	uint8_t *app_key,
Vladislav Rykov's avatar
Vladislav Rykov committed
70
71
72
73
	uint8_t *dev_id,
	gateway_protocol_packet_type_t *ptype,
	uint8_t *payload_length,
	uint8_t *payload,
Vladislav Rykov's avatar
Vladislav Rykov committed
74
75
	const uint8_t packet_length,
	const uint8_t *packet);
Vladislav Rykov's avatar
Vladislav Rykov committed
76
77
78
79
void gateway_protocol_data_send_payload_decode(
	sensor_data_t *sensor_data, 
	const uint8_t *payload, 
	const uint8_t payload_length);
Vladislav Rykov's avatar
Vladislav Rykov committed
80

Vladislav Rykov's avatar
Vladislav Rykov committed
81
82
83
84
85
86
87
88
void gateway_protocol_mk_stat(
	gcom_ch_t *gch,
	gateway_protocol_stat_t stat,
	uint8_t *pck,
	uint8_t *pck_len);

void send_utc(gcom_ch_t *pch);

Vladislav Rykov's avatar
Vladislav Rykov committed
89
90
void ctrc_handler (int sig);
static volatile uint8_t working = 1;
Vladislav Rykov's avatar
Vladislav Rykov committed
91

92
93
94
pthread_mutex_t mutex;
PGconn *conn;

Vladislav Rykov's avatar
Vladislav Rykov committed
95
int main (int argc, char **argv) {
96
97
98
	gcom_ch_request req;
	task_queue_t *tq;

Vladislav Rykov's avatar
Vladislav Rykov committed
99
100
	uint8_t buf[1024];
	uint8_t buf_len = 0;
Vladislav Rykov's avatar
Vladislav Rykov committed
101
	uint8_t payload[256];
Vladislav Rykov's avatar
Vladislav Rykov committed
102
	uint8_t payload_length = 0;
Vladislav Rykov's avatar
Vladislav Rykov committed
103
104
	PGresult *res;
	
Vladislav Rykov's avatar
Vladislav Rykov committed
105
106
	memset(&gch, 0x0, sizeof(gch));

Vladislav Rykov's avatar
Vladislav Rykov committed
107
	signal(SIGINT, ctrc_handler);
Vladislav Rykov's avatar
Vladislav Rykov committed
108

109
	conn = PQconnectdb("user=vlad dbname=iotserver password=dev");
Vladislav Rykov's avatar
Vladislav Rykov committed
110
	if (PQstatus(conn) == CONNECTION_BAD) {
Vladislav Rykov's avatar
Vladislav Rykov committed
111
		fprintf(stderr,"connection to db error: %s\n", PQerrorMessage(conn));
Vladislav Rykov's avatar
Vladislav Rykov committed
112
113
114
		return EXIT_FAILURE;
	}

Vladislav Rykov's avatar
Vladislav Rykov committed
115
	if ((gch.server_desc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
Vladislav Rykov's avatar
Vladislav Rykov committed
116
117
118
119
		perror("socket creation error");
		return EXIT_FAILURE;
	}

Vladislav Rykov's avatar
Vladislav Rykov committed
120
	gch.server.sin_family 		= AF_INET;
Vladislav Rykov's avatar
Vladislav Rykov committed
121
	gch.server.sin_port		= htons(54345);
Vladislav Rykov's avatar
Vladislav Rykov committed
122
	gch.server.sin_addr.s_addr 	= INADDR_ANY;
Vladislav Rykov's avatar
Vladislav Rykov committed
123

Vladislav Rykov's avatar
Vladislav Rykov committed
124
	if (bind(gch.server_desc, (struct sockaddr *) &gch.server, sizeof(gch.server)) < 0) {
Vladislav Rykov's avatar
Vladislav Rykov committed
125
126
127
128
		perror("binding error");
		return EXIT_FAILURE;
	}

129
	tq = task_queue_create(NTHREAD_MAX);
Vladislav Rykov's avatar
Vladislav Rykov committed
130
131
132
	gateway_protocol_packet_type_t packet_type;
	
	while (working) {
Vladislav Rykov's avatar
Vladislav Rykov committed
133
		buf_len = 0;
Vladislav Rykov's avatar
Vladislav Rykov committed
134
		printf("listenninig...\n");
Vladislav Rykov's avatar
Vladislav Rykov committed
135
136
		gch.sock_len = sizeof(gch.client);
		
Vladislav Rykov's avatar
Vladislav Rykov committed
137
138
139
140
141
142
143
144
		if (	recv_gcom_ch(&gch, buf, &buf_len, 1024) 
			&
			packet_decode(
				gch.app_key,
				&gch.dev_id,
				&packet_type,
				&payload_length, payload,
				buf_len, buf)			)
Vladislav Rykov's avatar
Vladislav Rykov committed
145
146
147
		{
			if (packet_type == GATEWAY_PROTOCOL_PACKET_TYPE_TIME_REQ) {
				printf("TIME REQ received\n");
Vladislav Rykov's avatar
Vladislav Rykov committed
148
				send_utc(&gch);
Vladislav Rykov's avatar
Vladislav Rykov committed
149
150
			} else if (packet_type == GATEWAY_PROTOCOL_PACKET_TYPE_DATA_SEND) {
				sensor_data_t sensor_data;
Vladislav Rykov's avatar
Vladislav Rykov committed
151
152
				time_t t;

Vladislav Rykov's avatar
Vladislav Rykov committed
153
				printf("DATA SEND received\n");
Vladislav Rykov's avatar
Vladislav Rykov committed
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
		        	gateway_protocol_data_send_payload_decode(&sensor_data, payload, payload_length);
				
				if (sensor_data.utc == 0) {
					struct timeval tv;
					gettimeofday(&tv, NULL);
					t = tv.tv_sec;
				} else {
					t = sensor_data.utc;
				}
				
				strftime(sensor_data.timedate, TIMEDATE_LENGTH, "%d/%m/%Y %H:%M:%S", localtime(&t));
				snprintf(buf, sizeof(buf), 
					"INSERT INTO dev_%s_%d VALUES (%d, '%s', $1)", (char *)gch.app_key, gch.dev_id, t, sensor_data.timedate);
				
				const char *params[1];
				int paramlen[1];
				int paramfor[1];
				params[0] = sensor_data.data;
				paramlen[0] = sensor_data.data_length;
				paramfor[0] = 1; // binary

				res = PQexecParams(conn, buf, 1, NULL, params, paramlen, paramfor, 0);
				if (PQresultStatus(res) == PGRES_COMMAND_OK) {
					PQclear(res);

					sprintf(buf, "SELECT * FROM pend_msgs WHERE app_key='%s' and dev_id = %d and ack = False", (char *)gch.app_key, gch.dev_id);
Vladislav Rykov's avatar
Vladislav Rykov committed
180
					res = PQexec(conn, buf);
Vladislav Rykov's avatar
Vladislav Rykov committed
181
182
183
184
185
186
					if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res)) {
						gateway_protocol_mk_stat(
							&gch, 
							GATEWAY_PROTOCOL_STAT_ACK_PEND,
							buf, &buf_len);
						printf("ACK_PEND prepared\n");
Vladislav Rykov's avatar
Vladislav Rykov committed
187
					} else {
Vladislav Rykov's avatar
Vladislav Rykov committed
188
189
190
191
192
						gateway_protocol_mk_stat(
							&gch, 
							GATEWAY_PROTOCOL_STAT_ACK,
							buf, &buf_len);
						printf("ACK prepared\n");
Vladislav Rykov's avatar
Vladislav Rykov committed
193
					}
Vladislav Rykov's avatar
Vladislav Rykov committed
194
195
					
					send_gcom_ch(&gch, buf, buf_len);
Vladislav Rykov's avatar
Vladislav Rykov committed
196
197
				} else {
					fprintf(stderr, "database error : %s\n", PQerrorMessage(conn));
Vladislav Rykov's avatar
Vladislav Rykov committed
198
				}
Vladislav Rykov's avatar
Vladislav Rykov committed
199
				PQclear(res);
Vladislav Rykov's avatar
Vladislav Rykov committed
200
			} else if (packet_type == GATEWAY_PROTOCOL_PACKET_TYPE_PEND_REQ) {
Vladislav Rykov's avatar
Vladislav Rykov committed
201
				sprintf(buf, "SELECT * FROM pend_msgs WHERE app_key = '%s' AND dev_id = %d AND ack = False", 
Vladislav Rykov's avatar
Vladislav Rykov committed
202
						(char *)gch.app_key, gch.dev_id);
Vladislav Rykov's avatar
Vladislav Rykov committed
203
204
205
				res = PQexec(conn, buf);
				if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res)) {
					char msg_cont[150];
Vladislav Rykov's avatar
Vladislav Rykov committed
206
207
					strncpy(msg_cont, PQgetvalue(res, 0, 2), sizeof(msg_cont));
					printf("PEND_SEND prepared : %s\n", msg_cont);
Vladislav Rykov's avatar
Vladislav Rykov committed
208
					PQclear(res);
Vladislav Rykov's avatar
Vladislav Rykov committed
209
210
211
212
				
					base64_decode(msg_cont, strlen(msg_cont)-1, payload);
					payload_length = BASE64_DECODE_OUT_SIZE(strlen(msg_cont));
					printf("prepared to send %d bytes : %s\n", payload_length, payload);
Vladislav Rykov's avatar
Vladislav Rykov committed
213
					
Vladislav Rykov's avatar
Vladislav Rykov committed
214
215
216
					// send the msg until ack is received
					uint8_t received_ack = 0;
					uint8_t pend_send_retries = PEND_SEND_RETRIES_MAX;
Vladislav Rykov's avatar
Vladislav Rykov committed
217
218
219
					struct timeval tv;
					tv.tv_sec = 0;
					tv.tv_usec = 300000; // 300ms ack recv timeout
Vladislav Rykov's avatar
Vladislav Rykov committed
220
221
					do {
						packet_encode(
Vladislav Rykov's avatar
Vladislav Rykov committed
222
							gch.app_key,
Vladislav Rykov's avatar
Vladislav Rykov committed
223
224
225
226
							gch.dev_id, 
							GATEWAY_PROTOCOL_PACKET_TYPE_PEND_SEND,
							payload_length, payload,
							&buf_len, buf);
Vladislav Rykov's avatar
Vladislav Rykov committed
227

Vladislav Rykov's avatar
Vladislav Rykov committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
						send_gcom_ch(&gch, buf, buf_len);	
						// set timeout
						if (setsockopt(gch.server_desc, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
							perror("setsockopt error");
						}
						recv_gcom_ch(&gch, buf, &buf_len, 1024);
						if (buf_len > 9) { /* min packet size. timeout -> -1 */
							uint8_t recv_app_key[GATEWAY_PROTOCOL_APP_KEY_SIZE +1];
							uint8_t recv_dev_id = 0xFF;
							if (packet_decode(
								recv_app_key,
								&recv_dev_id, 
								&packet_type,
								&buf_len, buf,
								buf_len, buf)) 
Vladislav Rykov's avatar
Vladislav Rykov committed
243
							{
Vladislav Rykov's avatar
Vladislav Rykov committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
								if (!memcmp(recv_app_key, gch.app_key, GATEWAY_PROTOCOL_APP_KEY_SIZE) &&
									recv_dev_id == gch.dev_id &&
									packet_type == GATEWAY_PROTOCOL_PACKET_TYPE_STAT &&
									buf_len == 1 &&
									buf[0] == GATEWAY_PROTOCOL_STAT_ACK)
								{
									sprintf(buf, "UPDATE pend_msgs SET ack = True WHERE app_key = '%s' AND dev_id = %d AND msg = '%s'", (char *)gch.app_key, gch.dev_id, msg_cont);
									res = PQexec(conn, buf);
									if (PQresultStatus(res) != PGRES_COMMAND_OK) {
										fprintf(stderr, "error db deleting : %s", PQerrorMessage(conn));
									}
									PQclear(res);
									received_ack = 1;
									printf("ACK received\n");
								} else {
									printf("error: packet_type = %02X, not STAT\n");
Vladislav Rykov's avatar
Vladislav Rykov committed
260
								}
Vladislav Rykov's avatar
Vladislav Rykov committed
261
262
							}
						}
Vladislav Rykov's avatar
Vladislav Rykov committed
263
					} while (!received_ack && pend_send_retries--);
Vladislav Rykov's avatar
Vladislav Rykov committed
264
265
266
267
268
					// cancel timeout
					tv.tv_usec = 0;	
					if (setsockopt(gch.server_desc, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
						perror("setsockopt error");
					}
Vladislav Rykov's avatar
Vladislav Rykov committed
269
				} else {
Vladislav Rykov's avatar
Vladislav Rykov committed
270
271
272
273
274
275
276
					gateway_protocol_mk_stat(
						&gch,
						GATEWAY_PROTOCOL_STAT_NACK,
						buf, &buf_len);
					
					send_gcom_ch(&gch, buf, buf_len);
					
Vladislav Rykov's avatar
Vladislav Rykov committed
277
					printf("nothing for app %s dev %d\n", (char *)gch.app_key, gch.dev_id);
Vladislav Rykov's avatar
Vladislav Rykov committed
278
				}
Vladislav Rykov's avatar
Vladislav Rykov committed
279
			} else {
Vladislav Rykov's avatar
Vladislav Rykov committed
280
281
282
283
284
285
286
				gateway_protocol_mk_stat(
					&gch,
					GATEWAY_PROTOCOL_STAT_NACK,
					buf, &buf_len);
				
				send_gcom_ch(&gch, buf, buf_len);
				
Vladislav Rykov's avatar
Vladislav Rykov committed
287
				fprintf(stderr, "packet type error : %02X\n", packet_type);
Vladislav Rykov's avatar
Vladislav Rykov committed
288
289
			}
		} else {
Vladislav Rykov's avatar
Vladislav Rykov committed
290
291
			
			fprintf(stderr, "payload decode error\n");
Vladislav Rykov's avatar
Vladislav Rykov committed
292
		}
Vladislav Rykov's avatar
Vladislav Rykov committed
293

Vladislav Rykov's avatar
Vladislav Rykov committed
294
295
	}

Vladislav Rykov's avatar
Vladislav Rykov committed
296
	close(gch.server_desc);
Vladislav Rykov's avatar
Vladislav Rykov committed
297
	PQfinish(conn);
Vladislav Rykov's avatar
Vladislav Rykov committed
298

Vladislav Rykov's avatar
Vladislav Rykov committed
299
300
301
	return EXIT_SUCCESS;
}

Vladislav Rykov's avatar
Vladislav Rykov committed
302
303
304
305
void ctrc_handler (int sig) {
	working = 0;
}

306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
void process_packet(void *request) {
	gcom_ch_request_t *req = (gcom_ch_request_t *)request;
	uint8_t payload[DEVICE_DATA_MAX_LENGTH];
	uint8_t payload_length;	
	PGresult *res;

	if (packet_decode(
		req->gch.app_key,
		&(req->gch.dev_id),
		&(req->packet_type),
		&payload_length, payload,
		req->packet_length, req->packet))
	{
		if (req->packet_type == GATEWAY_PROTOCOL_PACKET_TYPE_TIME_REQ) {
			printf("TIME REQ received\n");
			send_utc(&(req->gch));
		} else if (req->packet_type == GATEWAY_PROTOCOL_PACKET_TYPE_DATA_SEND) {
			sensor_data_t sensor_data;
			time_t t;
			// DEVICE_DATA_MAX_LENGTH*2 {hex} + 150
			char db_query[662];

			printf("DATA SEND received\n");
			gateway_protocol_data_send_payload_decode(&sensor_data, payload, payload_length);
			
			if (sensor_data.utc == 0) {
				struct timeval tv;
				gettimeofday(&tv, NULL);
				t = tv.tv_sec;
			} else {
				t = sensor_data.utc;
			}
			
			strftime(sensor_data.timedate, TIMEDATE_LENGTH, "%d/%m/%Y %H:%M:%S", localtime(&t));
			snprintf(db_query, sizeof(db_query), 
				"INSERT INTO dev_%s_%d VALUES (%d, '%s', $1)", 
				(char *)req->gch.app_key, req->gch.dev_id, t, sensor_data.timedate
			);
			
			const char *params[1];
			int paramslen[1];
			int paramsfor[1];
			params[0] = sensor_data.data;
			paramslen[0] = sensor_data.data_length;
			paramsfor[0] = 1; // format - binary

			res = PQexecParams(conn, db_query, 1, NULL, params, paramslen, paramsfor, 0);
			if (PQresultStatus(res) == PGRES_COMMAND_OK) {
				PQclear(res);

				snprintf(db_query, sizeof(db_query),
					 "SELECT * FROM pend_msgs WHERE app_key='%s' and dev_id = %d and ack = False", 
					(char *)req->gch.app_key, req->gch.dev_id
				);
				res = PQexec(conn, db_query);
				if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res)) {
					gateway_protocol_mk_stat(
						&(req->gch), 
						GATEWAY_PROTOCOL_STAT_ACK_PEND,
						req->packet, &(req->packet_length));
					printf("ACK_PEND prepared\n");
				} else {
					gateway_protocol_mk_stat(
						&(req->gch), 
						GATEWAY_PROTOCOL_STAT_ACK,
						req->packet, &(req->packet_length));
					printf("ACK prepared\n");
				}
				
				send_gcom_ch(&(req->gch), req->packet, req->packet_length);
			} else {
				fprintf(stderr, "database error : %s\n", PQerrorMessage(conn));
			}
			PQclear(res);
		} else if (req->packet_type == GATEWAY_PROTOCOL_PACKET_TYPE_PEND_REQ) {
			char db_query[200];
			snprintf(db_query, sizeof(db_query),
				 "SELECT * FROM pend_msgs WHERE app_key = '%s' AND dev_id = %d AND ack = False", 
				(char *)req->gch.app_key, req->gch.dev_id
			);
			res = PQexec(conn, db_query);
			
			if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res)) {
				char msg_cont[150];
				strncpy(msg_cont, PQgetvalue(res, 0, 2), sizeof(msg_cont));
				printf("PEND_SEND prepared : %s\n", msg_cont);
				PQclear(res);
			
				base64_decode(msg_cont, strlen(msg_cont)-1, payload);
				payload_length = BASE64_DECODE_OUT_SIZE(strlen(msg_cont));
				printf("prepared to send %d bytes : %s\n", payload_length, payload);
				
				// send the msg until ack is received
				uint8_t received_ack = 0;
				uint8_t pend_send_retries = PEND_SEND_RETRIES_MAX;
				struct timeval tv;
				tv.tv_sec = 0;
				tv.tv_usec = 300000; // 300ms ack recv timeout
				do {
					packet_encode(
						req->gch.app_key,
						req->gch.dev_id, 
						GATEWAY_PROTOCOL_PACKET_TYPE_PEND_SEND,
						payload_length, payload,
						&(req->packet_length), req->packet);

					send_gcom_ch(&(req->gch), req->packet, req->packet_length);
					// set timeout
					if (setsockopt(req->gch.server_desc, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
						perror("setsockopt error");
					}
					if (recv_gcom_ch(&(req->gch), 
						req->packet, 
						&(req->packet_length),
						DEVICE_DATA_MAX_LENGTH) > 9)
					{ /* min packet size. timeout -> -1 */
						uint8_t recv_app_key[GATEWAY_PROTOCOL_APP_KEY_SIZE +1];
						uint8_t recv_dev_id = 0xFF;
						if (packet_decode(
							recv_app_key,
							&recv_dev_id, 
							&(req->packet_type),
							&(req->packet_length), req->packet,
							req->packet_length, req->packet)) 
						{
							if (!memcmp(recv_app_key, gch.app_key, GATEWAY_PROTOCOL_APP_KEY_SIZE) &&
								recv_dev_id == gch.dev_id &&
								packet_type == GATEWAY_PROTOCOL_PACKET_TYPE_STAT &&
								buf_len == 1 &&
								buf[0] == GATEWAY_PROTOCOL_STAT_ACK)
							{
								snprintf(db_query, sizeof(db_query),
								 	"UPDATE pend_msgs SET ack = True WHERE app_key = '%s' AND dev_id = %d AND msg = '%s'", 
									(char *)gch.app_key, gch.dev_id, msg_cont
								);
								res = PQexec(conn, buf);
								if (PQresultStatus(res) != PGRES_COMMAND_OK) {
									fprintf(stderr, "error db deleting : %s", PQerrorMessage(conn));
								}
								PQclear(res);
								received_ack = 1;
								printf("ACK received\n");
							} else {
								printf("error: packet_type = %02X, not STAT\n");
							}
						}
					}
				} while (!received_ack && pend_send_retries--);
				// cancel timeout
				tv.tv_usec = 0;	
				if (setsockopt(req->gch.server_desc, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
					perror("setsockopt error");
				}
			} else {
				gateway_protocol_mk_stat(
					&(req->gch),
					GATEWAY_PROTOCOL_STAT_NACK,
					req->packet, &(req->packet_length));
				
				send_gcom_ch(&(req->gch), req->packet, req->packet_length);
				
				printf("nothing for app %s dev %d\n", (char *)req->gch.app_key, req->gch.dev_id);
			}
		} else {
			gateway_protocol_mk_stat(
				&(req->gch),
				GATEWAY_PROTOCOL_STAT_NACK,
				req->packet, &(req->packet_length));
			
			send_gcom_ch(&(req->gch), req->packet, req->packet_length);
				
			fprintf(stderr, "packet type error : %02X\n", packet_type);
		}
	} else {
		fprintf(stderr, "payload decode error\n");
	}
}

Vladislav Rykov's avatar
Vladislav Rykov committed
484
void gateway_protocol_data_send_payload_decode(
Vladislav Rykov's avatar
Vladislav Rykov committed
485
486
487
488
	sensor_data_t *sensor_data, 
	const uint8_t *payload, 
	const uint8_t payload_length) 
{
Vladislav Rykov's avatar
Vladislav Rykov committed
489
490
491
492
493
	uint8_t p_len = 0;

	memcpy(&sensor_data->utc, &payload[p_len], sizeof(sensor_data->utc));
	p_len += sizeof(sensor_data->utc);

Vladislav Rykov's avatar
Vladislav Rykov committed
494
495
	memcpy(sensor_data->data, &payload[p_len], payload_length - p_len);
	sensor_data->data_length = payload_length - p_len;
Vladislav Rykov's avatar
Vladislav Rykov committed
496
497
}

Vladislav Rykov's avatar
Vladislav Rykov committed
498
void packet_encode(
Vladislav Rykov's avatar
Vladislav Rykov committed
499
500
501
502
503
	const uint8_t *app_key,
	const uint8_t dev_id, 
	const gateway_protocol_packet_type_t p_type, 
	const uint8_t payload_length,
	const uint8_t *payload,
Vladislav Rykov's avatar
Vladislav Rykov committed
504
505
506
507
	uint8_t *packet_length,
	uint8_t *packet) 
{
	*packet_length = 0;
Vladislav Rykov's avatar
Vladislav Rykov committed
508
509
510
	
	memcpy(&packet[*packet_length], app_key, GATEWAY_PROTOCOL_APP_KEY_SIZE);
	*packet_length += GATEWAY_PROTOCOL_APP_KEY_SIZE;
Vladislav Rykov's avatar
Vladislav Rykov committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525

	packet[*packet_length] = dev_id;
	(*packet_length)++;

	packet[*packet_length] = p_type;
	(*packet_length)++;

	packet[*packet_length] = payload_length;
	(*packet_length)++;

	memcpy(&packet[*packet_length], payload, payload_length);
	*packet_length += payload_length;
}

uint8_t packet_decode(
Vladislav Rykov's avatar
Vladislav Rykov committed
526
	uint8_t *app_key,
Vladislav Rykov's avatar
Vladislav Rykov committed
527
528
529
530
	uint8_t *dev_id,
	gateway_protocol_packet_type_t *ptype,
	uint8_t *payload_length,
	uint8_t *payload,
Vladislav Rykov's avatar
Vladislav Rykov committed
531
532
	const uint8_t packet_length,
	const uint8_t *packet)
Vladislav Rykov's avatar
Vladislav Rykov committed
533
534
{
	uint8_t p_len = 0;
Vladislav Rykov's avatar
Vladislav Rykov committed
535
536
537
	
	memcpy(app_key, &packet[p_len], GATEWAY_PROTOCOL_APP_KEY_SIZE);
	p_len += GATEWAY_PROTOCOL_APP_KEY_SIZE;
Vladislav Rykov's avatar
Vladislav Rykov committed
538
539
	
	app_key[GATEWAY_PROTOCOL_APP_KEY_SIZE] = '\0';
Vladislav Rykov's avatar
Vladislav Rykov committed
540
541
542
543
544
545
546
547
548
549
550
551
552

	*dev_id = packet[p_len];
	p_len++;

	*ptype = (gateway_protocol_packet_type_t) packet[p_len];
	p_len++;

	*payload_length = packet[p_len];
	p_len++;

	memcpy(payload, &packet[p_len], *payload_length);
	p_len += *payload_length;

Vladislav Rykov's avatar
Vladislav Rykov committed
553
554
	printf("payload_length = %d , calc = %d, recv = %d\n", *payload_length, p_len, packet_length);

Vladislav Rykov's avatar
Vladislav Rykov committed
555
556
557
	return p_len == packet_length;
}

Vladislav Rykov's avatar
Vladislav Rykov committed
558
559
560
561
562
563
void gateway_protocol_mk_stat(
	gcom_ch_t *gch,
	gateway_protocol_stat_t stat,
	uint8_t *pck,
	uint8_t *pck_len)
{
Vladislav Rykov's avatar
Vladislav Rykov committed
564
565
566
567
	packet_encode(
		gch->app_key,
		gch->dev_id,
		GATEWAY_PROTOCOL_PACKET_TYPE_STAT,
Vladislav Rykov's avatar
Vladislav Rykov committed
568
		1, (uint8_t *)&stat,
Vladislav Rykov's avatar
Vladislav Rykov committed
569
		pck_len, pck);
Vladislav Rykov's avatar
Vladislav Rykov committed
570
571
}

Vladislav Rykov's avatar
Vladislav Rykov committed
572
573


Vladislav Rykov's avatar
Vladislav Rykov committed
574
void send_utc(gcom_ch_t *gch) {
Vladislav Rykov's avatar
Vladislav Rykov committed
575
	uint8_t buf[50];
Vladislav Rykov's avatar
Vladislav Rykov committed
576
577
578
579
580
581
	uint8_t buf_len = 0;
	struct timeval tv;
				
	gettimeofday(&tv, NULL);
				
	packet_encode (
Vladislav Rykov's avatar
Vladislav Rykov committed
582
		gch->app_key,
Vladislav Rykov's avatar
Vladislav Rykov committed
583
584
		gch->dev_id,
		GATEWAY_PROTOCOL_PACKET_TYPE_TIME_SEND,
Vladislav Rykov's avatar
Vladislav Rykov committed
585
		sizeof(uint32_t), (uint8_t *)&tv.tv_sec,
Vladislav Rykov's avatar
Vladislav Rykov committed
586
587
588
589
590
591
592
		&buf_len, buf
	);
					
	send_gcom_ch(gch, buf, buf_len);
}

int send_gcom_ch(gcom_ch_t *gch, uint8_t *pck, uint8_t pck_size) {
593
	int ret;
Vladislav Rykov's avatar
Vladislav Rykov committed
594
	
595
	if ((ret = sendto(gch->server_desc, (char *)pck, pck_size, 0, (struct sockaddr *)&gch->client, gch->sock_len)) < 0) {
Vladislav Rykov's avatar
Vladislav Rykov committed
596
597
598
599
600
601
		perror("sendto error");
	}
	return ret;
}

int recv_gcom_ch(gcom_ch_t *gch, uint8_t *pck, uint8_t *pck_length, uint16_t pck_size) {
602
603
	int ret;
	if ((ret = recvfrom(gch->server_desc, (char *)pck, pck_size, MSG_WAITALL, (struct sockaddr *)&gch->client, &gch->sock_len)) < 0) {
Vladislav Rykov's avatar
Vladislav Rykov committed
604
		perror("socket receive error");
605
606
	} else {
		*pck_length = ret;
Vladislav Rykov's avatar
Vladislav Rykov committed
607
	}
608
	return ret;
Vladislav Rykov's avatar
Vladislav Rykov committed
609
}
Vladislav Rykov's avatar
Vladislav Rykov committed
610
611
/* connection handler for multithreading version */
#ifdef MULTITHREADING_VER
Vladislav Rykov's avatar
Vladislav Rykov committed
612
613
614
615
616
617
618
619
620
621
622
623
void *connection_handler(void *args) {
	int client_desc = *(int *)args;
	
	uint8_t buf[128] = "";
	uint8_t buf_len = 0;
	uint8_t payload[128];
	uint8_t payload_length = 0;

	if ((buf_len = recv(client_desc, buf, sizeof(buf), 0)) > 0) {
		uint8_t dev_id = 0xFF;
		gateway_protocol_packet_type_t packet_type;
		
Vladislav Rykov's avatar
Vladislav Rykov committed
624
		if (gateway_protocol_packet_decode(	
Vladislav Rykov's avatar
Vladislav Rykov committed
625
626
627
628
629
630
					&dev_id,
					&packet_type,
					&payload_length, payload,
					buf_len, buf))
		{
			if (packet_type == GATEWAY_PROTOCOL_PACKET_TYPE_TIME_REQ) {
Vladislav Rykov's avatar
Vladislav Rykov committed
631
				printf("TIME REQ received\n");
Vladislav Rykov's avatar
Vladislav Rykov committed
632
633
634
635
636
637
638
639
640
641
642
643
644
645
				struct timeval tv;
				buf_len = 0;
				
				buf[0] = dev_id;
				buf_len++;

				buf[1] = GATEWAY_PROTOCOL_PACKET_TYPE_TIME_SEND;
				buf_len++;

				gettimeofday(&tv, NULL);
				memcpy(&buf[buf_len], &tv.tv_sec, sizeof(uint32_t));
				buf_len += sizeof(uint32_t);

				write(client_desc, buf, buf_len);
Vladislav Rykov's avatar
Vladislav Rykov committed
646
647
			} else {
				perror("packet type error");
Vladislav Rykov's avatar
Vladislav Rykov committed
648
			}
Vladislav Rykov's avatar
Vladislav Rykov committed
649
650
		} else {
			perror("packet decode error");
Vladislav Rykov's avatar
Vladislav Rykov committed
651
652
653
654
		}
	}

}
Vladislav Rykov's avatar
Vladislav Rykov committed
655
#endif