From 063a329a0b2d490e4c7d9a83f102d8602de170e5 Mon Sep 17 00:00:00 2001 From: Chris Marsh Date: Fri, 21 Jul 2017 13:54:52 -0700 Subject: [PATCH] Wait for READY event for connection. --- examples/send-presence/send-presence.c | 2 +- src/rpc_connection.cpp | 38 ++++++++++++++++++++------ src/rpc_connection.h | 3 +- 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/examples/send-presence/send-presence.c b/examples/send-presence/send-presence.c index bd2973b..b4d36c0 100644 --- a/examples/send-presence/send-presence.c +++ b/examples/send-presence/send-presence.c @@ -11,7 +11,7 @@ #include "discord-rpc.h" -static const char* APPLICATION_ID = "12345678910"; +static const char* APPLICATION_ID = "338030514596216832"; static int FrustrationLevel = 0; static void updateDiscordPresence() { diff --git a/src/rpc_connection.cpp b/src/rpc_connection.cpp index 12dfdc6..052402b 100644 --- a/src/rpc_connection.cpp +++ b/src/rpc_connection.cpp @@ -27,20 +27,40 @@ void RpcConnection::Open() if (state == State::Disconnected) { if (connection->Open()) { - state = State::Connecting; } else { return; } } - sendFrame.opcode = Opcode::Handshake; - sendFrame.length = JsonWriteHandshakeObj(sendFrame.message, sizeof(sendFrame.message), RpcVersion, appId); - - if (connection->Write(&sendFrame, sizeof(MessageFrameHeader) + sendFrame.length)) { - state = State::Connected; - if (onConnect) { - onConnect(); + if (state == State::SentHandshake) { + rapidjson::Document message; + if (Read(message)) { + auto cmd = message.FindMember("cmd"); + if (cmd == message.MemberEnd() || !cmd->value.IsString()) { + return; + } + 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) { - if (state != State::Connected) { + if (state != State::Connected && state != State::SentHandshake) { return false; } MessageFrame readFrame; diff --git a/src/rpc_connection.h b/src/rpc_connection.h index 4e1a8e6..c0e20dd 100644 --- a/src/rpc_connection.h +++ b/src/rpc_connection.h @@ -26,7 +26,8 @@ struct RpcConnection { enum class State : uint32_t { Disconnected, - Connecting, + SentHandshake, + AwaitingResponse, Connected, };