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 "bluemonkey.h"
21 #include "abstractroutingengine.h"
22 #include "ambplugin.h"
25 #include <QJsonDocument>
26 #include <QScriptEngine>
32 Q_SCRIPT_DECLARE_QMETAOBJECT(QTimer, QObject*)
34 #define foreach Q_FOREACH
36 extern "C" AbstractSource * create(AbstractRoutingEngine* routingengine, map<string, string> config)
38 auto plugin = new AmbPlugin<BluemonkeySink>(routingengine, config);
44 QVariant gvariantToQVariant(GVariant *value)
46 GVariantClass c = g_variant_classify(value);
47 if(c == G_VARIANT_CLASS_BOOLEAN)
48 return QVariant((bool) g_variant_get_boolean(value));
50 else if(c == G_VARIANT_CLASS_BYTE)
51 return QVariant((char) g_variant_get_byte(value));
53 else if(c == G_VARIANT_CLASS_INT16)
54 return QVariant((int) g_variant_get_int16(value));
56 else if(c == G_VARIANT_CLASS_UINT16)
57 return QVariant((unsigned int) g_variant_get_uint16(value));
59 else if(c == G_VARIANT_CLASS_INT32)
60 return QVariant((int) g_variant_get_int32(value));
62 else if(c == G_VARIANT_CLASS_UINT32)
63 return QVariant((unsigned int) g_variant_get_uint32(value));
65 else if(c == G_VARIANT_CLASS_INT64)
66 return QVariant((long long) g_variant_get_int64(value));
68 else if(c == G_VARIANT_CLASS_UINT64)
69 return QVariant((unsigned long long) g_variant_get_uint64(value));
71 else if(c == G_VARIANT_CLASS_DOUBLE)
72 return QVariant(g_variant_get_double(value));
74 else if(c == G_VARIANT_CLASS_STRING)
75 return QVariant(g_variant_get_string(value, NULL));
77 else if(c == G_VARIANT_CLASS_ARRAY)
79 gsize dictsize = g_variant_n_children(value);
81 for (int i=0;i<dictsize;i++)
83 GVariant *childvariant = g_variant_get_child_value(value,i);
84 GVariant *innervariant = g_variant_get_variant(childvariant);
85 list.append(gvariantToQVariant(innervariant));
91 return QVariant::Invalid;
95 BluemonkeySink::BluemonkeySink(AbstractRoutingEngine* e, map<string, string> config, AbstractSource &parent): QObject(0), AmbPluginImpl(e, config, parent), agent(nullptr), engine(nullptr), mSilentMode(false)
97 QTimer::singleShot(1,this,SLOT(reloadEngine()));
99 auth = new Authenticate(config, this);
101 /* connect(irc, &IrcCommunication::message, [&](QString sender, QString prefix, QString codes ) {
103 if(codes.startsWith("authenticate"))
106 int i = codes.indexOf("authenticate");
107 QString pin = codes.mid(i+13);
111 if(!auth->authorize(prefix, pin))
112 irc->respond(sender,"failed");
116 else if(codes.startsWith("bluemonkey"))
118 if(!auth->isAuthorized(prefix))
121 irc->respond(sender, "denied");
125 QString bm("bluemonkey");
127 codes = codes.mid(bm.length()+1);
129 QString response = engine->evaluate(codes).toString();
131 if(!mSilentMode || response != "undefined" )
132 irc->respond(sender, response);
139 PropertyList BluemonkeySink::subscriptions()
144 void BluemonkeySink::supportedChanged(const PropertyList & supportedProperties)
146 DebugOut()<<"supported changed"<<endl;
149 void BluemonkeySink::propertyChanged(AbstractPropertyType * value)
154 const string BluemonkeySink::uuid() const
159 int BluemonkeySink::supportedOperations()
161 return AbstractSource::Get | AbstractSource::Set;
164 QObject *BluemonkeySink::subscribeTo(QString str)
166 return new Property(str.toStdString(), "", routingEngine, this);
169 QObject *BluemonkeySink::subscribeTo(QString str, QString srcFilter)
171 return new Property(str.toStdString(), srcFilter, routingEngine, this);
174 QStringList BluemonkeySink::sourcesForProperty(QString property)
176 std::list<std::string> list = routingEngine->sourcesForProperty(property.toStdString());
178 for(auto itr = list.begin(); itr != list.end(); itr++)
180 strList<<(*itr).c_str();
186 QStringList BluemonkeySink::supportedProperties()
188 PropertyList props = routingEngine->supported();
199 bool BluemonkeySink::authenticate(QString pass)
204 void BluemonkeySink::loadConfig(QString str)
207 if(!file.open(QIODevice::ReadOnly))
209 DebugOut()<<"failed to open config file: "<<str.toStdString()<<endl;
213 QString script = file.readAll();
217 DebugOut()<<"evaluating script: "<<script.toStdString()<<endl;
219 QScriptValue val = engine->evaluate(script);
221 DebugOut()<<val.toString().toStdString()<<endl;
224 void BluemonkeySink::reloadEngine()
227 engine->deleteLater();
229 engine = new QScriptEngine(this);
231 if(agent) delete agent;
233 agent = new BluemonkeyAgent(engine);
235 //engine->setAgent(agent);
237 QScriptValue value = engine->newQObject(this);
238 engine->globalObject().setProperty("bluemonkey", value);
240 QScriptValue qtimerClass = engine->scriptValueFromQMetaObject<QTimer>();
241 engine->globalObject().setProperty("QTimer", qtimerClass);
243 // QScriptValue ircValue = engine->newQObject(irc);
244 // engine->globalObject().setProperty("irc", ircValue);
246 loadConfig(configuration["config"].c_str());
249 void BluemonkeySink::writeProgram(QString program)
251 QScriptSyntaxCheckResult result = QScriptEngine::checkSyntax(program);
252 if(result.state() != QScriptSyntaxCheckResult::Valid)
254 DebugOut(DebugOut::Error)<<"Syntax error in program: "<<result.errorMessage().toStdString()<<endl;
258 QFile file(configuration["customPrograms"].c_str());
260 if(!file.open(QIODevice::ReadWrite | QIODevice::Append))
262 DebugOut(DebugOut::Error)<<"failed to open file: "<<file.fileName().toStdString()<<endl;
266 file.write(program.toUtf8());
272 void BluemonkeySink::log(QString str)
274 DebugOut()<<str.toStdString()<<endl;
277 void BluemonkeySink::getHistory(QStringList properties, QDateTime begin, QDateTime end, QScriptValue cbFunction)
279 double b = (double)begin.toMSecsSinceEpoch() / 1000.0;
280 double e = (double)end.toMSecsSinceEpoch() / 1000.0;
281 AsyncRangePropertyRequest request;
282 request.timeBegin = b;
285 PropertyList reqlist;
287 foreach(QString prop, properties)
289 reqlist.push_back(prop.toStdString());
292 request.properties = reqlist;
293 request.completed = [&cbFunction](AsyncRangePropertyReply* reply)
297 DebugOut(DebugOut::Error)<<"bluemoney get history call failed"<<endl;
301 if(cbFunction.isFunction())
305 for(auto itr = reply->values.begin(); itr != reply->values.end(); itr++)
307 AbstractPropertyType *val = *itr;
309 list.append(gvariantToQVariant(val->toVariant()));
312 cbFunction.call(QScriptValue(),cbFunction.engine()->newVariant(list));
319 routingEngine->getRangePropertyAsync(request);
322 void BluemonkeySink::createCustomProperty(QString name, QScriptValue defaultValue)
325 auto create = [defaultValue, name]() -> AbstractPropertyType*
327 QVariant var = defaultValue.toVariant();
332 if(var.type() == QVariant::UInt)
333 return new BasicPropertyType<uint>(name.toStdString(), var.toUInt());
334 else if(var.type() == QVariant::Double)
335 return new BasicPropertyType<double>(name.toStdString(), var.toDouble());
336 else if(var.type() == QVariant::Bool)
337 return new BasicPropertyType<bool>(name.toStdString(), var.toBool());
338 else if(var.type() == QVariant::Int)
339 return new BasicPropertyType<int>(name.toStdString(), var.toInt());
340 else if(var.type() == QVariant::String)
341 return new StringPropertyType(name.toStdString(), var.toString().toStdString());
347 addPropertySupport(Zone::None, create);
349 routingEngine->updateSupported(supported(), PropertyList(), &source);
353 QVariant Property::value()
355 return mValue ? gvariantToQVariant(mValue->toVariant()) : QVariant::Invalid;
358 void Property::setValue(QVariant v)
360 if(v.type() == QVariant::List || v.type() == QVariant::Map)
363 QJsonDocument doc = QJsonDocument::fromVariant(v);
365 QString json = doc.toJson();
367 mValue->fromString(json.toStdString());
371 QString tempVal = v.toString();
372 mValue->fromString(tempVal.toStdString());
375 AsyncSetPropertyRequest request;
376 request.property = mValue->name;
377 request.value = mValue->copy();
378 request.completed = [&](AsyncPropertyReply* reply)
382 propertyChanged(reply->value);
386 routingEngine->setProperty(request);
389 void Property::getHistory(QDateTime begin, QDateTime end, QScriptValue cbFunction)
391 double b = (double)begin.toMSecsSinceEpoch() / 1000.0;
392 double e = (double)end.toMSecsSinceEpoch() / 1000.0;
393 AsyncRangePropertyRequest request;
394 request.timeBegin = b;
397 PropertyList reqlist;
398 reqlist.push_back(mValue->name);
400 request.properties = reqlist;
401 request.completed = [&cbFunction](AsyncRangePropertyReply* reply)
405 DebugOut(DebugOut::Error)<<"bluemoney get history call failed"<<endl;
409 if(cbFunction.isFunction())
413 for(auto itr = reply->values.begin(); itr != reply->values.end(); itr++)
415 AbstractPropertyType *val = *itr;
417 list.append(gvariantToQVariant(val->toVariant()));
420 cbFunction.call(QScriptValue(),cbFunction.engine()->newVariant(list));
427 routingEngine->getRangePropertyAsync(request);
430 Property::Property(VehicleProperty::Property prop, QString srcFilter, AbstractRoutingEngine* re, QObject *parent)
431 :QObject(parent), AbstractSink(re, std::map<std::string,std::string>()),mValue(nullptr), mUuid(amb::createUuid())
433 setType(prop.c_str());
436 QString Property::type()
438 return mValue->name.c_str();
441 void Property::setType(QString t)
443 if(mValue && type() != "")
444 routingEngine->unsubscribeToProperty(type().toStdString(), this);
446 routingEngine->subscribeToProperty(t.toStdString(), this);
448 mValue = VehicleProperty::getPropertyTypeForPropertyNameValue(t.toStdString());
453 AsyncPropertyRequest request;
454 request.property = mValue->name;
455 request.completed = [this](AsyncPropertyReply* reply)
458 propertyChanged(reply->value);
463 routingEngine->getPropertyAsync(request);
466 void Property::propertyChanged(AbstractPropertyType *value)
472 mValue = value->copy();
474 changed(gvariantToQVariant(mValue->toVariant()));