Change libwebsockets APIs
[profile/ivi/automotive-message-broker.git] / plugins / websocket / common.cpp
1 #include "common.h"
2 #include "debugout.h"
3 #include <math.h>
4 #include <glib.h>
5
6 #include <QVariantMap>
7
8 bool doBinary = false;
9
10 int lwsWrite(lws *lws, QByteArray d)
11 {
12         if(!lws)
13         {
14                 DebugOut(DebugOut::Error)<<__FUNCTION__<<": libwebsockets is not valid.  Perhaps it has not been initialized?" << endl;
15                 return -1;
16         }
17
18         DebugOut() << "Writing to websocket: " << d.constData() << endl;
19
20         int retval = -1;
21
22         QByteArray temp = d;
23
24         int numframes = 1;
25         int framesize = 5012;
26
27         if(d.length() > framesize)
28         {
29                 numframes = ceil((double)d.length() / double(framesize));
30                 QVariantMap multiFrameMessage;
31                 multiFrameMessage["type"] = "multiframe";
32                 multiFrameMessage["frames"] = numframes;
33
34                 lwsWriteVariant(lws, multiFrameMessage);
35         }
36
37         while(numframes--)
38         {
39                 int range = 0;
40                 if(temp.length() > framesize)
41                         range = framesize;
42                 else range = temp.length();
43
44                 QByteArray toWrite = temp.mid(0,range);
45                 const char* strToWrite = toWrite.data();
46
47                 temp = temp.mid(range);
48
49                 if(doBinary)
50                 {
51                         retval = lws_write(lws, (unsigned char*)strToWrite, toWrite.length(), LWS_WRITE_BINARY);
52                 }
53                 else
54                 {
55                         std::unique_ptr<char[]> buffer(new char[LWS_SEND_BUFFER_PRE_PADDING + toWrite.length() + LWS_SEND_BUFFER_POST_PADDING]);
56                         char *buf = buffer.get() + LWS_SEND_BUFFER_PRE_PADDING;
57                         memcpy(buf, strToWrite, toWrite.length());
58
59                         retval = lws_write(lws, (unsigned char*)strToWrite, toWrite.length(), LWS_WRITE_TEXT);
60                 }
61         }
62         return retval;
63 }
64
65 int lwsWriteVariant(lws *lws, QVariant d)
66 {
67         QByteArray replystr;
68         if(doBinary)
69                 replystr = QJsonDocument::fromVariant(d).toBinaryData();
70         else
71         {
72                 replystr = QJsonDocument::fromVariant(d).toJson();
73                 cleanJson(replystr);
74         }
75
76         lwsWrite(lws, replystr);
77 }
78
79 void cleanJson(QByteArray &json)
80 {
81         json.replace(" ", "");
82         json.replace("\n", "");
83         json.replace("\t", "");
84 }
85