2 Copyright (C) 2012 Intel Corporation
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with this library; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 #include "websocketsource.h"
22 #include <boost/assert.hpp>
23 #include <boost/lexical_cast.hpp>
26 #include <listplusplus.h>
28 #include <timestamp.h>
29 #include "uuidhelper.h"
31 #include <QVariantMap>
32 #include <QJsonDocument>
33 #include <QStringList>
37 #include "superptr.hpp"
39 #define __SMALLFILE__ std::string(__FILE__).substr(std::string(__FILE__).rfind("/")+1)
40 libwebsocket_context *context = NULL;
41 WebSocketSource *source;
42 AbstractRoutingEngine *m_re;
44 double oldTimestamp=0;
47 double averageLatency=0;
49 class UniquePropertyCache
52 bool hasProperty(std::string name, std::string source, Zone::Type zone)
54 for(auto i : mProperties)
57 i->sourceUuid == source &&
66 std::shared_ptr<AbstractPropertyType> append(std::string name, std::string source, Zone::Type zone, std::string type)
68 for(auto i : mProperties)
71 i->sourceUuid == source &&
78 auto t = VehicleProperty::getPropertyTypeForPropertyNameValue(name);
82 VehicleProperty::registerProperty(name, [name, type]() -> AbstractPropertyType* {
83 if(type == amb::BasicTypes::UInt16Str)
85 return new BasicPropertyType<uint16_t>(name, 0);
87 else if(type == amb::BasicTypes::Int16Str)
89 return new BasicPropertyType<int16_t>(name, 0);
91 else if(type == amb::BasicTypes::UInt32Str)
93 return new BasicPropertyType<uint32_t>(name, 0);
95 else if(type == amb::BasicTypes::Int32Str)
97 return new BasicPropertyType<int32_t>(name, 0);
99 else if(type == amb::BasicTypes::StringStr)
101 return new StringPropertyType(name);
103 else if(type == amb::BasicTypes::DoubleStr)
105 return new BasicPropertyType<double>(name, 0);
107 else if(type == amb::BasicTypes::BooleanStr)
109 return new BasicPropertyType<bool>(name, false);
111 DebugOut(DebugOut::Warning) << "Unknown or unsupported type: " << type << endl;
114 t = VehicleProperty::getPropertyTypeForPropertyNameValue(name);
117 if(t)/// check again to see if registration succeeded
119 t->sourceUuid = source;
122 mProperties.emplace_back(t);
125 return property(name, source, zone); /// will return nullptr if t didn't register
128 std::shared_ptr<AbstractPropertyType> property(std::string name, std::string source, Zone::Type zone)
130 for(auto i : mProperties)
132 if(i->name == name &&
133 i->sourceUuid == source &&
143 std::vector<std::shared_ptr<AbstractPropertyType>> properties() { return mProperties; }
146 std::vector<std::shared_ptr<AbstractPropertyType>> mProperties;
149 UniquePropertyCache properties;
151 static int callback_http_only(libwebsocket_context *context,struct libwebsocket *wsi,enum libwebsocket_callback_reasons reason,void *user, void *in, size_t len);
152 static struct libwebsocket_protocols protocols[] = {
167 //Called when a client connects, subscribes, or unsubscribes.
168 void WebSocketSource::checkSubscriptions()
170 while (queuedRequests.size() > 0)
172 VehicleProperty::Property prop = queuedRequests.front();
173 removeOne(&queuedRequests,prop);
174 if (contains(activeRequests,prop))
178 activeRequests.push_back(prop);
182 reply["type"] = "method";
183 reply["name"] = "subscribe";
184 reply["property"] = prop.c_str();
185 reply["transactionid"] = "d293f670-f0b3-11e1-aff1-0800200c9a66";
187 lwsWriteVariant(clientsocket, reply);
190 void WebSocketSource::setConfiguration(map<string, string> config)
192 //printf("WebSocketSource::setConfiguration has been called\n");
195 configuration = config;
197 if(config.find("binaryProtocol") != config.end())
199 doBinary = config["binaryProtocol"] == "true";
202 for (map<string,string>::iterator i=configuration.begin();i!=configuration.end();i++)
204 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Incoming setting for WebSocketSource:" << (*i).first << ":" << (*i).second << "\n";
205 //printf("Incoming setting: %s:%s\n",(*i).first.c_str(),(*i).second.c_str());
206 if ((*i).first == "ip")
210 if ((*i).first == "port")
212 port = boost::lexical_cast<int>((*i).second);
214 if ((*i).first == "ssl")
216 if ((*i).second == "true")
222 m_sslEnabled = false;
226 //printf("Connecting to websocket server at %s port %i\n",ip.c_str(),port);
227 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Connecting to websocket server at" << ip << ":" << port << "\n";
231 DebugOut(5) << "SSL ENABLED" << endl;
235 clientsocket = libwebsocket_client_connect(context, ip.c_str(), port, sslval,"/", "localhost", "websocket", protocols[0].name, -1);
238 PropertyInfo WebSocketSource::getPropertyInfo(const VehicleProperty::Property &property)
240 Zone::ZoneList zones;
241 for(auto i : properties.properties())
243 if(i->name == property)
245 zones.push_back(i->zone);
249 return PropertyInfo(0, zones);
252 bool gioPollingFunc(GIOChannel *source, GIOCondition condition, gpointer data)
254 //This is the polling function. If it return false, glib will stop polling this FD.
256 oldTimestamp = amb::currentTime();
258 struct pollfd pollstruct;
259 int newfd = g_io_channel_unix_get_fd(source);
260 pollstruct.fd = newfd;
261 pollstruct.events = condition;
262 pollstruct.revents = condition;
263 libwebsocket_service_fd(context,&pollstruct);
264 if (condition & G_IO_HUP)
266 //Hang up. Returning false closes out the GIOChannel.
267 //printf("Callback on G_IO_HUP\n");
270 if (condition & G_IO_IN)
274 DebugOut() << "gioPollingFunc" << condition << endl;
279 static int checkTimeouts(gpointer data)
281 WebSocketSource *src = (WebSocketSource*)data;
282 for (auto i=src->uuidTimeoutMap.begin();i!= src->uuidTimeoutMap.end();i++)
284 if (src->uuidRangedReplyMap.find((*i).first) != src->uuidRangedReplyMap.end())
287 if (amb::currentTime() > (*i).second)
289 //We've reached timeout
290 DebugOut() << "Timeout reached for request ID:" << (*i).first << "\n";
291 src->uuidRangedReplyMap[(*i).first]->success = false;
292 src->uuidRangedReplyMap[(*i).first]->completed(src->uuidRangedReplyMap[(*i).first]);
293 src->uuidRangedReplyMap.erase((*i).first);
294 src->uuidTimeoutMap.erase((*i).first);
297 if (src->uuidTimeoutMap.size() == 0)
305 //No timeout yet, keep waiting.
310 //Reply has already come back, ignore and erase from list.
311 src->uuidTimeoutMap.erase((*i).first);
314 if (src->uuidTimeoutMap.size() == 0)
324 static int callback_http_only(libwebsocket_context *context, struct libwebsocket *wsi,enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len)
326 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 4096 + LWS_SEND_BUFFER_POST_PADDING];
327 DebugOut() << __SMALLFILE__ << ":" << __LINE__ << reason << "callback_http_only" << endl;
330 case LWS_CALLBACK_CLOSED:
331 //fprintf(stderr, "mirror: LWS_CALLBACK_CLOSED\n");
333 //printf("Connection closed!\n");
336 //case LWS_CALLBACK_PROTOCOL_INIT:
337 case LWS_CALLBACK_CLIENT_ESTABLISHED:
339 //This happens when a client initally connects. We need to request the support event types.
340 source->clientConnected = true;
341 source->checkSubscriptions();
342 //printf("Incoming connection!\n");
343 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Incoming connection" << endl;
346 toSend["type"] = "method";
347 toSend["name"] = "getSupported";
348 toSend["transactionid"] = amb::createUuid().c_str();
350 lwsWriteVariant(wsi, toSend);
354 case LWS_CALLBACK_CLIENT_RECEIVE:
356 QByteArray d((char*)in, len);
358 WebSocketSource * manager = source;
360 if(manager->expectedMessageFrames && manager->partialMessageIndex < manager->expectedMessageFrames)
362 manager->incompleteMessage += d;
363 manager->partialMessageIndex++;
366 else if(manager->expectedMessageFrames && manager->partialMessageIndex == manager->expectedMessageFrames)
368 d = manager->incompleteMessage + d;
369 manager->expectedMessageFrames = 0;
375 doc = QJsonDocument::fromBinaryData(d);
378 doc = QJsonDocument::fromJson(d);
379 DebugOut(7)<<d.data()<<endl;
384 DebugOut(DebugOut::Warning)<<"Invalid message"<<endl;
388 QVariantMap call = doc.toVariant().toMap();
390 string type = call["type"].toString().toStdString();
391 string name = call["name"].toString().toStdString();
392 string id = call["transactionid"].toString().toStdString();
394 list<pair<string,string> > pairdata;
396 if(type == "multiframe")
398 manager->expectedMessageFrames = call["frames"].toInt();
399 manager->partialMessageIndex = 1;
400 manager->incompleteMessage = "";
403 else if (type == "valuechanged")
405 QVariantMap data = call["data"].toMap();
407 string value = data["value"].toString().toStdString();
408 double timestamp = data["timestamp"].toDouble();
409 int sequence = data["sequence"].toInt();
410 Zone::Type zone = data["zone"].toInt();
411 string type = data["type"].toString().toStdString();
413 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Value changed:" << name << value << endl;
417 auto property = properties.append(name, source->uuid(), zone, type);
421 DebugOut(DebugOut::Warning) << "We either don't have this or don't support it ("
422 << name << "," << zone << "," << type << ")" << endl;
425 property->timestamp = timestamp;
426 property->sequence = sequence;
427 property->fromString(value);
429 m_re->updateProperty(property.get(), source->uuid());
431 double currenttime = amb::currentTime();
433 /** This is now the latency between when something is available to read on the socket, until
434 * a property is about to be updated in AMB. This includes libwebsockets parsing and the
435 * JSON parsing in this section.
438 DebugOut()<<"websocket network + parse latency: "<<(currenttime - property->timestamp)*1000<<"ms"<<endl;
439 totalTime += (currenttime - oldTimestamp)*1000;
441 averageLatency = totalTime / numUpdates;
443 DebugOut()<<"Average parse latency: "<<averageLatency<<endl;
447 //printf("Exception %s\n",ex.what());
448 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Exception:" << ex.what() << "\n";
451 else if (type == "methodReply")
453 if (name == "getSupported" || name == "supportedChanged")
456 QVariant data = call["data"];
458 QVariantList supported = data.toList();
460 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Got getSupported request"<<endl;
463 Q_FOREACH(QVariant p, supported)
465 QVariantMap d = p.toMap();
466 Zone::Type zone = d["zone"].toInt();
467 std::string name = d["name"].toString().toStdString();
468 std::string proptype = d["type"].toString().toStdString();
469 std::string source = d["source"].toString().toStdString();
471 properties.append(name, source, zone, proptype);
474 source->updateSupported();
477 else if (name == "getRanged")
479 QVariantList data = call["data"].toList();
481 std::list<AbstractPropertyType*> propertylist;
483 Q_FOREACH(QVariant d, data)
485 QVariantMap obj = d.toMap();
487 std::string name = obj["name"].toString().toStdString();
488 std::string value = obj["value"].toString().toStdString();
489 double timestamp = obj["timestamp"].toDouble();
490 int sequence = obj["sequence"].toInt();
492 AbstractPropertyType* type = VehicleProperty::getPropertyTypeForPropertyNameValue(name, value);
495 DebugOut() << "TODO: support custom types here: " << endl;
498 type->timestamp = timestamp;
499 type->sequence = sequence;
501 propertylist.push_back(type);
504 if (source->uuidRangedReplyMap.find(id) != source->uuidRangedReplyMap.end())
506 source->uuidRangedReplyMap[id]->values = propertylist;
507 source->uuidRangedReplyMap[id]->success = true;
508 source->uuidRangedReplyMap[id]->completed(source->uuidRangedReplyMap[id]);
509 source->uuidRangedReplyMap.erase(id);
513 DebugOut() << "getRanged methodReply has been recieved, without a request being in!. This is likely due to a request coming in after the timeout has elapsed.\n";
516 else if (name == "get")
519 DebugOut() << __SMALLFILE__ << ":" << __LINE__ << "Got \"GET\" event:" << pairdata.size()<<endl;
520 if (source->uuidReplyMap.find(id) != source->uuidReplyMap.end())
522 QVariantMap obj = call["data"].toMap();
524 std::string property = obj["property"].toString().toStdString();
525 std::string value = obj["value"].toString().toStdString();
526 double timestamp = obj["timestamp"].toDouble();
527 int sequence = obj["sequence"].toInt();
528 Zone::Type zone = obj["zone"].toInt();
530 AbstractPropertyType* v = VehicleProperty::getPropertyTypeForPropertyNameValue(property, value);
531 v->timestamp = timestamp;
532 v->sequence = sequence;
535 if (source->uuidReplyMap.find(id) != source->uuidReplyMap.end() && source->uuidReplyMap[id]->error != AsyncPropertyReply::Timeout)
537 source->uuidReplyMap[id]->value = v;
538 source->uuidReplyMap[id]->success = true;
539 source->uuidReplyMap[id]->completed(source->uuidReplyMap[id]);
540 source->uuidReplyMap.erase(id);
545 DebugOut() << "get methodReply has been recieved, without a request being in!. This is likely due to a request coming in after the timeout has elapsed.\n";
552 DebugOut() << __SMALLFILE__ << ":" << __LINE__ << "GET Method Reply INVALID! Multiple properties detected, only single are supported!!!" << "\n";
555 //data will contain a property/value map.
563 case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
565 //printf("Requested extension: %s\n",(char*)in);
569 case LWS_CALLBACK_ADD_POLL_FD:
571 DebugOut(5) << __SMALLFILE__ << ":" << __LINE__ << "Adding poll for websocket IO channel" << endl;
572 //Add a FD to the poll list.
573 GIOChannel *chan = g_io_channel_unix_new(libwebsocket_get_socket_fd(wsi));
575 /// TODO: I changed this to be more consistent with the websocket sink end. it may not be correct. TEST
577 g_io_add_watch(chan,GIOCondition(G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP),(GIOFunc)gioPollingFunc,0);
578 g_io_channel_set_close_on_unref(chan,true);
579 g_io_channel_unref(chan); //Pass ownership of the GIOChannel to the watch.
586 void WebSocketSource::updateSupported()
589 for(auto i : properties.properties())
591 if(!contains(list, i->name))
592 list.push_back(i->name);
595 m_re->updateSupported(list, PropertyList(), this);
598 WebSocketSource::WebSocketSource(AbstractRoutingEngine *re, map<string, string> config) : AbstractSource(re, config), partialMessageIndex(0),expectedMessageFrames(0)
600 m_sslEnabled = false;
601 clientConnected = false;
604 struct lws_context_creation_info info;
605 memset(&info, 0, sizeof info);
606 info.protocols = protocols;
607 info.extensions = nullptr;
609 if(config.find("useExtensions") != config.end() && config["useExtensions"] == "true")
611 info.extensions = libwebsocket_get_internal_extensions();
616 info.port = CONTEXT_PORT_NO_LISTEN;
619 context = libwebsocket_create_context(&info);
621 setConfiguration(config);
623 //printf("websocketsource loaded!!!\n");
624 g_timeout_add(1000,checkTimeouts,this); //Do this once per second, check for functions that have timed out and reply with success = false;
627 PropertyList WebSocketSource::supported()
630 for(auto i : properties.properties())
632 list.push_back(i->name);
637 int WebSocketSource::supportedOperations()
639 /// TODO: need to do this correctly based on what the host supports.
640 return Get | Set | GetRanged;
643 const string WebSocketSource::uuid()
645 return "d293f670-f0b3-11e1-aff1-0800200c9a66";
648 void WebSocketSource::subscribeToPropertyChanges(VehicleProperty::Property property)
650 //printf("Subscribed to property: %s\n",property.c_str());
651 queuedRequests.push_back(property);
654 checkSubscriptions();
659 void WebSocketSource::unsubscribeToPropertyChanges(VehicleProperty::Property property)
661 removeRequests.push_back(property);
664 checkSubscriptions();
669 void WebSocketSource::getPropertyAsync(AsyncPropertyReply *reply)
671 std::string uuid = amb::createUuid();
672 uuidReplyMap[uuid] = reply;
673 uuidTimeoutMap[uuid] = amb::currentTime() + 10.0; ///TODO: 10 second timeout, make this configurable?
676 data["property"] = reply->property.c_str();
677 data["zone"] = reply->zoneFilter;
679 QVariantMap replyvar;
680 replyvar["type"] = "method";
681 replyvar["name"] = "get";
682 replyvar["data"] = data;
683 replyvar["transactionid"] = uuid.c_str();
685 lwsWriteVariant(clientsocket, replyvar);
688 void WebSocketSource::getRangePropertyAsync(AsyncRangePropertyReply *reply)
690 std::string uuid = amb::createUuid();
691 uuidRangedReplyMap[uuid] = reply;
692 uuidTimeoutMap[uuid] = amb::currentTime() + 60; ///TODO: 60 second timeout, make this configurable?
695 s << "{\"type\":\"method\",\"name\":\"getRanged\",\"data\": {";
697 QVariantMap replyvar;
698 replyvar["type"] = "method";
699 replyvar["name"] = "getRanged";
700 replyvar["transactionid"] = uuid.c_str();
701 replyvar["timeBegin"] = reply->timeBegin;
702 replyvar["timeEnd"] = reply->timeEnd;
703 replyvar["sequenceBegin"] = reply->sequenceBegin;
704 replyvar["sequenceEnd"] = reply->sequenceEnd;
706 QStringList properties;
708 for (auto itr = reply->properties.begin(); itr != reply->properties.end(); itr++)
710 VehicleProperty::Property p = *itr;
711 properties.append(p.c_str());
714 replyvar["data"] = properties;
716 lwsWriteVariant(clientsocket, replyvar);
719 AsyncPropertyReply * WebSocketSource::setProperty( AsyncSetPropertyRequest request )
721 AsyncPropertyReply* reply = new AsyncPropertyReply(request);
724 data["property"] = request.property.c_str();
725 data["value"] = request.value->toString().c_str();
726 data["zone"] = request.zoneFilter;
729 QVariantMap replyvar;
730 replyvar["type"] = "method";
731 replyvar["name"] = "set";
732 replyvar["data"] = data;
733 replyvar["transactionid"] = amb::createUuid().c_str();
735 lwsWriteVariant(clientsocket, replyvar);
737 ///TODO: we should actually wait for a response before we simply complete the call
738 reply->success = true;
739 reply->completed(reply);
743 extern "C" AbstractSource * create(AbstractRoutingEngine* routingengine, map<string, string> config)
745 return new WebSocketSource(routingengine, config);