1 //
2 // Copyright (c) 2010-2024 Antmicro
3 //
4 // This file is licensed under the MIT License.
5 // Full license text is available in 'licenses/MIT.txt'.
6 //
7
8 #include "socket_channel.h"
9
SocketCommunicationChannel()10 SocketCommunicationChannel::SocketCommunicationChannel()
11 {
12 ASocket::SettingsFlag dontLog = ASocket::NO_FLAGS;
13 mainSocket.reset(new CTCPClient(NULL, dontLog));
14 senderSocket.reset(new CTCPClient(NULL, dontLog));
15 }
16
connect(int receiverPort,int senderPort,const char * address)17 void SocketCommunicationChannel::connect(int receiverPort, int senderPort, const char* address)
18 {
19 mainSocket->Connect(address, std::to_string(receiverPort));
20 senderSocket->Connect(address, std::to_string(senderPort));
21 handshakeValid();
22 }
23
disconnect()24 void SocketCommunicationChannel::disconnect()
25 {
26 connected = false;
27 }
28
isConnected()29 bool SocketCommunicationChannel::isConnected()
30 {
31 return connected;
32 }
33
handshakeValid()34 void SocketCommunicationChannel::handshakeValid()
35 {
36 Protocol* received = receive();
37 if(received->actionId == handshake) {
38 sendMain(Protocol(handshake, 0, 0, noPeripheralIndex));
39 connected = true;
40 }
41 }
42
log(int logLevel,const char * data)43 void SocketCommunicationChannel::log(int logLevel, const char* data)
44 {
45 sendSender(Protocol(logMessage, strlen(data), logLevel, noPeripheralIndex));
46 senderSocket->Send(data, strlen(data));
47 }
48
receive()49 Protocol* SocketCommunicationChannel::receive()
50 {
51 Protocol* message = new Protocol;
52 mainSocket->CTCPClient::Receive((char *)message, sizeof(Protocol));
53 return message;
54 }
55
sendMain(const Protocol message)56 void SocketCommunicationChannel::sendMain(const Protocol message)
57 {
58 try {
59 mainSocket->Send((char *)&message, sizeof(struct Protocol));
60 }
61 catch(const char* msg) {
62 connected = false;
63 throw msg;
64 }
65 }
66
sendSender(const Protocol message)67 void SocketCommunicationChannel::sendSender(const Protocol message)
68 {
69 try {
70 senderSocket->Send((char *)&message, sizeof(struct Protocol));
71 }
72 catch(const char* msg) {
73 connected = false;
74 throw msg;
75 }
76 }
77
78