/
zmserver.cpp
1650 lines (1354 loc) · 43 KB
/
zmserver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Implementation of the ZMServer class.
* ============================================================
* This program is free software; you can redistribute it
* and/or modify it under the terms of the GNU General
* Public License as published bythe Free Software Foundation;
* either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* ============================================================ */
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <errno.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/shm.h>
#ifdef linux
# include <sys/vfs.h>
# include <sys/statvfs.h>
# include <sys/sysinfo.h>
#else
# include <sys/param.h>
# include <sys/mount.h>
# if CONFIG_CYGWIN
# include <sys/statfs.h>
# else // if !CONFIG_CYGWIN
# include <sys/sysctl.h>
# endif // !CONFIG_CYGWIN
#endif
#include "mythtv/mythconfig.h"
#if CONFIG_DARWIN
#define MSG_NOSIGNAL 0 // Apple also has SO_NOSIGPIPE?
#endif
#include "zmserver.h"
// the version of the protocol we understand
#define ZM_PROTOCOL_VERSION "6"
// the maximum image size we are ever likely to get from ZM
#define MAX_IMAGE_SIZE (2048*1536*3)
#define ADD_STR(list,s) list += s; list += "[]:[]";
// error messages
#define ERROR_TOKEN_COUNT "Invalid token count"
#define ERROR_MYSQL_QUERY "Mysql Query Error"
#define ERROR_MYSQL_ROW "Mysql Get Row Error"
#define ERROR_FILE_OPEN "Cannot open event file"
#define ERROR_INVALID_MONITOR "Invalid Monitor"
#define ERROR_INVALID_POINTERS "Cannot get shared memory pointers"
#define ERROR_INVALID_MONITOR_FUNCTION "Invalid Monitor Function"
#define ERROR_INVALID_MONITOR_ENABLE_VALUE "Invalid Monitor Enable Value"
MYSQL g_dbConn;
string g_zmversion = "";
string g_password = "";
string g_server = "";
string g_database = "";
string g_webPath = "";
string g_user = "";
string g_webUser = "";
string g_binPath = "";
time_t g_lastDBKick = 0;
void loadZMConfig(const string &configfile)
{
cout << "loading zm config from " << configfile << endl;
FILE *cfg;
char line[512];
char val[250];
if ( (cfg = fopen(configfile.c_str(), "r")) == NULL )
{
fprintf(stderr,"Can't open %s\n", configfile.c_str());
exit(1);
}
while ( fgets( line, sizeof(line), cfg ) != NULL )
{
char *line_ptr = line;
// Trim off any cr/lf line endings
size_t chomp_len = strcspn( line_ptr, "\r\n" );
line_ptr[chomp_len] = '\0';
// Remove leading white space
size_t white_len = strspn( line_ptr, " \t" );
line_ptr += white_len;
// Check for comment or empty line
if ( *line_ptr == '\0' || *line_ptr == '#' )
continue;
// Remove trailing white space
char *temp_ptr = line_ptr+strlen(line_ptr)-1;
while ( *temp_ptr == ' ' || *temp_ptr == '\t' )
{
*temp_ptr-- = '\0';
temp_ptr--;
}
// Now look for the '=' in the middle of the line
temp_ptr = strchr( line_ptr, '=' );
if ( !temp_ptr )
{
fprintf(stderr,"Invalid data in %s: '%s'\n", configfile.c_str(), line );
continue;
}
// Assign the name and value parts
char *name_ptr = line_ptr;
char *val_ptr = temp_ptr+1;
// Trim trailing space from the name part
do
{
*temp_ptr = '\0';
temp_ptr--;
}
while ( *temp_ptr == ' ' || *temp_ptr == '\t' );
// Remove leading white space from the value part
white_len = strspn( val_ptr, " \t" );
val_ptr += white_len;
strncpy( val, val_ptr, strlen(val_ptr)+1 );
if ( strcasecmp( name_ptr, "ZM_DB_HOST" ) == 0 ) g_server = val;
else if ( strcasecmp( name_ptr, "ZM_DB_NAME" ) == 0 ) g_database = val;
else if ( strcasecmp( name_ptr, "ZM_DB_USER" ) == 0 ) g_user = val;
else if ( strcasecmp( name_ptr, "ZM_DB_PASS" ) == 0 ) g_password = val;
else if ( strcasecmp( name_ptr, "ZM_PATH_WEB" ) == 0 ) g_webPath = val;
else if ( strcasecmp( name_ptr, "ZM_PATH_BIN" ) == 0 ) g_binPath = val;
else if ( strcasecmp( name_ptr, "ZM_WEB_USER" ) == 0 ) g_webUser = val;
else if ( strcasecmp( name_ptr, "ZM_VERSION" ) == 0 ) g_zmversion = val;
}
fclose(cfg);
}
void connectToDatabase(void)
{
if (!mysql_init(&g_dbConn))
{
cout << "Error: Can't initialise structure: " << mysql_error(&g_dbConn) << endl;
exit(mysql_errno(&g_dbConn));
}
if (!mysql_real_connect(&g_dbConn, g_server.c_str(), g_user.c_str(),
g_password.c_str(), 0, 0, 0, 0))
{
cout << "Error: Can't connect to server: " << mysql_error(&g_dbConn) << endl;
exit(mysql_errno( &g_dbConn));
}
if (mysql_select_db(&g_dbConn, g_database.c_str()))
{
cout << "Error: Can't select database: " << mysql_error(&g_dbConn) << endl;
exit(mysql_errno(&g_dbConn));
}
}
void kickDatabase(bool debug)
{
if (time(NULL) < g_lastDBKick + DB_CHECK_TIME)
return;
if (debug)
cout << "Kicking database connection" << endl;
g_lastDBKick = time(NULL);
if (mysql_query(&g_dbConn, "SELECT NULL;") == 0)
{
MYSQL_RES *res = mysql_store_result(&g_dbConn);
if (res)
mysql_free_result(res);
return;
}
cout << "Lost connection to DB - trying to reconnect" << endl;
// failed so try to reconnect to the DB
mysql_close(&g_dbConn);
connectToDatabase();
}
ZMServer::ZMServer(int sock, bool debug)
{
if (debug)
cout << "Using server protocol version '" << ZM_PROTOCOL_VERSION << "'\n";
m_sock = sock;
m_debug = debug;
// get the shared memory key
char buf[100];
m_shmKey = 0x7a6d2000;
string setting = getZMSetting("ZM_SHM_KEY");
if (setting != "")
sscanf(setting.c_str(), "%x", (unsigned int *)&m_shmKey);
if (m_debug)
{
snprintf(buf, sizeof(buf), "0x%x", (unsigned int)m_shmKey);
cout << "Shared memory key is: " << buf << endl;
}
// get the event filename format
setting = getZMSetting("ZM_EVENT_IMAGE_DIGITS");
int eventDigits = atoi(setting.c_str());
snprintf(buf, sizeof(buf), "%%0%dd-capture.jpg", eventDigits);
m_eventFileFormat = buf;
if (m_debug)
cout << "Event file format is: " << m_eventFileFormat << endl;
// get the analyse filename format
snprintf(buf, sizeof(buf), "%%0%dd-analyse.jpg", eventDigits);
m_analyseFileFormat = buf;
if (m_debug)
cout << "Analyse file format is: " << m_analyseFileFormat << endl;
getMonitorList();
}
ZMServer::~ZMServer()
{
if (m_debug)
cout << "ZMServer destroyed\n";
}
void ZMServer::tokenize(const string &command, vector<string> &tokens)
{
string token = "";
tokens.clear();
string::size_type startPos = 0;
string::size_type endPos = 0;
while((endPos = command.find("[]:[]", startPos)) != string::npos)
{
token = command.substr(startPos, endPos - startPos);
tokens.push_back(token);
startPos = endPos + 5;
}
// make sure we add the last token
if (endPos != command.length())
{
token = command.substr(startPos);
tokens.push_back(token);
}
}
void ZMServer::processRequest(char* buf, int nbytes)
{
#if 0
// first 8 bytes is the length of the following data
char len[9];
memcpy(len, buf, 8);
len[8] = '\0';
int dataLen = atoi(len);
#endif
buf[nbytes] = '\0';
string s(buf+8);
vector<string> tokens;
tokenize(s, tokens);
if (tokens.size() == 0)
return;
if (m_debug)
cout << "Processing: '" << tokens[0] << "'" << endl;
if (tokens[0] == "HELLO")
handleHello();
else if (tokens[0] == "GET_SERVER_STATUS")
handleGetServerStatus();
else if (tokens[0] == "GET_MONITOR_STATUS")
handleGetMonitorStatus();
else if (tokens[0] == "GET_EVENT_LIST")
handleGetEventList(tokens);
else if (tokens[0] == "GET_EVENT_DATES")
handleGetEventDates(tokens);
else if (tokens[0] == "GET_EVENT_FRAME")
handleGetEventFrame(tokens);
else if (tokens[0] == "GET_ANALYSE_FRAME")
handleGetAnalyseFrame(tokens);
else if (tokens[0] == "GET_LIVE_FRAME")
handleGetLiveFrame(tokens);
else if (tokens[0] == "GET_FRAME_LIST")
handleGetFrameList(tokens);
else if (tokens[0] == "GET_CAMERA_LIST")
handleGetCameraList();
else if (tokens[0] == "GET_MONITOR_LIST")
handleGetMonitorList();
else if (tokens[0] == "DELETE_EVENT")
handleDeleteEvent(tokens);
else if (tokens[0] == "DELETE_EVENT_LIST")
handleDeleteEventList(tokens);
else if (tokens[0] == "RUN_ZMAUDIT")
handleRunZMAudit();
else if (tokens[0] == "SET_MONITOR_FUNCTION")
handleSetMonitorFunction(tokens);
else
send("UNKNOWN_COMMAND");
}
bool ZMServer::send(const string s) const
{
// send length
uint32_t len = s.size();
char buf[9];
sprintf(buf, "%8d", len);
int status = ::send(m_sock, buf, 8, MSG_NOSIGNAL);
if (status == -1)
return false;
// send message
status = ::send(m_sock, s.c_str(), s.size(), MSG_NOSIGNAL);
if ( status == -1 )
return false;
else
return true;
}
bool ZMServer::send(const string s, const unsigned char *buffer, int dataLen) const
{
// send length
uint32_t len = s.size();
char buf[9];
sprintf(buf, "%8d", len);
int status = ::send(m_sock, buf, 8, MSG_NOSIGNAL);
if (status == -1)
return false;
// send message
status = ::send(m_sock, s.c_str(), s.size(), MSG_NOSIGNAL);
if ( status == -1 )
return false;
// send data
status = ::send(m_sock, buffer, dataLen, MSG_NOSIGNAL);
if ( status == -1 )
return false;
return true;
}
void ZMServer::sendError(string error)
{
string outStr("");
ADD_STR(outStr, string("ERROR - ") + error);
send(outStr);
}
void ZMServer::handleHello()
{
// just send OK so the client knows all is well
// followed by the protocol version we understand
string outStr("");
ADD_STR(outStr, "OK");
ADD_STR(outStr, ZM_PROTOCOL_VERSION);
send(outStr);
}
long long ZMServer::getDiskSpace(const string &filename, long long &total, long long &used)
{
struct statfs statbuf;
memset(&statbuf, 0, sizeof(statbuf));
long long freespace = -1;
total = used = -1;
// there are cases where statfs will return 0 (good), but f_blocks and
// others are invalid and set to 0 (such as when an automounted directory
// is not mounted but still visible because --ghost was used),
// so check to make sure we can have a total size > 0
if ((statfs(filename.c_str(), &statbuf) == 0) &&
(statbuf.f_blocks > 0) &&
(statbuf.f_bsize > 0))
{
total = statbuf.f_blocks;
total *= statbuf.f_bsize;
total = total >> 10;
freespace = statbuf.f_bavail;
freespace *= statbuf.f_bsize;
freespace = freespace >> 10;
used = total - freespace;
}
return freespace;
}
void ZMServer::handleGetServerStatus(void)
{
string outStr("");
ADD_STR(outStr, "OK")
// server status
string status = runCommand(g_binPath + "/zmdc.pl check");
ADD_STR(outStr, status)
// get load averages
double loads[3];
if (getloadavg(loads, 3) == -1)
{
ADD_STR(outStr, "Unknown")
}
else
{
char buf[30];
sprintf(buf, "%0.2lf", loads[0]);
ADD_STR(outStr, buf)
}
// get free space on the disk where the events are stored
char buf[15];
long long total, used;
string eventsDir = g_webPath + "/events/";
getDiskSpace(eventsDir, total, used);
sprintf(buf, "%d%%", (int) ((100.0 / ((float) total / used))));
ADD_STR(outStr, buf)
send(outStr);
}
void ZMServer::handleGetEventList(vector<string> tokens)
{
string outStr("");
if (tokens.size() != 4)
{
sendError(ERROR_TOKEN_COUNT);
return;
}
string monitor = tokens[1];
bool oldestFirst = (tokens[2] == "1");
string date = tokens[3];
if (m_debug)
cout << "Loading events for monitor: " << monitor << ", date: " << date << endl;
ADD_STR(outStr, "OK")
MYSQL_RES *res;
MYSQL_ROW row;
string sql("SELECT E.Id, E.Name, M.Id AS MonitorID, M.Name AS MonitorName, E.StartTime, "
"E.Length, M.Width, M.Height, M.DefaultRate, M.DefaultScale "
"from Events as E inner join Monitors as M on E.MonitorId = M.Id ");
if (monitor != "<ANY>")
{
sql += "WHERE M.Name = '" + monitor + "' ";
if (date != "<ANY>")
sql += "AND DATE(E.StartTime) = DATE('" + date + "') ";
}
else
{
if (date != "<ANY>")
sql += "WHERE DATE(E.StartTime) = DATE('" + date + "') ";
}
if (oldestFirst)
sql += "ORDER BY E.StartTime ASC";
else
sql += "ORDER BY E.StartTime DESC";
if (mysql_query(&g_dbConn, sql.c_str()))
{
fprintf(stderr, "%s\n", mysql_error(&g_dbConn));
sendError(ERROR_MYSQL_QUERY);
return;
}
res = mysql_store_result(&g_dbConn);
int eventCount = mysql_num_rows(res);
if (m_debug)
cout << "Got " << eventCount << " events" << endl;
char str[10];
sprintf(str, "%d", eventCount);
ADD_STR(outStr, str)
for (int x = 0; x < eventCount; x++)
{
row = mysql_fetch_row(res);
if (row)
{
ADD_STR(outStr, row[0]) // eventID
ADD_STR(outStr, row[1]) // event name
ADD_STR(outStr, row[2]) // monitorID
ADD_STR(outStr, row[3]) // monitor name
row[4][10] = 'T';
ADD_STR(outStr, row[4]) // start time
ADD_STR(outStr, row[5]) // length
}
else
{
cout << "Failed to get mysql row" << endl;
sendError(ERROR_MYSQL_ROW);
return;
}
}
mysql_free_result(res);
send(outStr);
}
void ZMServer::handleGetEventDates(vector<string> tokens)
{
string outStr("");
if (tokens.size() != 3)
{
sendError(ERROR_TOKEN_COUNT);
return;
}
string monitor = tokens[1];
bool oldestFirst = (tokens[2] == "1");
if (m_debug)
cout << "Loading event dates for monitor: " << monitor << endl;
ADD_STR(outStr, "OK")
MYSQL_RES *res;
MYSQL_ROW row;
string sql("SELECT DISTINCT DATE(E.StartTime) "
"from Events as E inner join Monitors as M on E.MonitorId = M.Id ");
if (monitor != "<ANY>")
sql += "WHERE M.Name = '" + monitor + "' ";
if (oldestFirst)
sql += "ORDER BY E.StartTime ASC";
else
sql += "ORDER BY E.StartTime DESC";
if (mysql_query(&g_dbConn, sql.c_str()))
{
fprintf(stderr, "%s\n", mysql_error(&g_dbConn));
sendError(ERROR_MYSQL_QUERY);
return;
}
res = mysql_store_result(&g_dbConn);
int dateCount = mysql_num_rows(res);
if (m_debug)
cout << "Got " << dateCount << " dates" << endl;
char str[10];
sprintf(str, "%d", dateCount);
ADD_STR(outStr, str)
for (int x = 0; x < dateCount; x++)
{
row = mysql_fetch_row(res);
if (row)
{
ADD_STR(outStr, row[0]) // event date
}
else
{
cout << "Failed to get mysql row" << endl;
sendError(ERROR_MYSQL_ROW);
return;
}
}
mysql_free_result(res);
send(outStr);
}
void ZMServer::handleGetMonitorStatus(void)
{
string outStr("");
ADD_STR(outStr, "OK")
// get monitor list
MYSQL_RES *res;
MYSQL_ROW row;
string sql("SELECT Id, Name, Type, Device, Host, Channel, Function, Enabled "
"FROM Monitors;");
if (mysql_query(&g_dbConn, sql.c_str()))
{
fprintf(stderr, "%s\n", mysql_error(&g_dbConn));
sendError(ERROR_MYSQL_QUERY);
return;
}
res = mysql_store_result(&g_dbConn);
// add monitor count
int monitorCount = mysql_num_rows(res);
if (m_debug)
cout << "Got " << monitorCount << " monitors" << endl;
char str[10];
sprintf(str, "%d", monitorCount);
ADD_STR(outStr, str)
for (int x = 0; x < monitorCount; x++)
{
row = mysql_fetch_row(res);
if (row)
{
string id = row[0];
string type = row[2];
string device = row[3];
string host = row[4];
string channel = row[5];
string function = row[6];
string enabled = row[7];
string name = row[1];
string events = "";
string zmcStatus = "";
string zmaStatus = "";
getMonitorStatus(id, type, device, host, channel, function,
zmcStatus, zmaStatus, enabled);
MYSQL_RES *res2;
MYSQL_ROW row2;
string sql2("SELECT count(if(Archived=0,1,NULL)) AS EventCount "
"FROM Events AS E "
"WHERE MonitorId = " + id);
if (mysql_query(&g_dbConn, sql2.c_str()))
{
fprintf(stderr, "%s\n", mysql_error(&g_dbConn));
sendError(ERROR_MYSQL_QUERY);
return;
}
res2 = mysql_store_result(&g_dbConn);
if (mysql_num_rows(res2) > 0)
{
row2 = mysql_fetch_row(res2);
if (row2)
events = row2[0];
else
{
cout << "Failed to get mysql row" << endl;
sendError(ERROR_MYSQL_ROW);
return;
}
}
ADD_STR(outStr, id)
ADD_STR(outStr, name)
ADD_STR(outStr, zmcStatus)
ADD_STR(outStr, zmaStatus)
ADD_STR(outStr, events)
ADD_STR(outStr, function)
ADD_STR(outStr, enabled)
mysql_free_result(res2);
}
else
{
cout << "Failed to get mysql row" << endl;
sendError(ERROR_MYSQL_ROW);
return;
}
}
mysql_free_result(res);
send(outStr);
}
string ZMServer::runCommand(string command)
{
string outStr("");
FILE *fd = popen(command.c_str(), "r");
char buffer[100];
while (fgets(buffer, sizeof(buffer), fd) != NULL)
{
outStr += buffer;
}
pclose(fd);
return outStr;
}
void ZMServer::getMonitorStatus(string id, string type, string device, string host, string channel,
string function, string &zmcStatus, string &zmaStatus,
string enabled)
{
zmaStatus = "";
zmcStatus = "";
string command(g_binPath + "/zmdc.pl status");
string status = runCommand(command);
if (type == "Local")
{
if (enabled == "0")
zmaStatus = device + "(" + channel + ") [-]";
else if (status.find("'zma -m " + id + "' running") != string::npos)
zmaStatus = device + "(" + channel + ") [R]";
else
zmaStatus = device + "(" + channel + ") [S]";
}
else
{
if (enabled == "0")
zmaStatus = host + " [-]";
else if (status.find("'zma -m " + id + "' running") != string::npos)
zmaStatus = host + " [R]";
else
zmaStatus = host + " [S]";
}
if (type == "Local")
{
if (enabled == "0")
zmcStatus = function + " [-]";
else if (status.find("'zmc -d "+ device + "' running") != string::npos)
zmcStatus = function + " [R]";
else
zmcStatus = function + " [S]";
}
else
{
if (enabled == "0")
zmcStatus = function + " [-]";
else if (status.find("'zmc -m " + id + "' running") != string::npos)
zmcStatus = function + " [R]";
else
zmcStatus = function + " [S]";
}
}
void ZMServer::handleGetEventFrame(vector<string> tokens)
{
static unsigned char buffer[MAX_IMAGE_SIZE];
char str[100];
if (tokens.size() != 4)
{
sendError(ERROR_TOKEN_COUNT);
return;
}
string monitorID(tokens[1]);
string eventID(tokens[2]);
int frameNo = atoi(tokens[3].c_str());
if (m_debug)
cout << "Getting frame " << frameNo << " for event " << eventID
<< " on monitor " << monitorID << endl;
string outStr("");
ADD_STR(outStr, "OK")
// try to find the frame file
string filepath("");
filepath = g_webPath + "/events/" + monitorID + "/" + eventID + "/";
sprintf(str, m_eventFileFormat.c_str(), frameNo);
filepath += str;
FILE *fd;
int fileSize = 0;
if ((fd = fopen(filepath.c_str(), "r" )))
{
fileSize = fread(buffer, 1, sizeof(buffer), fd);
fclose(fd);
}
else
{
cout << "Can't open " << filepath << ": " << strerror(errno) << endl;
sendError(ERROR_FILE_OPEN + string(" - ") + filepath + " : " + strerror(errno));
return;
}
if (m_debug)
cout << "Frame size: " << fileSize << endl;
// get the file size
sprintf(str, "%d", fileSize);
ADD_STR(outStr, str)
// send the data
send(outStr, buffer, fileSize);
}
void ZMServer::handleGetAnalyseFrame(vector<string> tokens)
{
static unsigned char buffer[MAX_IMAGE_SIZE];
char str[100];
if (tokens.size() != 4)
{
sendError(ERROR_TOKEN_COUNT);
return;
}
string monitorID(tokens[1]);
string eventID(tokens[2]);
int frameNo = atoi(tokens[3].c_str());
if (m_debug)
cout << "Getting anaylse frame " << frameNo << " for event " << eventID
<< " on monitor " << monitorID << endl;
// get the 'alarm' frames from the Frames table for this event
MYSQL_RES *res;
MYSQL_ROW row = NULL;
string sql("");
sql += "SELECT FrameId FROM Frames ";
sql += "WHERE EventID = " + eventID + " ";
sql += "AND Type = 'Alarm' ";
sql += "ORDER BY FrameID";
if (mysql_query(&g_dbConn, sql.c_str()))
{
fprintf(stderr, "%s\n", mysql_error(&g_dbConn));
sendError(ERROR_MYSQL_QUERY);
return;
}
res = mysql_store_result(&g_dbConn);
int frameCount = mysql_num_rows(res);
int frameID;
// if the required frame mumber is 0 or out of bounds then use the middle frame
if (frameNo == 0 || frameNo < 0 || frameNo > frameCount)
frameNo = (frameCount / 2) + 1;
// move to the required frame in the table
for (int x = 0; x < frameNo; x++)
{
row = mysql_fetch_row(res);
}
if (row)
{
frameID = atoi(row[0]);
}
else
{
cout << "handleGetAnalyseFrame: Failed to get mysql row for frameNo " << frameNo << endl;
sendError(ERROR_MYSQL_ROW);
return;
}
string outStr("");
ADD_STR(outStr, "OK")
// try to find the analyse frame file
string filepath("");
filepath = g_webPath + "/events/" + monitorID + "/" + eventID + "/";
sprintf(str, m_analyseFileFormat.c_str(), frameID);
filepath += str;
FILE *fd;
int fileSize = 0;
if ((fd = fopen(filepath.c_str(), "r" )))
{
fileSize = fread(buffer, 1, sizeof(buffer), fd);
fclose(fd);
}
else
{
cout << "Can't open " << filepath << ": " << strerror(errno) << endl;
sendError(ERROR_FILE_OPEN + string(" - ") + filepath + " : " + strerror(errno));
return;
}
if (m_debug)
cout << "Frame size: " << fileSize << endl;
// get the file size
sprintf(str, "%d", fileSize);
ADD_STR(outStr, str)
// send the data
send(outStr, buffer, fileSize);
}
void ZMServer::handleGetLiveFrame(vector<string> tokens)
{
static unsigned char buffer[MAX_IMAGE_SIZE];
char str[100];
// we need to periodically kick the DB connection here to make sure it
// stays alive because the user may have left the frontend on the live
// view which doesn't query the DB at all and eventually the connection
// will timeout
kickDatabase(m_debug);
if (tokens.size() != 2)
{
sendError(ERROR_TOKEN_COUNT);
return;
}
int monitorID = atoi(tokens[1].c_str());
if (m_debug)
cout << "Getting live frame from monitor: " << monitorID << endl;
string outStr("");
ADD_STR(outStr, "OK")
// echo the monitor id
sprintf(str, "%d", monitorID);
ADD_STR(outStr, str)
// try to find the correct MONITOR
MONITOR *monitor;
if (m_monitors.find(monitorID) != m_monitors.end())
monitor = m_monitors[monitorID];
else
{
sendError(ERROR_INVALID_MONITOR);
return;
}
// are the data pointers valid?
if (monitor->shared_data == NULL || monitor->shared_images == NULL)
{
sendError(ERROR_INVALID_POINTERS);
return;
}
// read a frame from the shared memory
int dataSize = getFrame(buffer, sizeof(buffer), monitor);
if (m_debug)
cout << "Frame size: " << dataSize << endl;
if (dataSize == 0)
{
// not really an error
outStr = "";
ADD_STR(outStr, "WARNING - No new frame available");
send(outStr);
return;
}
// add status
ADD_STR(outStr, monitor->status)
// send the data size
sprintf(str, "%d", dataSize);
ADD_STR(outStr, str)
// send the data
send(outStr, buffer, dataSize);
}
void ZMServer::handleGetFrameList(vector<string> tokens)
{
string eventID;
string outStr("");
if (tokens.size() != 2)
{
sendError(ERROR_TOKEN_COUNT);
return;
}
eventID = tokens[1];
if (m_debug)
cout << "Loading frames for event: " << eventID << endl;
ADD_STR(outStr, "OK")