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 lws_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(struct lws *wsi,enum lws_callback_reasons reason,void *user, void *in, size_t len);
152 static struct lws_protocols protocols[] = {
171 //Called when a client connects, subscribes, or unsubscribes.
172 void WebSocketSource::checkSubscriptions()
174 while (queuedRequests.size() > 0)
176 VehicleProperty::Property prop = queuedRequests.front();
177 removeOne(&queuedRequests,prop);
178 if (contains(activeRequests,prop))
182 activeRequests.push_back(prop);
186 reply["type"] = "method";
187 reply["name"] = "subscribe";
188 reply["property"] = prop.c_str();
189 reply["transactionid"] = "d293f670-f0b3-11e1-aff1-0800200c9a66";
191 lwsWriteVariant(clientsocket, reply);
194 void WebSocketSource::setConfiguration(map<string, string> config)
196 //printf("WebSocketSource::setConfiguration has been called\n");
199 configuration = config;
201 if(config.find("binaryProtocol") != config.end())
203 doBinary = config["binaryProtocol"] == "true";
206 for (map<string,string>::iterator i=configuration.begin();i!=configuration.end();i++)
208 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Incoming setting for WebSocketSource:" << (*i).first << ":" << (*i).second << "\n";
209 //printf("Incoming setting: %s:%s\n",(*i).first.c_str(),(*i).second.c_str());
210 if ((*i).first == "ip")
214 if ((*i).first == "port")
216 port = boost::lexical_cast<int>((*i).second);
218 if ((*i).first == "ssl")
220 if ((*i).second == "true")
226 m_sslEnabled = false;
230 //printf("Connecting to websocket server at %s port %i\n",ip.c_str(),port);
231 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Connecting to websocket server at" << ip << ":" << port << "\n";
235 DebugOut(5) << "SSL ENABLED" << endl;
239 clientsocket = lws_client_connect(context, ip.c_str(), port, sslval,"/", "localhost", "websocket", protocols[0].name, -1);
242 PropertyInfo WebSocketSource::getPropertyInfo(const VehicleProperty::Property &property)
244 Zone::ZoneList zones;
245 for(auto i : properties.properties())
247 if(i->name == property)
249 zones.push_back(i->zone);
253 return PropertyInfo(0, zones);
256 bool gioPollingFunc(GIOChannel *source, GIOCondition condition, gpointer data)
258 //This is the polling function. If it return false, glib will stop polling this FD.
260 oldTimestamp = amb::currentTime();
262 struct pollfd pollstruct;
263 int newfd = g_io_channel_unix_get_fd(source);
264 pollstruct.fd = newfd;
265 pollstruct.events = condition;
266 pollstruct.revents = condition;
267 lws_service_fd(context,&pollstruct);
268 if (condition & G_IO_HUP)
270 //Hang up. Returning false closes out the GIOChannel.
271 //printf("Callback on G_IO_HUP\n");
274 if (condition & G_IO_IN)
278 DebugOut() << "gioPollingFunc" << condition << endl;
283 static int checkTimeouts(gpointer data)
285 WebSocketSource *src = (WebSocketSource*)data;
286 for (auto i=src->uuidTimeoutMap.begin();i!= src->uuidTimeoutMap.end();i++)
288 if (src->uuidRangedReplyMap.find((*i).first) != src->uuidRangedReplyMap.end())
291 if (amb::currentTime() > (*i).second)
293 //We've reached timeout
294 DebugOut() << "Timeout reached for request ID:" << (*i).first << "\n";
295 src->uuidRangedReplyMap[(*i).first]->success = false;
296 src->uuidRangedReplyMap[(*i).first]->completed(src->uuidRangedReplyMap[(*i).first]);
297 src->uuidRangedReplyMap.erase((*i).first);
298 src->uuidTimeoutMap.erase((*i).first);
301 if (src->uuidTimeoutMap.size() == 0)
309 //No timeout yet, keep waiting.
314 //Reply has already come back, ignore and erase from list.
315 src->uuidTimeoutMap.erase((*i).first);
318 if (src->uuidTimeoutMap.size() == 0)
328 static int callback_http_only(struct lws *wsi,enum lws_callback_reasons reason, void *user, void *in, size_t len)
330 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 4096 + LWS_SEND_BUFFER_POST_PADDING];
331 DebugOut() << __SMALLFILE__ << ":" << __LINE__ << reason << "callback_http_only" << endl;
334 case LWS_CALLBACK_CLOSED:
335 //fprintf(stderr, "mirror: LWS_CALLBACK_CLOSED\n");
337 //printf("Connection closed!\n");
340 //case LWS_CALLBACK_PROTOCOL_INIT:
341 case LWS_CALLBACK_CLIENT_ESTABLISHED:
343 //This happens when a client initally connects. We need to request the support event types.
344 source->clientConnected = true;
345 source->checkSubscriptions();
346 //printf("Incoming connection!\n");
347 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Incoming connection" << endl;
350 toSend["type"] = "method";
351 toSend["name"] = "getSupported";
352 toSend["transactionid"] = amb::createUuid().c_str();
354 lwsWriteVariant(wsi, toSend);
358 case LWS_CALLBACK_CLIENT_RECEIVE:
360 QByteArray d((char*)in, len);
362 WebSocketSource * manager = source;
364 if(manager->expectedMessageFrames && manager->partialMessageIndex < manager->expectedMessageFrames)
366 manager->incompleteMessage += d;
367 manager->partialMessageIndex++;
370 else if(manager->expectedMessageFrames && manager->partialMessageIndex == manager->expectedMessageFrames)
372 d = manager->incompleteMessage + d;
373 manager->expectedMessageFrames = 0;
376 DebugOut(7) << "data received: " << d.data() << endl;
378 int start = d.indexOf("{");
380 if(manager->incompleteMessage.isEmpty() && start > 0)
382 DebugOut(7)<< "We have an incomplete message at the beginning. Toss it away." << endl;
383 d = d.right(start-1);
387 int end = d.lastIndexOf("}");
391 manager->incompleteMessage += d;
395 QByteArray tryMessage = manager->incompleteMessage + d.left(end+1);
397 DebugOut(6) << "Trying to parse message: " << tryMessage.data() << endl;
401 QJsonParseError parseError;
403 doc = QJsonDocument::fromJson(tryMessage, &parseError);
407 DebugOut(7) << "Invalid or incomplete message" << endl;
408 DebugOut(7) << parseError.errorString().toStdString() << ": " << parseError.offset << endl;
409 manager->incompleteMessage += d;
413 manager->incompleteMessage = end == d.length()-1 ? "" : d.right(end);
415 QVariantMap call = doc.toVariant().toMap();
417 string type = call["type"].toString().toStdString();
418 string name = call["name"].toString().toStdString();
419 string id = call["transactionid"].toString().toStdString();
421 if(type == "multiframe")
423 manager->expectedMessageFrames = call["frames"].toInt();
424 manager->partialMessageIndex = 1;
425 manager->incompleteMessage = "";
428 else if (type == "valuechanged")
430 QVariantMap data = call["data"].toMap();
432 string value = data["value"].toString().toStdString();
433 double timestamp = data["timestamp"].toDouble();
434 int sequence = data["sequence"].toInt();
435 Zone::Type zone = data["zone"].toInt();
436 string type = data["type"].toString().toStdString();
438 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Value changed:" << name << value << endl;
442 auto property = properties.append(name, source->uuid(), zone, type);
446 DebugOut(DebugOut::Warning) << "We either don't have this or don't support it ("
447 << name << "," << zone << "," << type << ")" << endl;
450 property->timestamp = timestamp;
451 property->sequence = sequence;
452 property->fromString(value);
454 m_re->updateProperty(property.get(), source->uuid());
456 double currenttime = amb::currentTime();
458 /** This is now the latency between when something is available to read on the socket, until
459 * a property is about to be updated in AMB. This includes libwebsockets parsing and the
460 * JSON parsing in this section.
463 DebugOut()<<"websocket network + parse latency: "<<(currenttime - property->timestamp)*1000<<"ms"<<endl;
464 totalTime += (currenttime - oldTimestamp)*1000;
466 averageLatency = totalTime / numUpdates;
468 DebugOut()<<"Average parse latency: "<<averageLatency<<endl;
472 //printf("Exception %s\n",ex.what());
473 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Exception:" << ex.what() << "\n";
476 else if (type == "methodReply")
478 if (name == "getSupported" || name == "supportedChanged")
481 QVariant data = call["data"];
483 QVariantList supported = data.toList();
485 DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Got getSupported request"<<endl;
487 double serverTime = call["systemTime"].toDouble();
489 DebugOut() << "Server time is: " << serverTime << endl;
492 source->serverTimeOffset = amb::Timestamp::instance()->epochTime() - serverTime;
494 Q_FOREACH(QVariant p, supported)
496 QVariantMap d = p.toMap();
497 Zone::Type zone = d["zone"].toInt();
498 std::string name = d["property"].toString().toStdString();
499 std::string proptype = d["type"].toString().toStdString();
500 std::string source = d["source"].toString().toStdString();
502 properties.append(name, source, zone, proptype);
505 source->updateSupported();
508 else if (name == "getRanged")
510 QVariantList data = call["data"].toList();
512 std::list<AbstractPropertyType*> propertylist;
514 Q_FOREACH(QVariant d, data)
516 QVariantMap obj = d.toMap();
518 std::string name = obj["property"].toString().toStdString();
519 std::string value = obj["value"].toString().toStdString();
520 double timestamp = obj["timestamp"].toDouble() + source->serverTimeOffset;
521 int sequence = obj["sequence"].toInt();
523 AbstractPropertyType* type = VehicleProperty::getPropertyTypeForPropertyNameValue(name, value);
526 DebugOut() << "TODO: support custom types here: " << endl;
529 type->timestamp = timestamp;
530 type->sequence = sequence;
532 propertylist.push_back(type);
535 if (source->uuidRangedReplyMap.find(id) != source->uuidRangedReplyMap.end())
537 source->uuidRangedReplyMap[id]->values = propertylist;
538 source->uuidRangedReplyMap[id]->success = true;
539 source->uuidRangedReplyMap[id]->completed(source->uuidRangedReplyMap[id]);
540 source->uuidRangedReplyMap.erase(id);
544 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";
547 else if (name == "get")
550 DebugOut() << __SMALLFILE__ << ":" << __LINE__ << "Got \"GET\" reply" << endl;
551 if (source->uuidReplyMap.find(id) != source->uuidReplyMap.end())
553 QVariantMap obj = call["data"].toMap();
555 std::string property = obj["property"].toString().toStdString();
556 std::string value = obj["value"].toString().toStdString();
557 double timestamp = obj["timestamp"].toDouble();
558 int sequence = obj["sequence"].toInt();
559 Zone::Type zone = obj["zone"].toInt();
561 auto v = amb::make_unique(VehicleProperty::getPropertyTypeForPropertyNameValue(property, value));
563 v->timestamp = timestamp;
564 v->sequence = sequence;
567 if (source->uuidReplyMap.find(id) != source->uuidReplyMap.end() && source->uuidReplyMap[id]->error != AsyncPropertyReply::Timeout)
569 source->uuidReplyMap[id]->value = v.get();
570 source->uuidReplyMap[id]->success = true;
571 source->uuidReplyMap[id]->completed(source->uuidReplyMap[id]);
572 source->uuidReplyMap.erase(id);
577 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";
582 DebugOut() << __SMALLFILE__ << ":" << __LINE__ << "GET Method Reply INVALID! Multiple properties detected, only single are supported!!!" << "\n";
587 else if (name == "set")
589 DebugOut() << __SMALLFILE__ << ":" << __LINE__ << "Got \"SET\" event" << endl;
590 std::string id = call["transactionid"].toString().toStdString();
592 if(source->setReplyMap.find(id) != source->setReplyMap.end() && source->setReplyMap[id]->error != AsyncPropertyReply::Timeout)
594 AsyncPropertyReply* reply = source->setReplyMap[id];
596 reply->success = call["success"].toBool();
597 reply->error = AsyncPropertyReply::strToError(call["error"].toString().toStdString());
599 QVariantMap obj = call["data"].toMap();
601 std::string property = obj["property"].toString().toStdString();
602 std::string value = obj["value"].toString().toStdString();
604 double timestamp = obj["timestamp"].toDouble();
605 int sequence = obj["sequence"].toInt();
606 Zone::Type zone = obj["zone"].toInt();
608 auto v = amb::make_unique(VehicleProperty::getPropertyTypeForPropertyNameValue(property, value));
612 v->timestamp = timestamp;
613 v->sequence = sequence;
618 throw std::runtime_error("property may not be registered.");
621 reply->value = v.get();
622 reply->completed(reply);
623 source->setReplyMap.erase(id);
628 DebugOut(DebugOut::Warning) << "Unhandled methodReply: " << name << endl;
636 case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
638 //printf("Requested extension: %s\n",(char*)in);
642 case LWS_CALLBACK_ADD_POLL_FD:
644 DebugOut(5) << __SMALLFILE__ << ":" << __LINE__ << "Adding poll for websocket IO channel" << endl;
645 //Add a FD to the poll list.
646 GIOChannel *chan = g_io_channel_unix_new(lws_get_socket_fd(wsi));
648 /// TODO: I changed this to be more consistent with the websocket sink end. it may not be correct. TEST
650 g_io_add_watch(chan,GIOCondition(G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP),(GIOFunc)gioPollingFunc,0);
651 g_io_channel_set_close_on_unref(chan,true);
652 g_io_channel_unref(chan); //Pass ownership of the GIOChannel to the watch.
659 void WebSocketSource::updateSupported()
662 for(auto i : properties.properties())
664 if(!contains(list, i->name))
665 list.push_back(i->name);
668 m_re->updateSupported(list, PropertyList(), this);
671 WebSocketSource::WebSocketSource(AbstractRoutingEngine *re, map<string, string> config) : AbstractSource(re, config), partialMessageIndex(0),expectedMessageFrames(0),
674 m_sslEnabled = false;
675 clientConnected = false;
678 struct lws_context_creation_info info;
679 memset(&info, 0, sizeof info);
680 info.protocols = protocols;
681 info.extensions = nullptr;
683 if(config.find("useExtensions") != config.end() && config["useExtensions"] == "true")
685 info.extensions = lws_get_internal_extensions();
690 info.port = CONTEXT_PORT_NO_LISTEN;
693 context = lws_create_context(&info);
695 setConfiguration(config);
697 //printf("websocketsource loaded!!!\n");
698 g_timeout_add(1000,checkTimeouts,this); //Do this once per second, check for functions that have timed out and reply with success = false;
701 PropertyList WebSocketSource::supported()
704 for(auto i : properties.properties())
706 list.push_back(i->name);
711 int WebSocketSource::supportedOperations()
713 /// TODO: need to do this correctly based on what the host supports.
714 return Get | Set | GetRanged;
717 const string WebSocketSource::uuid()
719 return "d293f670-f0b3-11e1-aff1-0800200c9a66";
722 void WebSocketSource::subscribeToPropertyChanges(VehicleProperty::Property property)
724 //printf("Subscribed to property: %s\n",property.c_str());
725 queuedRequests.push_back(property);
728 checkSubscriptions();
733 void WebSocketSource::unsubscribeToPropertyChanges(VehicleProperty::Property property)
735 removeRequests.push_back(property);
738 checkSubscriptions();
743 void WebSocketSource::getPropertyAsync(AsyncPropertyReply *reply)
745 std::string uuid = amb::createUuid();
746 uuidReplyMap[uuid] = reply;
747 uuidTimeoutMap[uuid] = amb::currentTime() + 10.0; ///TODO: 10 second timeout, make this configurable?
750 data["property"] = reply->property.c_str();
751 data["zone"] = reply->zoneFilter;
753 QVariantMap replyvar;
754 replyvar["type"] = "method";
755 replyvar["name"] = "get";
756 replyvar["data"] = data;
757 replyvar["transactionid"] = uuid.c_str();
759 lwsWriteVariant(clientsocket, replyvar);
762 void WebSocketSource::getRangePropertyAsync(AsyncRangePropertyReply *reply)
764 std::string uuid = amb::createUuid();
765 uuidRangedReplyMap[uuid] = reply;
766 uuidTimeoutMap[uuid] = amb::currentTime() + 60; ///TODO: 60 second timeout, make this configurable?
769 s << "{\"type\":\"method\",\"name\":\"getRanged\",\"data\": {";
771 QVariantMap replyvar;
772 replyvar["type"] = "method";
773 replyvar["name"] = "getRanged";
774 replyvar["transactionid"] = uuid.c_str();
775 replyvar["timeBegin"] = reply->timeBegin - serverTimeOffset;
776 replyvar["timeEnd"] = reply->timeEnd - serverTimeOffset;
777 replyvar["sequenceBegin"] = reply->sequenceBegin;
778 replyvar["sequenceEnd"] = reply->sequenceEnd;
780 QStringList properties;
782 for (auto itr = reply->properties.begin(); itr != reply->properties.end(); itr++)
784 VehicleProperty::Property p = *itr;
785 properties.append(p.c_str());
788 replyvar["data"] = properties;
790 lwsWriteVariant(clientsocket, replyvar);
793 AsyncPropertyReply * WebSocketSource::setProperty( AsyncSetPropertyRequest request )
795 AsyncPropertyReply* reply = new AsyncPropertyReply(request);
797 std::string uuid = amb::createUuid();
800 data["property"] = request.property.c_str();
801 data["value"] = request.value->toString().c_str();
802 data["zone"] = request.zoneFilter;
804 QVariantMap replyvar;
805 replyvar["type"] = "method";
806 replyvar["name"] = "set";
807 replyvar["data"] = data;
808 replyvar["transactionid"] = uuid.c_str();
810 lwsWriteVariant(clientsocket, replyvar);
812 setReplyMap[uuid] = reply;
817 extern "C" AbstractSource * create(AbstractRoutingEngine* routingengine, map<string, string> config)
819 return new WebSocketSource(routingengine, config);