source: trunk/FACT++/src/StateMachineDimControl.cc@ 14711

Last change on this file since 14711 was 14674, checked in by tbretz, 12 years ago
Implemenetd a way to just check if a server is available and command descriptions have been received.
File size: 15.7 KB
Line 
1#include "StateMachineDimControl.h"
2
3#include "Dim.h"
4#include "Event.h"
5#include "RemoteControl.h"
6#include "Configuration.h"
7#include "Converter.h"
8
9using namespace std;
10
11// ------------------------------------------------------------------------
12
13bool StateMachineDimControl::fIsServer = false;
14
15string StateMachineDimControl::Line(const string &txt, char fill)
16{
17 const int n = (55-txt.length())/2;
18
19 ostringstream out;
20 out << setfill(fill);
21 out << setw(n) << fill << ' ';
22 out << txt;
23 out << ' ' << setw(n) << fill;
24
25 if (2*n+txt.length()+2 != 57)
26 out << fill;
27
28 return out.str();
29}
30
31int StateMachineDimControl::ChangeState(int qos, const Time &, int scriptdepth, string scriptfile, string user)
32{
33 string msg;
34 /*
35 switch (qos)
36 {
37 case -4: msg = "End"; break;
38 case -3: msg = "Loading"; break;
39 case -2: msg = "Compiling"; break;
40 case -1: msg = "Running"; break;
41 default:
42 {
43 ostringstream out;
44 out << "Label " << qos;
45 msg = out.str();
46 }
47 }
48 */
49
50 //if (qos<0)
51 msg += to_string(scriptdepth);
52
53 msg += ":"+scriptfile+"["+user+":"+to_string(getpid())+"]";
54
55 //if (fDebug)
56 //Write(time, Line(msg, qos<-1 ? '=' :'-'), MessageImp::kInternal);
57
58 if (qos==-4)
59 fScriptUser = fUser;
60
61 SetCurrentState(qos+4, msg.c_str());
62 //SetCurrentState(qos+4, Line(msg, qos<-1 ? '=' :'-').c_str());
63 return GetCurrentState();
64
65 //return qos+4;
66}
67
68int StateMachineDimControl::Write(const Time &time, const std::string &txt, int qos)
69{
70 if (txt=="")
71 {
72 return ChangeState(qos, time, Readline::GetScriptDepth(), Readline::GetScript(), fScriptUser);
73 /*
74 === This might be necessary for thread safety,
75 === but it break that the signal for the start of a new
76 === script arrives synchronously before the first output
77 === from the script
78
79 // Post an anonymous event to the event loop
80 Event evt("");
81 evt.AssignFunction(bind(&StateMachineDimControl::ChangeState, this,
82 qos, time, Readline::GetScriptDepth(),
83 Readline::GetScript(), fScriptUser));
84 return PostEvent(evt);
85 */
86 }
87
88 // if (qos<fVerbosity)
89 // return 0;
90
91 return StateMachineDim::Write(time, txt, qos);
92}
93
94int StateMachineDimControl::StartScript(const EventImp &imp, const string &cmd)
95{
96 string opt(imp.GetString());
97
98 const map<string,string> data = Tools::Split(opt, true);
99 if (imp.GetSize()==0 || opt.size()==0 || opt[0]==0)
100 {
101 Error("File name missing in DIM_CONTROL/START");
102 return GetCurrentState();
103 }
104
105 if (fDebug)
106 Debug("Start '"+opt+"' received.");
107
108 if (fDebug)
109 Debug("Received data: "+imp.GetString());
110
111 const auto user = data.find("user");
112 fScriptUser = user==data.end() ? fUser : user->second;
113
114 if (fDebug)
115 {
116 for (auto it=data.begin(); it!=data.end(); it++)
117 Debug(" Arg: "+it->first+" = "+it->second);
118 }
119
120 string emit = cmd+imp.GetString();
121 if (cmd==".js ")
122 emit += fArgumentsJS;
123
124 Readline::SetExternalInput(emit);
125 return 1;
126}
127
128int StateMachineDimControl::StopScript()
129{
130 Readline::StopScript();
131 InterpreterV8::JsStop();
132 return GetCurrentState();
133}
134
135bool StateMachineDimControl::SendDimCommand(const string &server, string str, ostream &lout)
136{
137 const lock_guard<mutex> guard(fMutex);
138
139 if (fServerList.find(server)==fServerList.end())
140 throw runtime_error("SendDimCommand - Server '"+server+"' not online.");
141
142 str = Tools::Trim(str);
143
144 // Find the delimiter between the command name and the data
145 size_t p0 = str.find_first_of(' ');
146 if (p0==string::npos)
147 p0 = str.length();
148
149 // Get just the command name separated from the data
150 const string name = str.substr(0, p0);
151
152 // Compile the command which will be sent to the state-machine
153 for (auto is=fServiceList.begin(); is!=fServiceList.end(); is++)
154 {
155 if (str.empty() && is->server==server)
156 return true;
157
158 if (is->server!=server || is->service!=name)
159 continue;
160
161 if (!is->iscmd)
162 throw runtime_error("'"+server+"/"+name+" not a command.");
163
164 // Avoid compiler warning of unused parameter
165 lout << flush;
166
167 // Convert the user entered data according to the format string
168 // into a data block which will be attached to the event
169#ifndef DEBUG
170 ostringstream sout;
171 const Converter conv(sout, is->format, false);
172#else
173 const Converter conv(lout, is->format, false);
174#endif
175 if (!conv)
176 throw runtime_error("Couldn't properly parse the format... ignored.");
177
178#ifdef DEBUG
179 lout << kBlue << server << '/' << name;
180#endif
181 const vector<char> v = conv.GetVector(str.substr(p0));
182#ifdef DEBUG
183 lout << kBlue << " [" << v.size() << "]" << endl;
184#endif
185 const string cmd = server + '/' + name;
186 const int rc = DimClient::sendCommand(cmd.c_str(), (void*)v.data(), v.size());
187 if (!rc)
188 throw runtime_error("ERROR - Sending command "+cmd+" failed.");
189
190 return true;
191 }
192
193 if (!str.empty())
194 throw runtime_error("SendDimCommand - Format information for "+server+"/"+name+" not yet available.");
195
196 return false;
197}
198
199int StateMachineDimControl::PrintStates(std::ostream &out, const std::string &serv)
200{
201 const lock_guard<mutex> guard(fMutex);
202
203 int rc = 0;
204 for (auto it=fServerList.begin(); it!=fServerList.end(); it++)
205 {
206 if (!serv.empty() && *it!=serv)
207 continue;
208
209 out << kRed << "----- " << *it << " -----" << endl;
210
211 int cnt = 0;
212 for (auto is=fStateDescriptionList.begin(); is!=fStateDescriptionList.end(); is++)
213 {
214 const string &server = is->first.first;
215
216 if (server!=*it)
217 continue;
218
219 const int32_t &state = is->first.second;
220 const string &name = is->second.first;
221 const string &comment = is->second.second;
222
223 out << kBold << setw(5) << state << kReset << ": ";
224 out << kYellow << name;
225 if (!comment.empty())
226 out << kBlue << " (" << comment << ")";
227 out << endl;
228
229 cnt++;
230 }
231
232 if (cnt==0)
233 out << " <no states>" << endl;
234 else
235 rc++;
236
237 out << endl;
238 }
239
240 return rc;
241}
242
243int StateMachineDimControl::PrintDescription(std::ostream &out, bool iscmd, const std::string &serv, const std::string &service)
244{
245 const lock_guard<mutex> guard(fMutex);
246
247 int rc = 0;
248 for (auto it=fServerList.begin(); it!=fServerList.end(); it++)
249 {
250 if (!serv.empty() && *it!=serv)
251 continue;
252
253 out << kRed << "----- " << *it << " -----" << endl << endl;
254
255 for (auto is=fServiceList.begin(); is!=fServiceList.end(); is++)
256 {
257 if (is->server!=*it)
258 continue;
259
260 if (!service.empty() && is->service!=service)
261 continue;
262
263 if (is->iscmd!=iscmd)
264 continue;
265
266 rc++;
267
268 out << " " << is->service;
269 if (!is->format.empty())
270 out << '[' << is->format << ']';
271
272 const auto id = fServiceDescriptionList.find(*it+"/"+is->service);
273 if (id!=fServiceDescriptionList.end())
274 {
275 const vector<Description> &v = id->second;
276
277 for (auto j=v.begin()+1; j!=v.end(); j++)
278 out << " <" << j->name << ">";
279 out << endl;
280
281 if (!v[0].comment.empty())
282 out << " " << v[0].comment << endl;
283
284 for (auto j=v.begin()+1; j!=v.end(); j++)
285 {
286 out << " " << kGreen << j->name;
287 if (!j->comment.empty())
288 out << kReset << ": " << kBlue << j->comment;
289 if (!j->unit.empty())
290 out << kYellow << " [" << j->unit << "]";
291 out << endl;
292 }
293 }
294 out << endl;
295 }
296 out << endl;
297 }
298
299 return rc;
300}
301
302int StateMachineDimControl::HandleStateChange(const string &server, DimDescriptions *dim)
303{
304 fMutex.lock();
305 const State descr = dim->description();
306 const State state = State(dim->state(), descr.index==DimState::kNotAvailable?"":descr.name, descr.comment, dim->cur.first);
307 fCurrentStateList[server] = state;
308 fMutex.unlock();
309
310 fStateCallback(server, state);
311
312 return GetCurrentState();
313}
314
315State StateMachineDimControl::GetServerState(const std::string &server)
316{
317 const lock_guard<mutex> guard(fMutex);
318
319 const auto it = fCurrentStateList.find(server);
320 return it==fCurrentStateList.end() ? State() : it->second;
321}
322
323int StateMachineDimControl::HandleStates(const string &server, DimDescriptions *dim)
324{
325 fMutex.lock();
326
327 const auto is = fCurrentStateList.find(server);
328 for (auto it=dim->states.begin(); it!=dim->states.end(); it++)
329 {
330 fStateDescriptionList[make_pair(server, it->index)] = make_pair(it->name, it->comment);
331 if (is==fCurrentStateList.end())
332 continue;
333
334 State &s = is->second;
335 if (s.index==it->index)
336 {
337 s.name = it->name;
338 s.comment = it->comment;
339 }
340 }
341
342 fMutex.unlock();
343
344 return GetCurrentState();
345}
346
347int StateMachineDimControl::HandleDescriptions(DimDescriptions *dim)
348{
349 fMutex.lock();
350
351 for (auto it=dim->descriptions.begin(); it!=dim->descriptions.end(); it++)
352 fServiceDescriptionList[it->front().name].assign(it->begin(), it->end());
353
354 fMutex.unlock();
355
356 return GetCurrentState();
357}
358
359std::vector<Description> StateMachineDimControl::GetDescription(const std::string &service)
360{
361 const lock_guard<mutex> guard(fMutex);
362
363 const auto it = fServiceDescriptionList.find(service);
364 return it==fServiceDescriptionList.end() ? vector<Description>() : it->second;
365}
366
367int StateMachineDimControl::HandleServerAdd(const string &server)
368{
369 if (server!="DIS_DNS")
370 {
371 struct Find : string
372 {
373 Find(const string &ref) : string(ref) { }
374 bool operator()(const DimDescriptions *dim) { return *this==dim->server; }
375 };
376
377 if (find_if(fDimDescriptionsList.begin(), fDimDescriptionsList.end(),
378 Find(server))==fDimDescriptionsList.end())
379 {
380 DimDescriptions *d = new DimDescriptions(server);
381
382 fDimDescriptionsList.push_back(d);
383 d->SetCallback(bind(&StateMachineDimControl::HandleStateChange, this, server, d));
384 d->SetCallbackStates(bind(&StateMachineDimControl::HandleStates, this, server, d));
385 d->SetCallbackDescriptions(bind(&StateMachineDimControl::HandleDescriptions, this, d));
386 d->Subscribe(*this);
387 }
388 }
389
390 // Make a copy of the list to be able to
391 // lock the access to the list
392 fMutex.lock();
393 fServerList.insert(server);
394 fMutex.unlock();
395
396 return GetCurrentState();
397}
398
399int StateMachineDimControl::HandleServerRemove(const string &server)
400{
401 fMutex.lock();
402 fServerList.erase(server);
403 fMutex.unlock();
404
405 return GetCurrentState();
406}
407
408vector<string> StateMachineDimControl::GetServerList()
409{
410 vector<string> rc;
411
412 fMutex.lock();
413
414 rc.reserve(fServerList.size());
415 for (auto it=fServerList.begin(); it!=fServerList.end(); it++)
416 rc.push_back(*it);
417
418 fMutex.unlock();
419
420 return rc;
421}
422
423vector<string> StateMachineDimControl::GetCommandList(const string &server)
424{
425 const lock_guard<mutex> guard(fMutex);
426
427 const string s = server.substr(0, server.length()-1);
428
429 if (fServerList.find(s)==fServerList.end())
430 return vector<string>();
431
432 vector<string> rc;
433
434 for (auto it=fServiceList.begin(); it!=fServiceList.end(); it++)
435 if (it->iscmd && it->server==s)
436 rc.push_back(server+it->service);
437
438 return rc;
439}
440
441vector<string> StateMachineDimControl::GetCommandList()
442{
443 vector<string> rc;
444
445 fMutex.lock();
446
447 for (auto it=fServiceList.begin(); it!=fServiceList.end(); it++)
448 if (it->iscmd)
449 rc.push_back(it->server+"/"+it->service);
450
451 fMutex.unlock();
452 return rc;
453}
454
455
456int StateMachineDimControl::HandleAddService(const Service &svc)
457{
458 // Make a copy of the list to be able to
459 // lock the access to the list
460 fMutex.lock();
461 fServiceList.insert(svc);
462 fMutex.unlock();
463
464 return GetCurrentState();
465}
466
467bool StateMachineDimControl::HasServer(const std::string &server)
468{
469 fMutex.lock();
470 const bool rc = fServerList.find(server)!=fServerList.end();
471 fMutex.unlock();
472
473 return rc;
474}
475
476StateMachineDimControl::StateMachineDimControl(ostream &out) : StateMachineDim(out, fIsServer?"DIM_CONTROL":"")
477{
478 fDim.Subscribe(*this);
479 fDimList.Subscribe(*this);
480
481 fDimList.SetCallbackServerAdd (bind(&StateMachineDimControl::HandleServerAdd, this, placeholders::_1));
482 fDimList.SetCallbackServerRemove(bind(&StateMachineDimControl::HandleServerRemove, this, placeholders::_1));
483 fDimList.SetCallbackServiceAdd (bind(&StateMachineDimControl::HandleAddService, this, placeholders::_1));
484
485 // State names
486 AddStateName(0, "Idle", "No script currently in processing.");
487 AddStateName(1, "Loading", "Script is loading.");
488 AddStateName(2, "Compiling", "JavaScript is compiling.");
489 AddStateName(3, "Running", "Script is running.");
490
491 AddEvent("START", "C", 0)
492 (bind(&StateMachineDimControl::StartScript, this, placeholders::_1, ".js "))
493 ("Start a JavaScript");
494
495 AddEvent("EXECUTE", "C", 0)
496 (bind(&StateMachineDimControl::StartScript, this, placeholders::_1, ".x "))
497 ("Execute a batch script");
498
499 AddEvent("STOP", "C")
500 (bind(&StateMachineDimControl::StopScript, this))
501 ("Stop a runnning batch script or JavaScript");
502}
503
504StateMachineDimControl::~StateMachineDimControl()
505{
506 for (auto it=fDimDescriptionsList.begin(); it!=fDimDescriptionsList.end(); it++)
507 delete *it;
508}
509
510int StateMachineDimControl::EvalOptions(Configuration &conf)
511{
512 fDebug = conf.Get<bool>("debug");
513 fUser = conf.Get<string>("user");
514 fScriptUser = fUser;
515
516 const map<string, string> &js = conf.GetOptions<string>("JavaScript.");
517 for (auto it=js.begin(); it!=js.end(); it++)
518 {
519 string key = it->first;
520 string val = it->second;
521
522 // Escape key
523 boost::replace_all(key, "\\", "\\\\");
524 boost::replace_all(key, "'", "\\'");
525 boost::replace_all(key, "\"", "\\\"");
526
527 // Escape value
528 boost::replace_all(val, "\\", "\\\\");
529 boost::replace_all(val, "'", "\\'");
530 boost::replace_all(val, "\"", "\\\"");
531
532 fArgumentsJS += " '"+key +"'='"+val+"'";
533 }
534
535 // fVerbosity = 40;
536
537 // if (conf.Has("verbosity"))
538 // fVerbosity = conf.Get<uint32_t>("verbosity");
539
540 // if (conf.Get<bool>("quiet"))
541 // fVerbosity = 90;
542
543 const int cnt = conf.Get<bool>("stop")+conf.Has("start")+conf.Has("batch");
544
545 if (fIsServer)
546 {
547 if (cnt>0)
548 {
549 Error("--start, --batch, --stop are mutually exclusive to --server.");
550 return 3;
551 }
552 return -1;
553 }
554
555 if (cnt>1)
556 {
557 Error("--start, --batch and --stop are all mutually exclusive.");
558 return 4;
559 }
560
561 if (conf.Get<bool>("stop"))
562 return Dim::SendCommand("DIM_CONTROL/STOP", fUser) + 1;
563
564 if (conf.Has("start"))
565 return Dim::SendCommand("DIM_CONTROL/START", conf.Get<string>("start")+" user="+fUser) + 1;
566
567 if (conf.Has("batch"))
568 return Dim::SendCommand("DIM_CONTROL/EXECUTE", conf.Get<string>("batch")+" user="+fUser) + 1;
569
570 if (conf.Has("msg"))
571 return Dim::SendCommand("CHAT/MSG", fUser+": "+conf.Get<string>("msg")) + 1;
572
573 return -1;
574}
Note: See TracBrowser for help on using the repository browser.