gateway_protocol.c 2.26 KB
Newer Older
1
#include <gateway_protocol.h>
2
#include "security_adapter.h"
3
4
5

#define GATEWAY_PROTOCOL_APP_KEY_SIZE       8

6
static gateway_protocol_checkup_callback_t checkup_callback;
7
8

void gateway_protocol_packet_encode (
9
    const gateway_protocol_conf_t *gwp_conf,
10
11
12
13
14
15
16
17
    const gateway_protocol_packet_type_t packet_type,
    const uint8_t payload_length,
    const uint8_t *payload,
    uint8_t *packet_length,
    uint8_t *packet)
{
    *packet_length = 0;

18
    memcpy(&packet[*packet_length], gwp_conf->app_key, GATEWAY_PROTOCOL_APP_KEY_SIZE);
19
20
    (*packet_length) += GATEWAY_PROTOCOL_APP_KEY_SIZE;

21
    packet[*packet_length] = gwp_conf->dev_id;
22
23
24
25
26
27
28
29
30
31
    (*packet_length)++;

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

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

    memcpy(&packet[*packet_length], payload, payload_length);
    (*packet_length) += payload_length;
32
33
34
35
36
37
38
39
40
41

    if (gwp_conf->secure) {
	    security_adapter_encrypt(	gwp_conf->secure_key, 
					&packet[GATWAY_PROTOCOL_APP_KEY_SIZE], 
					*packet_length,
					&packet[GATWAY_PROTOCOL_APP_KEY_SIZE], 
					*packet_length-GATEWAY_PROTOCOL_APP_KEY_SIZE
	    );
	    (*packet_length) += GATEWAY_PROTOCOL_APP_KEY_SIZE; 
    }
42
43
44
}

uint8_t gateway_protocol_packet_decode (
45
    gateway_protocol_conf_t *gwp_conf,
46
47
48
49
50
51
52
53
    gateway_protocol_packet_type_t *packet_type,
    uint8_t *payload_length,
    uint8_t *payload,
    const uint8_t packet_length,
    const uint8_t *packet)
{
    uint8_t p_len = 0;

54
    memcpy(gwp_conf->app_key, &packet[p_len], GATEWAY_PROTOCOL_APP_KEY_SIZE);
55
56
    p_len += GATEWAY_PROTOCOL_APP_KEY_SIZE;

57
58
59
60
61
62
63
64
65
66
67
68
    checkup_callback(gwp_conf);

    if (gwp_conf->secure) {
	    security_adapter_decrypt(	gwp_conf->secure_key, 
					&packet[GATWAY_PROTOCOL_APP_KEY_SIZE], 
					packet_length-GATEWAY_PROTOCOL_APP_KEY_SIZE
					&packet[GATWAY_PROTOCOL_APP_KEY_SIZE], 
					*packet_length
	    );
    }

    gwp_conf->dev_id = packet[p_len];
69
70
71
72
73
    p_len++;

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

74
    *payload_length = packet[p_len];
75
76
77
78
79
    p_len++;

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

80
81
82
83
84
    return p_len;
}

void gateway_protocol_set_checkup_callback(gateway_protocol_checkup_callback_t callback) {
    checkup_callback = callback;
85
}
86