forked from OUXT-Polaris/firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
135 lines (124 loc) · 3.9 KB
/
main.cpp
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
/**
* @file main.cpp
* @author T.nishimura ([email protected])
* @brief
* data protocol
* |header1|header2|length|data...|end|
*
* @version 0.1
* @date 2022-06-04
*
* @copyright Copyright (c) 2022
*
*/
#include "mbed.h"
#include "EthernetInterface.h"
#include <vector>
#include "../config.hpp"
enum class receiveStatus
{
header1 = 0,
header2 = 1,
length = 2,
data = 3,
};
int main(void)
{
const uint8_t header1 = 0xFF;
const uint8_t header2 = 0xFE;
const uint8_t end = 0xFD;
EthernetInterface net;
TCPSocket sock;
TCPSocket *client;
PwmOut led(A0);
uint8_t rxBuf[32] = {0};
std::vector<uint8_t> data;
receiveStatus status = receiveStatus::header1;
uint8_t length = 0;
uint8_t count = 0;
net.set_network(myIp, netmask, gateway);
if (net.connect() != 0)
{
printf("connection failed\r\n");
}
else
{
printf("connection success\r\n");
}
sock.open(&net);
sock.bind(myPort);
sock.listen(1);
while (1)
{
nsapi_error_t error = 0;
client = sock.accept(&error);
if (error == NSAPI_ERROR_OK)
{
while (client->recv(rxBuf, sizeof(rxBuf)) > 0)
{
for (unsigned int i = 0; i < sizeof(rxBuf); i++)
{
switch (status)
{
case receiveStatus::header1:
if (rxBuf[i] == header1)
{
status = receiveStatus::header2;
data.emplace_back(rxBuf[i]);
count++;
}
break;
case receiveStatus::header2:
// header1読み込み後
// header2が読み込まれたらdata受け取り開始
if (rxBuf[i] == header2)
{
status = receiveStatus::length;
data.clear();
count = 0;
}
else
// header2以外が読み込まれたらdata受け取り続行
{
data.emplace_back(rxBuf[i]);
count++;
status = receiveStatus::data;
}
break;
case receiveStatus::length:
// 長さを保存
length = rxBuf[i];
status = receiveStatus::data;
break;
case receiveStatus::data:
// length == countになるまでdataを保存
if (count < length)
{
data.emplace_back(rxBuf[i]);
count++;
}
else
{
status = receiveStatus::header1;
// 終了文字と一致する時
if (rxBuf[i] == end)
{
// byte列 → double
const double period = *reinterpret_cast<double *>(&data[0]);
const double value = *reinterpret_cast<double *>(&data[sizeof(double)]);
printf("period : %lf value : %lf\r\n", period, value);
led.period(static_cast<float>(period));
led.write(static_cast<float>(value));
}
}
break;
}
}
}
client->close();
}
}
sock.close();
net.disconnect();
return 0;
}