/* * MIT License * * Copyright (c) 2019 Alexey Edelev * * This file is part of qtprotobuf project https://git.semlanik.org/semlanik/qtprotobuf * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #pragma once #include #include #include #include #include #include #include "abstractchannel.h" #include "asyncreply.h" namespace qtprotobuf { class AbstractChannel; class AbstractClientPrivate; class AbstractClient : public QObject { public: void attachChannel(std::shared_ptr channel); AbstractChannel::StatusCodes lastError() const; QString lastErrorString() const; protected: AbstractClient(const QString &service, QObject *parent = nullptr); virtual ~AbstractClient(); template bool call(const QString &method, const A &arg, R &ret) { QByteArray retData; if (call(method, arg.serialize(), retData)) { try { ret.deserialize(retData); } catch (std::invalid_argument &) { qProtoCritical() << "Response deserialization failed invalid field found"; return false; } catch (std::out_of_range &) { qProtoCritical() << "Invalid size of received buffer"; return false; } catch (...) { throw; } return true; } return false; } template AsyncReply *call(const QString &method, const A &arg) { return call(method, arg.serialize()); } template::value, int> = 0> void subscribe(const QString &method, const A &arg, void(C::*signal)(const R &)) { subscribe_p(method, arg.serialize(), [this, signal](const QByteArray &data) { R ret; ret.deserialize(data); C* client = static_cast(this); (client->*signal)(ret); }); } template void subscribe(const QString &method, const A &arg, R &ret) { subscribe_p(method, arg.serialize(), [&ret](const QByteArray &data) { ret.deserialize(data); }); } private: bool call(const QString &method, const QByteArray& arg, QByteArray& ret); AsyncReply *call(const QString &method, const QByteArray& arg); void subscribe_p(const QString &method, const QByteArray& arg, const std::function &handler); Q_DISABLE_COPY(AbstractClient) AbstractClientPrivate *d; }; }