Wait for READY event for connection.

This commit is contained in:
Chris Marsh 2017-07-21 13:54:52 -07:00
parent 559f56b05c
commit 063a329a0b
3 changed files with 32 additions and 11 deletions

View file

@ -11,7 +11,7 @@
#include "discord-rpc.h" #include "discord-rpc.h"
static const char* APPLICATION_ID = "12345678910"; static const char* APPLICATION_ID = "338030514596216832";
static int FrustrationLevel = 0; static int FrustrationLevel = 0;
static void updateDiscordPresence() { static void updateDiscordPresence() {

View file

@ -27,20 +27,40 @@ void RpcConnection::Open()
if (state == State::Disconnected) { if (state == State::Disconnected) {
if (connection->Open()) { if (connection->Open()) {
state = State::Connecting;
} }
else { else {
return; return;
} }
} }
sendFrame.opcode = Opcode::Handshake; if (state == State::SentHandshake) {
sendFrame.length = JsonWriteHandshakeObj(sendFrame.message, sizeof(sendFrame.message), RpcVersion, appId); rapidjson::Document message;
if (Read(message)) {
if (connection->Write(&sendFrame, sizeof(MessageFrameHeader) + sendFrame.length)) { auto cmd = message.FindMember("cmd");
state = State::Connected; if (cmd == message.MemberEnd() || !cmd->value.IsString()) {
if (onConnect) { return;
onConnect(); }
auto evt = message.FindMember("evt");
if (evt == message.MemberEnd() || !evt->value.IsString()) {
return;
}
if (!strcmp(cmd->value.GetString(), "DISPATCH") && !strcmp(evt->value.GetString(), "READY")) {
state = State::Connected;
if (onConnect) {
onConnect();
}
}
}
}
else {
sendFrame.opcode = Opcode::Handshake;
sendFrame.length = JsonWriteHandshakeObj(sendFrame.message, sizeof(sendFrame.message), RpcVersion, appId);
if (connection->Write(&sendFrame, sizeof(MessageFrameHeader) + sendFrame.length)) {
state = State::SentHandshake;
}
else {
Close();
} }
} }
} }
@ -68,7 +88,7 @@ bool RpcConnection::Write(const void* data, size_t length)
bool RpcConnection::Read(rapidjson::Document& message) bool RpcConnection::Read(rapidjson::Document& message)
{ {
if (state != State::Connected) { if (state != State::Connected && state != State::SentHandshake) {
return false; return false;
} }
MessageFrame readFrame; MessageFrame readFrame;

View file

@ -26,7 +26,8 @@ struct RpcConnection {
enum class State : uint32_t { enum class State : uint32_t {
Disconnected, Disconnected,
Connecting, SentHandshake,
AwaitingResponse,
Connected, Connected,
}; };