-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSimulator.cpp
More file actions
103 lines (86 loc) · 2.1 KB
/
Simulator.cpp
File metadata and controls
103 lines (86 loc) · 2.1 KB
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
//
// Simulator.cpp
// HWConsoleServer
//
// Created by James Lennon on 10/10/14.
// Copyright (c) 2014 James Lennon. All rights reserved.
//
#include "Simulator.h"
#include "openpad.h"
#include "rapidjson.h"
#include "document.h"
#include "writer.h"
#include <unistd.h>
#include <thread>
#include <iostream>
using namespace openpad;
TCPSocket *sock;
char buf[1024];
mutex mut;
IDObject id1, id2;
void sendBadRequest(){
Request r;
sendMsg(sock, r);
}
void sendDiscovReq(IDObject& id){
Request r(0);
Document d;
Value& obj = r.serializeJSON(d.GetAllocator());
Value& idval = id.serializeJSON(d.GetAllocator());
obj.AddMember("id", idval, d.GetAllocator());
obj.AddMember("APIVersion", 1, d.GetAllocator());
sendMsg(sock, r);
}
void sendJoinReq(){
Request r(2);
sendMsg(sock, r);
}
void sendDisconnectReq(){
Request r(3);
sendMsg(sock, r);
}
void handle(const char* msg, int len){
mut.lock();
// if(OP_DEBUG)cout << "simulator got: " << msg << endl;
mut.unlock();
}
void getResponses(){
string msg;
while (true) {
int amt = sock->recv(buf, BUFFER_LENGTH-1);
buf[amt] = 0;
int bytesProcessed = 0;
do {
int len = (int)strlen(buf+bytesProcessed);
msg.append(buf+bytesProcessed, len);
if(bytesProcessed+len<amt){
handle(msg.c_str(), msg.length());
msg = "";
}
bytesProcessed+=len+1;
} while (bytesProcessed<amt);
}
}
void simulate(){
sleep(3);
unsigned short currentPort = START_PORT;
while (true) {
try {
sock = new TCPSocket("0.0.0.0", currentPort);
break;
} catch (SocketException ex) {
currentPort++;
}
}
// if(OP_DEBUG)printf("Simulator connected on port %d\n", currentPort);
thread t(getResponses);
t.detach();
id1.firstname = "James";
id1.lastname = "Lennon";
id1.username = "j_lennon";
id1.phoneid = "a";
sendDiscovReq(id1);
// sendJoinReq();
// sendDisconnectReq();
sleep(2);
}